我这里只是我的按钮的一小段代码:
up = new JButton(new ImageIcon("more_buttons\\up3.png"));
up.setBackground(new Color(224,223,227));
up.setPreferredSize(new Dimension(5,15));
up.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
value1000++;
if(value1000>0)
{
number.setText(value1000+"");
down.setEnabled(true);
}
}
});
down = new JButton(new ImageIcon("more_buttons\\down3.png"));
down.setBackground(new Color(224,223,227));
down.setPreferredSize(new Dimension(5,15));
down.setEnabled(false);
down.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
value1000--;
if(value1000>0)
{
number.setText(value1000+"");
}
if(value1000==0)
{
number.setText(value1000+"");
down.setEnabled(false);
}
}
});
我想知道我是否可以为这个按钮制作一个 Action 命令,这样我就不必在我的程序中重复这段代码。我只需要调用 buttonaction(e)
之类的函数。我不习惯创建 Action 命令,但我以前使用过它,但仅用于附加文本。我不确定如何使用这样的功能来做到这一点。是否可以?还是有更有效的方法来做到这一点?
最佳答案
您可以将相同的 ActionListener
添加到多个按钮:
ActionListener al = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// You can check which button was pressed and act accordingly
// simply by checking the event source:
if (e.getSource() == button1)
System.out.println("Button1 was pressed.");
else if (e.getSource() == button2)
System.out.println("Button2 was pressed.");
}
};
button1.addActionListener(al);
button2.addActionListener(al);
关于java - 如何为相同的按钮制作 Action 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24989527/