gpt4 book ai didi

java - JButton Action 监听器不起作用

转载 作者:行者123 更新时间:2023-12-02 05:34:47 24 4
gpt4 key购买 nike

我正在为 mt GUI 计算器上的 JButtons 设置 Action 监听器。为了测试这一点,我将其设置为当我按下计算器上的第一个按钮时将显示更改为新消息。但是,它不起作用。任何建议将不胜感激!非常感谢!

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class GUICalculator extends JFrame{

//Fields
JButton[] buttons = new JButton[16];
String s = "0.0";

public GUICalculator(){
Font font1 = new Font("Monospaced", Font.BOLD, 20);
NumberListener numListen = new NumberListener();

//Create JPanel p1
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(4, 4, 10, 20));
String buttonValues[] = {"1", "2", "3", "+",
"4", "5", "6", "-",
"7", "8", "9", "*",
"0", ".", "C", "/"};

for(int i = 0; i < 16; i++){
JButton button = new JButton(buttonValues[i]);
buttons[i] = button;
buttons[0].addActionListener(numListen);
p1.add(buttons[i]);
}

//Create text field
JTextField text = new JTextField();
text.setText(s);
text.setEditable(true);
text.setFont(font1);

//Create JPanel p2
JPanel p2 = new JPanel();
p2.setLayout(new BorderLayout(10, 20));
p2.add(p1, BorderLayout.CENTER);
p2.add(new JButton("="), BorderLayout.SOUTH);
p2.add(text, BorderLayout.NORTH);

//Add contents to the frame
add(p2, BorderLayout.CENTER);
}
public static void main(String[] args) {

GUICalculator frame = new GUICalculator();
frame.setTitle("Calculator");
frame.setSize(300,300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

private class NumberListener implements ActionListener {

public void actionPerformed(ActionEvent e) {
if(e.getSource() == buttons[0]){
s = "It worked!";
}
else{
s = "It did not work";
}
}
}
}

最佳答案

添加尚未在 ActionListener 中注册的按钮时,您正在创建一个新的按钮实例。替换

p1.add(new JButton(buttonValues[i]));

p1.add(buttons[i]);

关于java - JButton Action 监听器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25098557/

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