2013-05-10 20 views
5

Sto facendo una calcolatrice per testare le mie capacità in java. Come può far apparire i numeri nel campo jTextfield fino a quando non ho premuto un pulsante per calcolare i numeri; Voglio che tutti i numeri vengano visualizzati nel campo di testo. per esempio se ho premuto 1 e pari a zero voglio che il campo di testo per avere 10.Calcolatrice Java aggiungi numeri al campo di testo

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

Puoi condividere il codice completo. sembra che tu non stia aggiungendo il testo –

+0

Vedi [questo esempio] (http://stackoverflow.com/a/7441804/418556) per suggerimenti. –

risposta

1

si dovrebbe aggiungere con in.getText() invece di stringa vuota

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

di risparmiare il fastidio di un gran numero di if-else è possibile creare un array di JButton s e analizzarli in sequenza.
Così tasto 0 sarà a indice 0.

Quindi, è possibile aggiungere il testo al JTextField come:

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 

È possibile ciclo come segue:

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

Ecco il tutorial di Oracle su questo argomento: http://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html

2

Si desidera aggiungere il testo a qualsiasi cosa già ci sia - prova qualcosa come

in.setText(in.getText() + num) invece di in.setText("" + num)

Problemi correlati