2013-05-10 10 views
5

私はjavaで自分のスキルをテストする電卓を作っています。数字を計算するために1つのボタンを押すまで、数字をjTextフィールドに表示するにはどうすればいいですか?私はすべての数字をテキストフィールドに表示したい。私はテキストフィールドが10Javaの電卓は、テキストフィールドに数字を追加します

int num; 
JTextField in = new JTextField(20); // input field where numbers will up; 

public void actionPerformed(ActionEvent e) { 
    if (e.getSource() == bouttons.get(0)) { 
     num = 0; 
     in.setText("" + num); 
    } 
    if (e.getSource() == bouttons.get(1)) { 
     int num = 1; 
     in.setText("" + num); 
    } 
} 

The screenshot

+0

あなたは完全なコードを共有することができますように。テキストを追加していないようです –

+0

ヒントは[この例](http://stackoverflow.com/a/7441804/418556)を参照してください。 –

答えて

1

を持ちたい1及びゼロを押した場合たとえば、あなたは自分自身の面倒を保存するにはin.getText()の代わりに、空の文字列

int num ; 
JTextField in = new JTextField(20); // input field where numbers will up; 
public void actionPerformed(ActionEvent e) { 



    if (e.getSource() == bouttons.get(0)) { 

     num =0; 

     in.setText(in.getText() + num); 

    } 

    if (e.getSource() == bouttons.get(1)) { 

     int num = 1; 
     in.setText(in.getText() + num); 

    } 

} 
2

を追加しなければなりませんif-elseがたくさんある場合は、JButtonの配列を作成して、それらをループで処理することができます。次のように、ループ

String alreadyDisplayed = in.getText(); //get the existing text 
String toDisplay = alreadyDisplayed + Integer.toString(loopCounter);// append the position to the text 
in.setText(toDisplay);// display the text 

することができます:ここで

for(int i=0;i<jbuttonArray.length;i++){ 
    if(e.getSource()==jbuttonArray[i]){ 
     //insert above code here; 
    } 
} 

がある
だから、ボタン0はその後、あなたのようにJTextFieldにテキストを追加することができ、インデックス0

になりますこのトピックに関するオラクルのチュートリアル:http://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html

2

何かを試してみてください

in.setText(in.getText() + num)代わりのin.setText("" + num)

関連する問題