gpt4 book ai didi

java - Swing:如何使用多个按钮?

转载 作者:行者123 更新时间:2023-12-01 22:09:43 27 4
gpt4 key购买 nike

我创建了这个小测试程序。它有 2 个按钮和 2 个标签。我想知道如何使用 2 个按钮。因此,当我按下按钮 1 时,我会更改文本 1 的文本,而当我按下按钮 2 时,我会更改文本 2 的文本。我只是想了解如何使用多个按钮。

我的代码:

JLabel text1, text2;
JButton button1, button2;

public Game(String title) {
super(title);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().setLayout(new FlowLayout());

addComponents();

setSize(250, 250);
setResizable(false);

}

public void addComponents() {
text1 = new JLabel();
getContentPane().add(text1, text2);

text2 = new JLabel();
getContentPane().add(text2);

button1 = new JButton("Button");
getContentPane().add(button1);
button1.addActionListener(this);

button2 = new JButton("Button 2");
getContentPane().add(button2);
button2.addActionListener(this);
}

@Override
public void actionPerformed(ActionEvent e) {


}

我是编程新手,所以我也希望有人能为代码写一些注释。这样我就可以了解多个按钮的代码是如何工作的。

最佳答案

在您的 actionPerformed 方法中,您可以获取操作的来源

@Override
public void actionPerformed(ActionEvent e) {

if(e.getSource() == button1){
//Do Something
}else if(e.getSource() == button2){
//Do Something Else
}

关于java - Swing:如何使用多个按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32066410/

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