gpt4 book ai didi

java - 如何使java中的按钮与文本字段对应?

转载 作者:行者123 更新时间:2023-12-02 11:11:32 25 4
gpt4 key购买 nike

刚刚完成大学一年级类(class),想要提高我的 Java 编码技能。我目前正在尝试开发一个简单的 GUI 计算器应用程序。然而,我坚持如何在我的 jButtons 上制作,例如按下后第一个出现在我的文本字段上。我知道我可能必须使用 Action 监听器来实现此功能,但我目前陷入困境。任何帮助都会很棒。非常感谢。

public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new JFrame("Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
frame.pack();
frame.setIconImage(new ImageIcon("F:\\Java Summer Project\\Sumer_Project\\images\\farme_image.jpg").getImage());
frame.setSize(500, 480);
frame.setResizable(false);
frame.setVisible(true);

////// panel\\\
JPanel panel = new JPanel();
panel.setLayout(null);
frame.add(panel);

TextField textField = new TextField();
textField.setBounds(0, 0, 500, 200);
textField.setEnabled(true);
panel.add(textField);

JButton openbracketButton = new JButton("(");
openbracketButton.setBounds(0, 200, 50, 50);
panel.add(openbracketButton);

JButton closebracketButton = new JButton(")");
closebracketButton.setBounds(50, 200, 50, 50);
panel.add(closebracketButton);

JButton percButton = new JButton("%");
percButton.setBounds(100, 200, 50, 50);
panel.add(percButton);

JButton clearButton = new JButton("ac");
clearButton.setBounds(150, 200, 50, 50);
panel.add(clearButton);

JButton divideButton = new JButton("÷");
divideButton.setBounds(150, 250, 50, 50);
panel.add(divideButton);

JButton timesButton = new JButton("X");
timesButton.setBounds(150, 300, 50, 50);
panel.add(timesButton);

JButton minusButton = new JButton("+");
minusButton.setBounds(150, 350, 50, 50);
panel.add(minusButton);

JButton plusButton = new JButton("-");
plusButton.setBounds(150, 400, 50, 50);
panel.add(plusButton);

JButton oneButton = new JButton("1");
oneButton.setBounds(0, 250, 50, 50);
oneButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent oneButton) {
System.out.println("Do Something Clicked");
}
});

panel.add(oneButton);

最佳答案

我猜你正在寻找这样的东西:

oneButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent oneButton) {
if(StringUtils.isEmpty(textField)) {
// If its empty so just put 1 in the display
textField.setText("1");
} else {
// Get value on display and convert to a integer
// Plus one because its the button one
int result = 1 + Integer.parseInt(textField.getText());
// Set the result to the display
textField.setText((String) result);
}
}
});

祝你学业有成!

关于java - 如何使java中的按钮与文本字段对应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50584411/

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