import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

/*
 * [4] 버튼에 ActionListener()를 달고, 액션 이벤트가 발생하면
 *  ActionPerformed() 메소드가 호출되어 버튼의 글자를 [삽입]/[수정] 토글 시키기
 */
class MyAction implements ActionListener { // 액션이벤트 처리하는 루틴 리스너를 상속받기
 public void actionPerformed(ActionEvent e) { // 액션이벤트가 발생하면 호출되는 메소드
  JButton btn = (JButton) e.getSource();
  if(btn.getText().equals("삽입")) // 삽입과 같으면 수정으로
   btn.setText("수정");
  else
   btn.setText("삽입"); // 수정과 같으면 삽입으로
 }
}
public class Action1 extends JFrame {
 Action1() {
  this.setTitle("NULL 레이아웃 예제");
  this.setSize(300, 300);
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setLayout(new FlowLayout()); // 프레임에 대한 배치관리자 설정
  
  //================== 코드 작성 구간 ==================
  // 1) 버튼 만들기
  JButton btn1 = new JButton("삽입");
  // 2) 버튼에 액션리스너 만들기
  btn1.addActionListener(new MyAction());
  this.add(btn1);
  //==============================================
  
  this.setVisible(true);
 }

 public static void main(String[] args) {
  new Action1();
 }

}

 

----------------------------------------------------------------------------------------- 배경 색 추가

class MyAction implements ActionListener { // 액션이벤트 처리하는 루틴 리스너를 상속받기
 public void actionPerformed(ActionEvent e) { // 액션이벤트가 발생하면 호출되는 메소드
  JButton btn = (JButton) e.getSource();
  if(btn.getText().equals("삽입")) { // 삽입과 같으면 수정으로
   btn.setText("수정");
   btn.setBackground(Color.RED);
  }
  else {
   btn.setText("삽입"); // 수정과 같으면 삽입으로
   btn.setBackground(Color.BLUE);
  }
 }
}

+ Recent posts