[英]How to create Action Listener inside anonymous class?
我目前有一个Frame类,用于创建框架,添加按钮和标签。 我目前在Frame类中具有动作侦听器的代码,并且需要移动它,以便从匿名类中调用动作侦听器。 这是我目前拥有的。
public static void main(String[] args)
{
Frame grid = new Frame();
grid.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
grid.setVisible(true);
grid.pack();
grid.setTitle("Frame");
}
public class Frame extends JFrame
{
ImageIcon green = new ImageIcon("green.png");
JLabel label;
public JButton button1,button2;
public Frame()
{
setLayout(new GridLayout(4,4));
/**create buttons*/
button1 = new JButton("");
add(button1);
button2 = new JButton("");
add(button2);
label = new JLabel(green);
add(label);
/**Add action listener to buttons, I need these 2 liseners in a anonymous class */
button1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
button1.setText("X");
}
});
button2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
button2.setText("X");
}
});
谁能告诉我如何移动该动作监听器,以便从匿名类中调用它? 我假设我在创建框架时主要是这样做的? 像这样的东西?
Frame grid = new Frame(){
//Code might go here?
}
我不确定,我是匿名类的新手。 谁能告诉我如何在匿名类中实现动作侦听器?
您可能会说类似的话:
class Frame
{
private JButton button1;
// Here it is:
private ActionListener firstActionListener = new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
button1.setText("X");
}
};
public Frame()
{
....
button1.addActionListener(firstActionListener);
}
}
虽然我想知道您需要什么。 您可能需要看一下http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html
您不能简单地将侦听器添加到既不支持您尝试连接的侦听器的组件,也不能添加到您没有引用的组件。
也就是说, JFrame
不支持ActionListener
并且您没有要向其添加操作的按钮的引用。
我知道你所做的按钮public
,但对我来说,这是一个糟糕的主意,因为你是暴露的组件外修改。 没有什么能阻止代码更改按钮的状态,将控制权从Frame
类移开了。
相反,您应该为感兴趣的各方提供注册兴趣的功能,例如知道何时激活按钮。
public static class Frame extends JFrame {
ImageIcon green = new ImageIcon("green.png");
JLabel label;
private JButton button1, button2;
public Frame() {
//...
}
public void addButton1ActionListener(ActionListener listener) {
button1.addActionListener(listener);
}
public void addButton2ActionListener(ActionListener listener) {
button2.addActionListener(listener);
}
public void removeButton1ActionListener(ActionListener listener) {
button1.removeActionListener(listener);
}
public void removeButton2ActionListener(ActionListener listener) {
button2.removeActionListener(listener);
}
然后,您只需将ActionListener
添加到想要的任何按钮,例如...
public static void main(String[] args) {
Frame grid = new Frame();
grid.addButton1ActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Do stuff
}
});
grid.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
grid.setVisible(true);
grid.pack();
grid.setTitle("Frame");
}
现在,这引起了问题,因为现在您已经提供了对底层按钮的访问权限,而您可能不想这么做。
现在,除了问题以外,我可能建议使用某种模型。 这将应用于Frame
,使其可以根据需要修改其状态,然后将事件通知提供给感兴趣的各方,说明某些状态或其他状态已更改,并且他们应采取适当的措施,例如更新视图。
最好用MVC模式来描述
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.