繁体   English   中英

简单计算器-文本字段问题

[英]Simple Calculator - Textfield issue

我正在创建一个简单的计算器,但无法弄清楚如何在JTextField(sumField)中显示多个数字,即,当按下数字按钮时,该数字将添加到已显示的数字的右侧。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Calculator extends JFrame implements ActionListener {

private JButton clearButton, plusButton, minusButton, equalsButton, oneButton, twoButton, 
threeButton, fourButton,fiveButton, sixButton, sevenButton, eightButton, nineButton;
private JTextField sumField;

public static void main(String[] args) {
    Calculator demo = new Calculator();
    demo.setSize(230, 250);
    demo.createGUI();
    demo.setVisible(true);
}

private void createGUI() {
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    Container window = getContentPane();
    window.setLayout(new FlowLayout());

    sumField = new JTextField(15);
    window.add(sumField);
    oneButton = new JButton("1");
    window.add(oneButton);
    oneButton.addActionListener(this);
    twoButton = new JButton("2");
    window.add(twoButton);
    twoButton.addActionListener(this);
    threeButton = new JButton("3");
    window.add(threeButton);
    threeButton.addActionListener(this);
    plusButton = new JButton("+");
    window.add(plusButton);
    plusButton.addActionListener(this);
    fourButton = new JButton("4");
    window.add(fourButton);
    fourButton.addActionListener(this);
    fiveButton = new JButton("5");
    window.add(fiveButton);
    fiveButton.addActionListener(this);
    sixButton = new JButton("6");
    window.add(sixButton);
    sixButton.addActionListener(this);
    minusButton = new JButton("-");
    window.add(minusButton);
    minusButton.addActionListener(this);
    sevenButton = new JButton("7");
    window.add(sevenButton);
    sevenButton.addActionListener(this);
    eightButton = new JButton("8");
    window.add(eightButton);
    eightButton.addActionListener(this);
    nineButton = new JButton("9");
    window.add(nineButton);
    nineButton.addActionListener(this);
    equalsButton = new JButton("=");
    window.add(equalsButton);
    equalsButton.addActionListener(this);
    clearButton = new JButton("C");
    window.add(clearButton);
    clearButton.addActionListener(this);
}

public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();      
    if (source == oneButton) {
        calc("1");
    }
}

private void calc(String i) {
    sumField.setText(i);
}
}

您正在覆盖“文本”窗格的内容,请尝试追加。

private void calc(String i) {
    String contents = sumfield.getText();
    sumField.setText(contents+i);
}

您应该修改calc方法。 试试这个,它应该可以工作:

private void calc(String i) {
    sumField.setText(sumField.getText()+i);
}

希望这可以帮助 ;)

暂无
暂无

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

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