gpt4 book ai didi

java - JButton - 如何连接?

转载 作者:行者123 更新时间:2023-12-02 06:19:59 29 4
gpt4 key购买 nike

我在网上找到了这段代码并对其进行了修改,但它停止工作了。我认为这与我添加 Jpanel 时有关,但我所做的与 JPanel 配合效果最好。如何使 if 语句执行的操作中的事件起作用?

    import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;

import javax.swing.*;

public class GUI extends JFrame implements ActionListener {

static JPanel panel = new JPanel(new GridLayout(5, 5, 1, 1));

public GUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
//setSize(100, 100);
//setLocation(100, 100);



//Button 1
JButton button1 = new JButton("1");
button1.addActionListener(this);
panel.add(button1);

//Button 2
JButton button2 = new JButton("2");
button2.addActionListener(this);
panel.add(button2);

//Button 3
JButton button3 = new JButton("3");
button3.addActionListener(this);
panel.add(button3);

//Button 2
JButton button4 = new JButton("4");
button4.addActionListener(this);
panel.add(button4);

//Button 2
JButton button5 = new JButton("5");
button5.addActionListener(this);
panel.add(button5);

//Button 2
JButton button6 = new JButton("6");
button6.addActionListener(this);
panel.add(button6);

//Button 2
JButton button7 = new JButton("7");
button7.addActionListener(this);
panel.add(button7);

//Button 2
JButton button8 = new JButton("8");
button8.addActionListener(this);
panel.add(button8);

//Button 2
JButton button9 = new JButton("9");
button9.addActionListener(this);
panel.add(button9);



panel.setVisible(true);
}

public static void main(String[] args) {
new GUI();
JFrame f = new JFrame("Calc");
f.setContentPane(panel);
f.setSize(1000, 1000);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);

}

ArrayList numbers = new ArrayList();
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();

if (command.equals("button1")) {
myMethod();
numbers.add(1);
System.out.println("1");
}
if (command.equals("button1")) {
numbers.add(2);
System.out.println("2");
}
}

public void myMethod() {
JOptionPane.showMessageDialog(this, "Hello, World!!!!!");
System.out.println("Hey");
}
}

最佳答案

您需要将actionPerformed部分更改为:

@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();

if (command.equals("1")) {
myMethod();
numbers.add(1);
System.out.println("1");
}
if (command.equals("2")) {
numbers.add(2);
System.out.println("2");
}

}

在这里,当单击按钮时,您的 e.getActionCommand() 将给出构造函数字符串。即“1”、“2”、“3”等等

reference

关于java - JButton - 如何连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21094586/

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