简体   繁体   English

如何在 Java 中创建 GUI 计算器?

[英]How do I create a GUI Calculator in Java?

I am creating a Calculator GUI in java.我正在 java 中创建一个计算器 GUI。 So far I have created a layout and added everything to the canvas.到目前为止,我已经创建了一个布局并将所有内容添加到 canvas。 I am now in the implementing phase.我现在处于实施阶段。 My current problem is that when I can not enter more than one-digit numbers.我目前的问题是当我不能输入超过一位数字时。 enter image description here在此处输入图像描述

at numberbox.setText, instead of setting new value each time on button click, get existing value and append new value.在 numberbox.setText 处,不是每次单击按钮时都设置新值,而是获取现有值和 append 新值。 old value = numberbox.getText;旧值 = numberbox.getText; numberbox.setText(oldvalue+new value); numberbox.setText(旧值+新值);

String text = numberBox.getText();
//Your Code Here
text += actionPerformed(e);
numberBox.setText(text);

You should try update text.您应该尝试更新文本。

Normally, a simple calculator would have the characters they would like displayed within the Number Box as the actual caption on the button selected.通常,一个简单的计算器会将他们希望在数字框中显示的字符作为所选按钮上的实际标题。 This then means that all you need to append to the Number Box is the caption of the button selected.这意味着您需要append到数字框是所选按钮的标题。 Knowing this greatly reduces the code contained within the actionPerformed event.知道这一点会大大减少actionPerformed事件中包含的代码。

public void actionPerformed(ActionEvent e) {
    numberBox.setText(numberBox.getText() + ((JButton) e.getSource()).getText());
}

And that's all.就这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM