โญ์ด๋ฒคํธ ๋ฆฌ์ค๋ ์์ฑ๊ณผ์
1. ์ด๋ฒคํธ ๋ฆฌ์คํฐ ํด๋์ค ์์ฑ
ActionListener์์ actionPerformed()๋ผ๋ ๋ฉ์๋๋ง์ด ์ ์๋์ด ์๋ค.
์ด ๋ฉ์๋๋ ์ก์ ์ด๋ฒคํธ๊ฐ ๋ฐ์ํ ๋๋ง๋ค ํธ์ถ๋๋ค.
ActionListener ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํ๋ MyListener๋ผ๊ณ ํ๋ ํด๋์ค๋ฅผ ์์ฑํ๋ฉด ๋ค์๊ณผ ๊ฐ๋ค.class MyListener implements ActionListener { //์ก์ ์ด๋ฒคํธ๊ฐ ๋ฐ์ํ๋ฉด ํธ์ถ๋๋ค. public void actionPerformed(ActionEvent e) { ... //Action ์ด๋ฒคํธ๋ฅผ ์ฒ๋ฆฌํ๋ ์ฝ๋๊ฐ ์ฌ๊ธฐ์ ๋ค์ด๊ฐ๋ค. } }
2. ์ด๋ฒคํธ ๋ฆฌ์คํฐ ์ด๋ฒคํธ ์์ค์ ๋ฑ๋กํ๋ค.
์ด๋ฒคํธ ๋ฆฌ์ค๋๋ ๊ฐ์ฒด๋ฅผ ์ด๋ฒคํธ ์์ค์ ๋ฑ๋กํ๋ ๋จ๊ณ
public class MyFrame extends JFrame //ํ๋ ์ ์์ํด์ MyFrame ์ ์ธ public MyFrame() { //์์ฑ์ ์ปดํฌ๋ํธ๋ฅผ ์์ฑํ๊ณ ์ถ๊ฐํ๋ค. { JButton button = new JButton(); //๋ฒํผ์์ฑ button.addActionListener(new MyListener()); //์ด๋ฒคํธ๋ฆฌ์ค๋ ๊ฐ์ฒด๋ฅผ new ๋ฅผ ์ด์ฉํ์ฌ์ ์์ฑํ๊ณ ๋ฒํผ์ ์ด๋ฒคํธ ๋ฆฌ์ค๋ ๊ฐ์ฒด๋ฅผ ๋ฑ๋ก } }
3. ์ด๋ฒคํธ ๊ฐ์ฒด
์ด๋ฒคํธ ๋ฆฌ์ค๋๋ ์ด๋ฒคํธ ๊ฐ์ฒด๋ฅผ ๋งค๊ฐ๋ณ์๋ก ๊ฐ์ง๋ค.์ด๋ฒคํธ ๊ฐ์ฒด๋ฅผ ๋ฐ์ํ ์ด๋ฒคํธ์ ๋ํ ๋ชจ๋ ์ ๋ณด๋ฅผ ๋ฆฌ์ค๋๋ก ์ ๋ฌ
๋ชจ๋ ๊ฐ์ฒด๋ EventObject ํด๋์ค๋ฅผ ์์๋ฐ๋๋ค.
EventObject ํด๋์ค๋ getSource()๋ฉ์๋๋ฅผ ๊ฐ์ง๊ณ ์๋๋ฐ ์ด ๋ฉ์๋๋ ์ด๋ฒคํธ ๋ฐ์ํ ์ด๋ฒคํธ ์์ค๋ฅผ ๋ฐํํ๋ค.
๊ทธ๋ฆฌ๊ณ Object ํ์ ์ผ๋ก ๋ฐํํ๋ฏ๋ก ์ด๊ฒ์ ํ์ํ ํ์ ์ผ๋ก ํ๋ณํํ์ฌ์ ์ฌ์ฉํ๋ฉด ๋๋ค.public void actionPerformed(MouseEvent e){ button = (JButton)e.getSource(); //ํ๋ณํ }
โญ๋ฆฌ์ค๋๋ฅผ ๋ ๋ฆฝ์ ์ธ ํด๋์ค๋ก ์์ฑ
- ๋ฒํผ์ด ๋๋ ค์ง๋ฉด ๋ฒํผ์ ํ ์คํธ๊ฐ ๋ณ๊ฒฝ๋๋ ํ๋ก๊ทธ๋จ์ ์์ฑ
-MyListener ํด๋์ค ์์ฑimport javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; class MyListener implements ActionListener { //๋ณ๋์ ํด๋์ค๋ก ์ ์ํ๋ค.ActionListner ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํ๋ค. @Override public void actionPerformed(ActionEvent e) { // ... Action ์ด๋ฒคํธ๋ฅผ ์ฒ๋ฆฌํ๋ ์ฝ๋๊ฐ ์ฌ๊ธฐ์ ๋ค์ด๊ฐ๋ค. JButton button = (JButton)e.getSource(); button.setText("๋ง์นจ๋ด ๋ฒํผ์ด ๋๋ฌ์ก์ต๋๋ค."); } }
- ActionEventTest ํด๋์ค ์์ฑ
import javax.swing.*; import java.awt.*; class MyFrame extends JFrame { //ํ๋ ์ ์์ํด์ MyFrame ์ ์ธ private JButton button; public MyFrame() { //์์ฑ์ ์ปดํฌ๋ํธ๋ฅผ ์์ฑํ๊ณ ์ถ๊ฐํ๋ค. this.setSize(300,200); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("์ด๋ฒคํธ์์ "); this.setLayout(new FlowLayout()); button = new JButton("๋ฒํผ์ ๋๋ฅด์์ค"); button.addActionListener(new MyListener()); //๋ฒํผ์ ์ด๋ฒคํธ ๋ฆฌ์ค๋ ๋ฑ๋ก this.add(button); this.setVisible(true); //์ด๋ฒคํธ๋ฆฌ์ค๋ ๊ฐ์ฒด๋ฅผ new ๋ฅผ ์ด์ฉํ์ฌ์ ์์ฑํ๊ณ ๋ฒํผ์ ์ด๋ฒคํธ ๋ฆฌ์ค๋ ๊ฐ์ฒด๋ฅผ ๋ฑ๋ก //... } } public class P395_ActionEventTest { public static void main(String[] args) { MyFrame t = new MyFrame(); } }
- ์ฌ์ฉ์๊ฐ ๋ฒํผ์ ํด๋ฆญํ๋ ๊ฒฝ์ฐ
- ์ฌ์ฉ์๊ฐ ๋ฉ๋ด ํญ๋ชฉ์ ์ ํํ๋ ๊ฒฝ์ฐ
- ์ฌ์ฉ์๊ฐ ํ ์คํธ ํ๋์์ ์ํฐํค๋ฅผ ๋๋ฅด๋ ๊ฒฝ์ฐ
- ์ด๋ฒคํธ๋ฅผ ์ฒ๋ฆฌํ๊ธฐ ์ํด์๋ ๋ฆฌ์ค๋ ์ธํฐํ์ด์ค์์ ์ ์๋์ด ์๋ ๋ชจ๋ ๋ฉ์๋๋ฅผ ๊ตฌํํด์ผ ํด์ ๋ด๊ฐ ์์ฑํ๊ณ ์ถ์ ๋ฉ์๋๊ฐ 1๊ฐ ๋ฟ์ด๋ผ๋ ๋ชจ๋ ๋ฉ์๋๋ฅผ ๊ตฌํํด์ผ ํ๋ ๋ถํธํจ์ด ์์๋ค.
- ์ด๋ฌํ ๋ถํธํจ์ ํด์ํ๊ธฐ ์ํ ๊ฒ์ด ๊ฐ ๋ฆฌ์ค๋์ ๋์ํ๋ ์ด๋ํฐ ํด๋์ค
- ๋ฆฌ์ค๋๋ ์ธํฐํ์ด์ค์ด๊ณ ์ด๋ํฐ๋ ํด๋์ค์ ํํ๋ก ์ ๊ณต๋๋ค.
- ๋ฆฌ์ค๋๋ฅผ ์ฌ์ฉํ ๋๋ implement๋ฅผ, ์ด๋ํฐ๋ฅผ ์ฌ์ฉํ ๋๋ extends
โญ ์ด๋ํฐ๋ฅผ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ
- extends KeyAdaptor ๋ฅผ ์ฌ์ฉ