2015-03-02 23 views
1

我試圖用這些代碼創建一個Java AWT方案2點的整數:添加使用AWT

import javax.swing.*; 
import java.awt.*; 

public class Exer1 extends JFrame { 

    public Exer1(){ 

     super ("Addition"); 
     JLabel add1 = new JLabel("Enter 1st Integer: "); 
     JTextField jtf1 = new JTextField(10); 
     JLabel add2 = new JLabel("Enter 2nd Integer: "); 
     JTextField jtf2 = new JTextField(10); 
     JButton calculate = new JButton("Calculate"); 
     FlowLayout flo = new FlowLayout(); 
     setLayout(flo); 
     add(add1); 
     add(jtf1); 
     add(add2); 
     add(jtf2); 
     add(calculate); 
     setSize(200,200); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setVisible(true); 

    } 

    public static void main(String[] a){ 
     Exer1 ex1 = new Exer1(); 
    } 

} 

我的問題是如何添加使用的JTextField這2個整數。有人能幫我嗎?非常感謝。 :)

回答

1

您需要在您的JButton上使用ActionListener

然後,你需要「從JTextField小號的得到int,總結他們像未來:

calculate.addActionListener(new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      try { 
       int i1 = Integer.valueOf(jtf1.getText()); 
       int i2 = Integer.valueOf(jtf2.getText()); 
       System.out.println("sum=" + (i1 + i2)); 
      } catch (Exception e1){ 
       e1.printStackTrace(); 
      } 
     } 
    }); 
1

通常,您應該爲按鈕上的點擊事件創建事件偵聽器:Lesson: Writing Event Listeners。在該處理程序,你把你的兩個文本字段的內容,將它們轉換爲整數:

Integer i1 = Integer.valueOf(jtf1.getText()); 

然後就可以將這兩個整數,而在另一個控制顯示他們或做別的事與他們。

1
How to Use Buttons, Check Boxes, and Radio Buttons

開始和 How to Write an Action Listeners

這將爲您提供您需要能夠在用戶按下按鈕告訴信息。

JTextField#getText然後返回的String。那麼這個問題就變得轉換Stringint,而如果你走的時候,有成千上萬的例子演示瞭如何實現的問題

一旦你與轉換Stringint的古怪玩耍了,你可以看看How to Use SpinnersHow to Use Formatted Text Fields,它們對輸入的值執行自己的驗證