简单计算器 - Textfield问题

时间:2014-06-16 12:50:07

标签: java swing jbutton jtextfield calculator

我正在创建一个简单的计算器,但无法解决如何在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);
}
}

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

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

希望这会有所帮助;)