通过内部类设置两个不同的Listener,实现对两个不同按钮的监听,内部类的好处是可以使用外部类所有的方法和变量的存取,从而可以在继承了父类的方法的基础上在当前的类中进行操作,如果引入外部类,无法获取相关的组件对象。
代码实现如下:
package GuiTest;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TwoButtonListener {
//声明全局变量
JFrame frame;
JLabel label;
public static void main(String[] args) {
TwoButtonListener gui=new TwoButtonListener();
gui.go();
}
void go(){
frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton labelbutton=new JButton("Change Label");
//设置特定的监听事件
labelbutton.addActionListener(new LabelListener());
JButton colorbutton=new JButton("Change circke");
//设置特定的监听事件
colorbutton.addActionListener(new ColorListener());
label=new JLabel("I am a label");
JpanelGenralColor jpanelGenralColor=new JpanelGenralColor();
//添加按钮和画布以及label
frame.getContentPane().add(BorderLayout.SOUTH,colorbutton);
frame.getContentPane().add(BorderLayout.CENTER,jpanelGenralColor);
frame.getContentPane().add(BorderLayout.EAST,labelbutton);
frame.getContentPane().add(BorderLayout.WEST,label);
frame.setSize(300,300);
frame.setVisible(true);
}
//声明内部类 用来监听label按钮的事件
class LabelListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
label.setText("Ouch!");
}
}
//声明内部类 用来监听color按钮的事件
class ColorListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
frame.repaint();
}
}
}