기초 컴포넌트들

Dec 29, 2023
기초 컴포넌트들

1. 레이블(JLabel) : 텍스트를 표시할 수 있는 공간

사용자를 위한 정보 또는 계산의 결과를 표시하는데 사용
텍스트와 이미지를 동시에 표기 가능
폰트의 종류, 크기, 색상 등은 변경 가능
 

레이블 사용 방법

1) 객체를 생성할 때 텍스트를 생성자에게 넘김


package ex09; import javax.swing.*; import java.awt.*; public class LabelTest extends JFrame { private JPanel panel; private JLabel label1, label2; public LabelTest() { setTitle("레이블 테스트"); setSize(400, 150); panel = new JPanel(); label1 = new JLabel("Color Label"); label1.setForeground(Color.BLUE); label2 = new JLabel("Font Label"); label2.setFont(new Font("Arial", Font.ITALIC, 30)); label2.setForeground(Color.ORANGE); panel.add(label1); panel.add(label2); add(panel); setVisible(true); } public static void main(String[] args) { LabelTest t = new LabelTest(); } }
notion image

 
label = new JLabel(”텍스트");

2) 객체를 생성하고 텍스트를 설정

label = new JLabel(”");
label.setText(”텍스트");

3) 폰트, 색깔 설정

label.setForeground(Color.색깔); label.setFont(new Font("폰트 이름",스타일, 폰트 크기));

레이블에 이미지 표시하기


package ex09; import javax.swing.*; public class ImageLabelTest extends JFrame { private JPanel panel; private JLabel label; private JButton button; public ImageLabelTest() { setTitle("레이블 테스트"); setSize(400, 250); panel = new JPanel(); label = new JLabel("animal"); ImageIcon icon = new ImageIcon("D:/workspace/java_lec/study/animal.png"); label.setIcon(icon); button = new JButton("자세한 정보를 보려면 클릭하세요!"); panel.add(label); panel.add(button); add(panel); setVisible(true); } public static void main(String[] args) { ImageLabelTest t = new ImageLabelTest(); } }
notion image

 
ImageIcon icon = new ImageIcon(”이미지 파일의 경로");
label.setIcon(icon);
png, gif, jpeg 이미지 파일을 읽을 수 있음
이미지가 설정되면 레이블의 텍스트는 오른쪽에 표시
 

2. 텍스트필드(JTextField)

사용자가 한 줄의 텍스트를 입력할 수 있는 공간
JTextField 클래스로서 제공됨

텍스트 필드 생성하기


package ex09; import javax.swing.*; public class LoginWindow extends JFrame { public LoginWindow() { setTitle("login window"); setSize(300, 150); JPanel panel = new JPanel(); add(panel); panel.add(new JLabel("id ")); panel.add(new JTextField(20)); panel.add(new JLabel("pass")); panel.add(new JPasswordField(20)); JButton login = new JButton("login"); panel.add(login); JButton cancel = new JButton("cancel"); panel.add(cancel); setVisible(true); } public static void main(String[] args) { new LoginWindow(); } }
notion image

 
JTextField 텍스트필드명 = new JTextField(크기); // 텍스트 생성 tf.setTxt("텍스트"); // 텍스트 설정 System.out.println(텍스트필드명.getText()); // 텍스트 가져오기
사용자로부터 입력받을 때
입력후 enter > 액션 이벤트 발생
액션 리스너를 정의하고 actionPerformed()에서 액션 이벤트를 처리함
텍스트필드명.requestFocus();
 

2-1. 자식클래스 : JPasswordField, JFormattedTextField

 
JPasswordField : 사용자가 입력한 비밀번호를 나타내기 위한 텍스트 필드
일반 텍스트 필드와 달리, 입력된 텍스트가 화면에 표시되지 않음
대신 '*'이나 다른 문자로 마스킹
JPasswordField passwordField = new JPasswordField();
 
비밀번호를 가져올 때에는 getPassword() 메서드를 사용, 반환된 값은 문자 배열
char[] password = passwordField.getPassword();
 
JFormattedTextField : 특정 형식을 따르는 입력을 받기 위한 텍스트 필드
형식을 지정하여 사용자에게 입력을 요청
MaskFormatter formatter = new MaskFormatter("(###) ###-####"); JFormattedTextField phoneField = new JFormattedTextField(formatter);
 

3. 버튼(JButton)

클릭되면 어떤 동작을 실행하는 버튼
버튼 안의 텍스트, 버튼 텍스트의 폰트, 버튼의 전경색, 배경색, 버튼의 상태 설정 가능
 
JBotton : 가장 일반적인 버튼
JCheckBox : 체크박스 버튼
JRadioButton : 그룹 중의 하나의 버튼만 체크할 수 있는 버튼
JToggleButton : 2가지 상태를 가지고 토글이 가능한 버튼

버튼 만들기


package ex09; import javax.swing.*; public class TempConverter extends JFrame { public TempConverter() { JPanel panel = new JPanel(); add(panel); JLabel label1 = new JLabel("화씨 온도"); JLabel label2 = new JLabel("섭씨 온도"); JTextField field1 = new JTextField(15); JTextField field2 = new JTextField(15); JButton button = new JButton("변환"); panel.add(label1); panel.add(field1); panel.add(label2); panel.add(field2); panel.add(button); setSize(300, 150); setTitle("온도변환기"); setVisible(true); } public static void main(String[] args) { TempConverter t = new TempConverter(); } }
notion image
 
package ex09; import javax.swing.*; public class MyFrame10 extends JFrame { public MyFrame10() { setSize(600, 150); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("MyFrame"); JPanel panel = new JPanel(); JPanel panelA = new JPanel(); JPanel panelB = new JPanel(); JLabel label1 = new JLabel("자바 피자에 오신 것을 환영합니다. 피자의 종류를 선택하시오."); panelA.add(label1); JButton buttton1 = new JButton("콤보피자"); JButton buttton2 = new JButton("포테이토피자"); JButton buttton3 = new JButton("불고기피자"); panelB.add(buttton1); panelB.add(buttton2); panelB.add(buttton3); JLabel label2 = new JLabel("개수"); JTextField field1 = new JTextField(10); panelB.add(label2); panelB.add(field1); panel.add(panelA); panel.add(panelB); add(panel); setVisible(true); } public static void main(String[] args) { MyFrame10 f = new MyFrame10(); } }
notion image

1) JBotton 객체 생성하기 → new해서 버튼 생성
2) add(객체 변수); → 프레임에 버튼 추가
 
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class ButtonExample extends Application { public void start(Stage primaryStage) { primaryStage.setTitle("버튼 예제"); // 버튼 텍스트, 폰트, 전경색, 배경색 설정 String buttonText = "클릭하세요"; String buttonFont = "Arial"; String buttonForeground = "white"; String buttonBackground = "blue"; // 버튼 생성 Button button = new Button(buttonText); // 버튼 속성 설정 button.setStyle("-fx-font-family: " + buttonFont + "; -fx-text-fill: " + buttonForeground + "; -fx-background-color: " + buttonBackground + ";"); // 버튼 이벤트 핸들링 button.setOnAction(e -> System.out.println("버튼이 클릭되었습니다.")); // 버튼 상태 설정 (활성화 또는 비활성화) // button.setDisable(true); // 비활성화 // button.setDisable(false); // 활성화 (기본값) // 레이아웃 설정 StackPane root = new StackPane(); root.getChildren().add(button);
import javax.swing.JButton; import javax.swing.JFrame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ButtonExample { public static void main(String[] args) { // 프레임 생성 JFrame frame = new JFrame("버튼 예제"); frame.setSize(300, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 버튼 생성 JButton button = new JButton("클릭하세요"); // 버튼 이벤트 핸들링 button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("버튼이 클릭되었습니다."); } }); // 버튼 크기 및 위치 설정 button.setBounds(50, 50, 200, 50); // 프레임에 버튼 추가 frame.add(button); // 프레임을 보이도록 설정 frame.setLayout(null); frame.setVisible(true); } }

계산기 틀 만들기


package ex09; import javax.imageio.stream.ImageInputStream; import javax.swing.*; import java.awt.*; public class CalculatorFrame extends JFrame { private JPanel panel; private JTextField tField; private JButton[] buttons; private String[] labels = { "Backspace", "", "", "CE", "C", "7", "8", "9", "/", "sqrt", "4", "5", "6", "x", "%", "1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "=" }; public CalculatorFrame() { tField = new JTextField(35); panel = new JPanel(); tField.setText("0."); tField.setEnabled(false); panel.setLayout(new GridLayout(0, 5, 3, 3)); buttons = new JButton[25]; int index = 0; for (int row = 0; row < 5; row++) { for (int cols = 0; cols < 5; cols++) { buttons[index] = new JButton(labels[index]); if(cols >= 3) { buttons[index].setForeground(Color.red); } else { buttons[index].setForeground(Color.blue); } buttons[index].setBackground(Color.yellow); panel.add(buttons[index]); index++; } add(tField, BorderLayout.NORTH); add(panel, BorderLayout.CENTER); setVisible(true); pack(); } } public static void main(String[] args) { CalculatorFrame c = new CalculatorFrame(); } }
notion image

 
Share article
RSSPowered by inblog