본문 바로가기

프로그래밍/JAVA

자바 액션리스너 예제 - JAVA example of action listener

첨부 이미지


import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel; //필요한 부분을 임포트 합니다.


public class Assign extends JFrame implements ActionListener {    //JFrame을 extends하고 ActionListener를 implements 액션리스너를 사용해서 버튼에 액션을 부여하려면 액션리스너를 사용해야됩니다.

 private JPanel panel = new JPanel();  //패널생성
 private JButton yellow = new JButton("Yellow");  //버튼생성
 private JButton red = new JButton("RED");  
 private JButton blue = new JButton("BLUE");

 public Assign(){  //생성자
  init();
  finale();
 }
 
 public void init(){  //초기값을 정의
  yellow.setBackground(Color.yellow);  각버튼의 배경생을 지정 하고 액션리스너에 추가
  yellow.addActionListener(this);
  red.setBackground(Color.red);
  red.addActionListener(this);
  blue.setBackground(Color.blue);
  blue.addActionListener(this);
  setSize(250,200);   //프레임의 사이즈 정의
  panel.setSize(250, 100);   //패널의 사이즈 정의
  panel.setLayout(new FlowLayout());   //레이아웃을 정의
  panel.add(yellow);    //패널에 버튼들을 답니다.
  panel.add(red);
  panel.add(blue);
  add(panel);


 }

 public void finale(){
  
  setVisible(true);   //마지막에 프레임이 보이게 설정
  addWindowListener(new WindowAdapter(){
   @Override
   public void windowClosing(WindowEvent e) {   //x버튼을 눌렀을때프로세스가 완전히 종료되도록..
    // TODO Auto-generated method stub
    super.windowClosing(e);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   }
  });

 }
 @Override
 public void actionPerformed(ActionEvent e) {
  // TODO Auto-generated method stub
  if(e.getSource().equals(yellow)){   //yellow버튼이 눌렸을때 할일
   panel.setBackground(Color.yellow);
  }
  if(e.getSource().equals(red)){   //각버튼...이 눌렸을때 할일..
   panel.setBackground(Color.red);
  }
  if(e.getSource().equals(blue)){
   panel.setBackground(Color.blue);
  }
 }

 public static void main(String[] args){
  Assign test = new Assign();
 }

}


'프로그래밍 > JAVA' 카테고리의 다른 글

자바 쓰레드 예제(JAVA Thread example)  (0) 2010.11.04