출처는 하단에 명시 해 놓았고 소스는 직접 구현 해봄
1. 첫번째 방법
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; @SuppressWarnings("serial") public class ExJButtonActionListener extends JFrame { class MyActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "버튼을 누르셨군요", "Message", JOptionPane.ERROR_MESSAGE); } } public ExJButtonActionListener() { JButton btn = new JButton("버튼"); ActionListener listener = new MyActionListener(); btn.addActionListener(listener); JPanel panel = new JPanel(); panel.add(btn); Container contentPane = getContentPane(); contentPane.add(panel, BorderLayout.CENTER); setTitle("ExJButtonActionListener"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(300, 300); setVisible(true); } public static void main(String[] args) { new ExJButtonActionListener(); } } | cs |
2. 두번째 방법 (anonymous 클래스 사용)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; @SuppressWarnings("serial") public class ExJButtonActionListener2 extends JFrame { public ExJButtonActionListener2() { JButton btn = new JButton("버튼"); btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "버튼을 누르셨군요", "Message", JOptionPane.ERROR_MESSAGE); } }); JPanel panel = new JPanel(); panel.add(btn); Container contentPane = getContentPane(); contentPane.add(panel, BorderLayout.CENTER); setTitle("ExJButtonActionListener"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(300, 300); setVisible(true); } public static void main(String[] args) { new ExJButtonActionListener(); } } | cs |
출처 : ActionListener 사용법
반응형
'JAVA' 카테고리의 다른 글
[JAVA][SWING]setBorder TitledBorder LineBorder (0) | 2018.09.13 |
---|---|
[JAVA][SWING]BorderLayout in BorderLayout (0) | 2018.09.13 |
[JAVA][eclipse][ERROR] eclipse PHOTON 설치 오류 (1) | 2018.09.11 |
진행바,프로그레스바(JProgressBar) (0) | 2018.09.11 |
[JAVA][SWING] 팝업 JOptionPane (showInputDialog, showConfirmDialog, showMessageDialog) (0) | 2018.09.11 |