如何使用相同的 ActionPerformed 函数为不同的 JButton 提供不同的功能?
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)。
有谁知道我做错了什么,或者我应该做什么?