如何为不同的JButton使用相同的ActionPerformed函数提供不同的功能?
public class ToolBarExample extends JPanel implements ActionListener {
public JTextPane pane;
public JMenuBar menuBar;
public JToolBar toolBar;
public JButton Aster;
public JButton Azaleas;
public JButton ChristFern;
public JButton JapBarberry;
public ToolBarExample() {
toolBar = new JToolBar("Formatting", JToolBar.VERTICAL);
this.Aster = new JButton(new ImageIcon("images/PlantIcons/[Blueprint]_Aster.png"));
this.toolBar.add(Aster);
this.Aster.addActionListener(this);
this.Azaleas = new JButton(new ImageIcon("images/PlantIcons/[Blueprint]_Azaleas.png"));
this.toolBar.add(Azaleas);
this.Azaleas.addActionListener(this);
this.ChristFern = new JButton(new ImageIcon("images/PlantIcons/[Blueprint]_ChristmasFern.png"));
this.toolBar.add(ChristFern);
this.ChristFern.addActionListener(this);
this.JapBarberry = new JButton(new ImageIcon("images/PlantIcons/[Blueprint]_JapaneseBarberry.png"));
this.toolBar.add(JapBarberry);
this.JapBarberry.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
try {
if(e.getSource() == Aster) {
NativePlant plant1 = new NativePlant(4, 5, 600, "test", "images/[Blueprint]_Aster.png", 200, 600);
Game.setNatives(plant1);
}
if(e.getSource() == Azaleas) {
NativePlant plant1 = new NativePlant(4, 5, 600, "test", "images/[Blueprint]_Azaleas.png", 100, 600);
Game.setNatives(plant1);
}
if(e.getSource() == ChristFern) {
NativePlant plant1 = new NativePlant(4, 5, 600, "test", "images/[Blueprint]_ChristmasFern.png", 300, 600);
Game.setNatives(plant1);
}
if(e.getSource() == JapBarberry) {
NativePlant plant1 = new NativePlant(4, 5, 600, "test", "images/[Blueprint]_JapaneseBarberry.png", 400, 600);
Game.setNatives(plant1);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
现在我正在尝试使用e.getSource来查找正在推送的按钮, 然后为每个按钮执行不同的操作。 但是,现在唯一正在工作的按钮是第一个(Aster)。
有谁知道我做错了什么,或者我应该做什么?
答案 0 :(得分:1)
您可以使用每个按钮的setActionCommand()并从actionPerformed中调用相应的getActionCommand。在我看来,使用常量来定义动作将是一个很好的方法。一小部分样本如下;
public class SwingTest extends JFrame implements ActionListener{
public SwingTest()
{
JButton btnOne = new JButton("test one");
btnOne.addActionListener(this);
btnOne.setActionCommand("TestOne");
JButton btnTwo = new JButton("test two");
btnTwo.addActionListener(this);
btnTwo.setActionCommand("TestTwo");
this.setLayout(new FlowLayout());
this.getContentPane().add(btnOne);
this.getContentPane().add(btnTwo);
}
public static void main(String[] args) {
SwingTest t = new SwingTest();
t.pack();
t.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
}
答案 1 :(得分:0)
而不是
e.getSource() == Aster
将其更改为:
e.getSource().equals(Aster)
它看起来像是一样的东西,但它会给你你想要的结果...... 因为.equals()正在检查对象的状态,而'=='正在检查实际的实例。
http://www.javabeat.net/qna/13-what-is-difference-between-equals-and-/