JAVA/GUI - Swing
JTextField를 활용한 한 줄의 문자열을 입력
DesignatedRoom
2020. 10. 16. 13:22
TextFieldFrame.java
위에서 버튼들에 대한 이벤트 등록하는 방법은 세 가지 방법이 있음을 Frame에서 보았다.여기서는 마우스에 대한 이벤트를 별 개의 클래스로 빼서 처리를 하는 방법을 사용했다.
소스 코드
더보기
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class TextFieldFrame extends JFrame
{
private static final long serialVersionUID = 1L;
private JTextField textField1;
private JTextField textField2;
private JTextField textField3;
private JPasswordField passwordField; // 패스워드 입력
public TextFieldFrame()
{
super( "JTextField and JPasswordField 테스트" );
setLayout( new FlowLayout() );
// construct textfield with 10 columns
textField1 = new JTextField( 10 );
add( textField1 );
// construct textfield with default text
textField2 = new JTextField( "문자를 입력 하세요." );
add( textField2 );
// construct textfield with default text and 21 columns
textField3 = new JTextField( "편집 불 가능", 21 );
textField3.setEditable( false ); // 비활성화
add( textField3 );
// construct passwordfield with default text
passwordField = new JPasswordField( "Hidden text" );
add( passwordField ); // add passwordField to JFrame
// TextFieldHandler: 개발자가 정의하는 이벤트 처리 클래스
TextFieldHandler handler = new TextFieldHandler();
textField1.addActionListener( handler );
textField2.addActionListener( handler );
textField3.addActionListener( handler );
passwordField.addActionListener( handler );
}
// ActionListener : 마우스 클릭 전문 처리
private class TextFieldHandler implements ActionListener{
// process textfield events
// ActionEvent : 이벤트가 발생한 객체의 정보를 가지고 있음
public void actionPerformed( ActionEvent event ){
String string = "";
// event.getSource(): 객체명 추출 가능
// event.getActionCommand(): 입력 문자열 추출
if ( event.getSource() == textField1 ){
string = String.format( "textField1: %s", event.getActionCommand() );
}else if ( event.getSource() == textField2 ){
string = String.format( "textField2: %s", event.getActionCommand() );
}else if ( event.getSource() == textField3 ){
string = String.format( "textField3: %s", event.getActionCommand() );
}else if ( event.getSource() == passwordField ){
string = String.format(
"passwordField: %s",
new String( passwordField.getPassword() )
);
}
// 이벤트 정보 출력
JOptionPane.showMessageDialog( null, string );
}
}
}
TextFieldTest.java
소스 코드
더보기
import javax.swing.JFrame;
public class TextFieldTest{
public static void main( String args[] ){
TextFieldFrame textFieldFrame = new TextFieldFrame();
textFieldFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
textFieldFrame.setSize( 325, 100 );
textFieldFrame.setVisible( true );
}
}
프로그램 실행결과