▷ JTextField
→ 텍스트 한 줄을 입력 가능한 컴포넌트
→ BorderLayout에 바로 부착할 경우 기본 생성자로 생성 가능하지만, 주로 JPanel 등에 부착해서 사용할 때
생성자 파라미터로 컬럼길이를 전달해야 함
→ getText() 메서드로 입력된 텍스트를 가져오고, setText() 메서드로 새 텍스트를 표시할 수 있다.
→ ActionListener를 연결하여 텍스트 입력 후 엔터키에 대한 동작 처리 가능
→ KeyListener를 연결하면 키보드에서 눌러지는 키에 대한 동작 처리 가능
ex_component.Clone_Ex1
package ex_component;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Clone_Ex1 {
JTextField tf; // 다른 메서드에서 접근을 위해 멤버변수로 선언
public Clone_Ex1() {
showFrame();
}
public void showFrame() {
JFrame f = new JFrame("Clone_Ex1");
f.setBounds(600,300,600,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tf = new JTextField();
f.add(tf, BorderLayout.CENTER); // 기본이 CENTER라서 생략가능.
JButton btn = new JButton("입력");
f.add(btn, BorderLayout.SOUTH);
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// String str = tf.getText();
// System.out.println(str);
// tf.setText("");
// tf.requestFocus();
printMessage();
}
});
tf.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// String str = tf.getText();
// System.out.println(str);
// tf.setText("");
// tf.requestFocus();
printMessage();
}
});
f.setVisible(true);
}
public void printMessage() {
String str = tf.getText();
System.out.println(str);
tf.setText("");
tf.requestFocus();
}
public static void main(String[] args) {
new Clone_Ex1();
}
}
수업시간에 한 내용을 Clone 파일을 만들어서 작성함
JTextField 객체를 사용하여 텍스트 입력이 가능하고
getText()와 setText()를 통해서 제어 가능
'JAVA' 카테고리의 다른 글
Android (0) | 2022.02.28 |
---|---|
swing (Container) (0) | 2022.02.26 |
swing (Layout 변경2) (0) | 2022.02.26 |
swing (Layout 변경) (0) | 2022.02.26 |
swing (Layout) (0) | 2022.02.26 |