이벤트 처리 과정
예를 들면 버튼을 누른다 → 이벤트 객체가 발생한다 → 이벤트 처리.
이벤트 처리 과정에는
우선 버튼을 누를 수 있는 Frame 을 만들어 주고 → 이벤트리스너 클래스를 작성한다.(ActionListener 를 implements 해준다)
ex)
class MyListener implements ActionListener{ //JButton이 눌릴때마다 액션.
@Override
public void actionPerformed(ActionEvent e) {//ActionEvent를 처리할 수 있는 메 //소드를
// FIXME Auto-generated method stub // 가지는 인터페이스는 ActionListener
// if(e.getSource() == button)
// if(button.getText().equals("버튼"))
// button.setText("눌림");
// else if(button.getText().equals("눌림"))
// button.setText("버튼");
** 이벤트를 발생시키는 근원지(컴포넌트) 생성.
class MyFrame extends JFrame
{
public MyFrame(){
this.setTitle("상속 받아서 만듬");
this.setSize(500, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
label = new JLabel("안녕하세요");
JButton button1 = new JButton("버튼1");
button1.addActionListener(new MyListener); //이벤트 리스너등록!
panel.add(label);
panel.add(button1);
this.add(panel);
this.setVisible(true);
}
그런데 frame과 이벤트 처리클래스가 서로 독립적일때는 이벤트처리 함수에서 컴포넌트에 접근이 불가능하다.
그래서 컴포넌트 참조변수들을 멤버로 빼주고 이벤트처리 클래스를 Frame클래스의 내부클래스로 만들면 이벤트처리 메소드에서 컴포넌트에 접근이 가능함.
위코드로 예를 들자면..
class MyFrame extends JFrame
{
private JButton button1; //메소드에서 컴포넌트에 접근이 가능함.
private JPanel panel;
private JLabel label;
private MyListener myListener = new MyListener();
public MyFrame(){
this.setTitle("상속 받아서 만듬");
this.setSize(500, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
label = new JLabel("안녕하세요");
button1 = new JButton("버튼1");
button1.addActionListener(myListener);
panel.add(label);
panel.add(button1);
this.add(panel);
this.setVisible(true);
}
class MyListener implements ActionListener{ //JButton이 눌릴때마다 액션.
@Override
public void actionPerformed(ActionEvent e) {//ActionEvent를 처리할 수 있는 메소드를
// FIXME Auto-generated method stub // 가지는 인터페이스는 ActionListener
if(e.getSource() == button)
if(button.getText().equals("버튼"))
button.setText("눌림");
else if(button.getText().equals("눌림"))
button.setText("버튼");
}
}
public class Test {
public static void main(String[] args) {
MyFrame mf = new MyFrame();
결과는
'[JAVA]' 카테고리의 다른 글
[JAVA]10월 13일 배치 관리자 FlowLayout, BorderLayout, GridLayout (0) | 2015.10.13 |
---|---|
[JAVA]10월 13일 이벤트 처리 Action, Key, Mouse, MouseMotion (0) | 2015.10.13 |
[JAVA]10월 12일 GUI, 그래픽 사용자 인터페이스 (0) | 2015.10.12 |
[JAVA]10월 7일 네트워크 프로그래밍 TCP (단체 채팅 서버코드 예제) (0) | 2015.10.07 |
[JAVA]10월 5일 네트워크 프로그래밍 (0) | 2015.10.05 |