Java
Action Listener 작성하기
_mojo_
2021. 7. 28. 00:22
독립된 클래스로 Action 이벤트의 리스너 작성 코드
import javax.swing.*; // JFrame
import java.awt.*; // Container
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class IndepClassListener extends JFrame{
public IndepClassListener() {
setTitle("Action 이벤트 리스너 예제");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c=getContentPane();
c.setLayout(new FlowLayout());
JButton btn=new JButton("Action");
btn.addActionListener((ActionListener) new MyActionListener());
c.add(btn);
setSize(350,150);
setVisible(true);
}
public static void main(String [] args) {
new IndepClassListener();
}
}
class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JButton b=(JButton)e.getSource();
if(b.getText().equals("Action")) {
b.setText("액션");
}
else {
b.setText("Action");
}
}
}
내부 클래스로 Action 이벤트 리스너 만들기
import javax.swing.*; // JFrame
import java.awt.*; // Container
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class IndepClassListener extends JFrame{
public IndepClassListener() {
setTitle("Action 이벤트 리스너 예제");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c=getContentPane();
c.setLayout(new FlowLayout());
JButton btn=new JButton("Action");
btn.addActionListener((ActionListener) new MyActionListener());
c.add(btn);
setSize(350,150);
setVisible(true);
}
private class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JButton b=(JButton)e.getSource();
if(b.getText().equals("Action")) {
b.setText("액션");
}
else {
b.setText("Action");
}
}
}
public static void main(String [] args) {
new IndepClassListener();
}
}
익명 클래스로 Action 이벤트 리스너 만들기
import javax.swing.*; // JFrame
import java.awt.*; // Container
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class IndepClassListener extends JFrame{
public IndepClassListener() {
setTitle("Action 이벤트 리스너 예제");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c=getContentPane();
c.setLayout(new FlowLayout());
JButton btn=new JButton("Action");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JButton b=(JButton)e.getSource();
if(b.getText().equals("Action")) {
b.setText("액션");
}
else {
b.setText("Action");
}
}
});
c.add(btn);
setSize(350,150);
setVisible(true);
}
public static void main(String [] args) {
new IndepClassListener();
}
}