2013-12-13 31 views
0

我有一個用Swing庫編寫的Java表單,其中包含多個JTextField對象和一個JButton對象。爲Java按鈕創建操作

我需要的是,當用戶單擊按鈕時,要調用的方法將讀取JTextField對象的所有值,並將它們作爲另一個方法的參數傳遞。

在HTML/JavaScript中,這將是類似於:

<input type="button" onClick="myMethod()"> 

如果myFunction的()將瀏覽所有文本字段的形式和讀出的值,然後返回這些值的數組。

想法? :)

感謝

達里奧

回答

2
public class Test extends JFrame { 

    JTextField jtf1 = new JTextField(10); 
    JTextField jtf2 = new JTextField(10); 
    JTextField jtf3 = new JTextField(10); 
    JTextField jtf4 = new JTextField(10); 
    JButton button = new JButton("Button"); 

    public Test() { 
     JPanel panel = new JPanel(new GridLayout(4, 1)); 
     panel.add(jtf1); 
     panel.add(jtf2); 
     panel.add(jtf3); 
     panel.add(jtf4); 

     add(panel, BorderLayout.CENTER); 
     add(button, BorderLayout.SOUTH); 

     button.addActionListener(new ActionListener(){ // add a listener to the button 
      public void actionPerformed(ActionEvent e){ // perform the action when clicked 
       String str1 = jtf1.getText();  // get input from text field 1 
       String str2 = jtf2.getText();  // get input from text field 2 
       String str3 = jtf3.getText();  // get input from text field 3 
       String str4 = jtf4.getText();  // get input from text field 4 

       // do something with strings 
       someMethod(str1, str2, str3, str4); // pass to someMethod 
      } 
     }); 
    } 

    private void someMethod(String s1, String s2, String s3, String s4){ 
     // dumb example 
     System.out.println(s1 + " " + s2 + " " + s3 + " " + s4); 
    } 

    public static void main(String[] args){ 
     SwingUtilities.invokeLater(new Runnable(){ 
      public void run(){ 
       Test test = new Test(); 
       test.setDefaultCloseOperation(EXIT_ON_CLOSE); 
       test.pack(); 
       test.setVisible(true); 
      } 
     }); 
    } 
} 

注意:如果您從文本字段需要數值,你應該分析文本

+0

嗨@peeskillet,我得到一個錯誤,告訴我getText()未定義類型字符串 – MrD

+0

因爲它是未定義的。你是否試圖用String來使用該方法?該方法將與文本字段一起使用並返回一個字符串。因此'String str1 = jtf1.getText();' –

+0

修正了謝謝:) – MrD

2

入住這http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

b = new Button("Click me"); 
b.addActionListener(this); 



public void actionPerformed(ActionEvent e) { 
    numClicks++; 
    text.setText("Button Clicked " + numClicks + " times"); 
} 
+3

它注意'addActionListener(this)'只有在引用了一個類im時才起作用使ActionListener接口成爲可能。 – PakkuDon

+0

+1給PakkuDon指出。謝謝 !! –