[JAVA/자바] 액션리스너를 이용한 클릭(이미지 변환) 예제 프로그램
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
class MyAction implements ActionListener{
public void actionPerformed(ActionEvent e){
JButton btn = (JButton) e.getSource();
if(btn.getText().equals("삽입")){
btn.setText("수정");
ImageIcon img1 = new ImageIcon("thm.jpg");
JButton b52 = new JButton(img1);
btn.add(b52,BorderLayout.CENTER);
}
else{
btn.setText("삽입");
ImageIcon img = new ImageIcon("thm1.jpg");
JButton b51 = new JButton(img);
btn.add(b51,BorderLayout.CENTER);
}
}
}
public class Action1 extends JFrame {
Action1() {
this.setTitle("토글 키 예제");
this.setSize(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this.setLayout(new FlowLayout()); // 프레임에 대한 배치관리자 설정
JPanel btn = new JPanel();
btn.setLayout(new BorderLayout());
JButton btn1 = new JButton("삽입");
btn.add(btn1,BorderLayout.NORTH);
ImageIcon img1 = new ImageIcon("thm.jpg"); // 이미지 파일 이름
JButton b52 = new JButton(img1);
btn.add(b52,BorderLayout.CENTER);
ImageIcon img = new ImageIcon("thm1.jpg"); // 이미지 파일 이름
JButton b51 = new JButton(img);
btn.add(b51,BorderLayout.CENTER);
btn1.addActionListener(new MyAction());
this.add(btn);
this.setVisible(true);
}
public static void main (String[] args) {
new Action1();
}
}