gpt4 book ai didi

java - 如何赋予 JButton 不同的功能?

转载 作者:行者123 更新时间:2023-11-30 11:38:59 26 4
gpt4 key购买 nike

如何使用相同的 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)。

有谁知道我做错了什么,或者我应该做什么?

最佳答案

您可以使用每个按钮的 setActionCommand() 并从 actionPerformed 调用相应的 getActionCommand。在我看来,使用常量来定义 Action 是一个很好的方法。小样如下;

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());
}
}

关于java - 如何赋予 JButton 不同的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13465634/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com