2014-06-16 6 views
0

나는 간단한 계산기를 만들지 만 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); 
} 
} 

답변

1

텍스트 팬의 내용을 덮어 쓰고 추가하십시오.

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

감사합니다 많이 다시 나에게 얻기를 위해 - 이것은 또한 치료를 일했다. – user3563455

0

calc 메서드를 수정해야합니다. 이 시도, 그것은 작동합니다 :

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

희망이 도움)

+0

Brilliant 귀하의 의견을 보내 주셔서 감사합니다. – user3563455