2013-05-10 8 views
5

में संख्याएं जोड़ें मैं जावा में अपने कौशल का परीक्षण करने के लिए एक कैलकुलेटर बना रहा हूं। जब तक मैं संख्याओं की गणना करने के लिए एक बटन दबाता हूं तब तक jTextfield में संख्याएं दिखाने के लिए कैसे बना सकते हैं; मैं चाहता हूं कि प्रत्येक नंबर टेक्स्टफील्ड में दिखाना चाहें। उदाहरण के लिए अगर मैं दबाया 1 और शून्य मैं चाहता हूँ पाठ फ़ील्ड 10.जावा कैलकुलेटर टेक्स्टफील्ड

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

के लिए आप खाली स्ट्रिंग के बजाय 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 एस की एक सरणी बना सकते हैं और उन्हें लूप में ले जा सकते हैं।
तो बटन 0 0

फिर सूचकांक में हो जाएगा, तो आप में पाठ संलग्न कर सकते हैं JTextField के रूप में:

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

यहाँ है:

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 

आप पाश इस प्रकार कर सकते हैं इस विषय पर ओरेकल द्वारा ट्यूटोरियल: http://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html

2

आप जो भी पहले से मौजूद हैं, उस पाठ को जोड़ना चाहते हैं - कुछ कोशिश करें जैसे

in.setText(in.getText() + num) बजाय in.setText("" + num)

संबंधित मुद्दे