2009-11-13 81 views
1

因此,我創建一個小的Java應用程序,只是想知道如何獲取JTextField的內容,然後將該值分配給一個String變量,工作:將JTextField的內容放入一個變量 - Java&Swing

JTextField txt_cust_Name = new JTextField(); 
String cust_Name; 
txt_cust_Name.addActionListener(new ActionListener() 
{ 
    public void actionPerformed(ActionEvent e) 
    { 
     cust_Name = txt_cust_Name.getText(); 
    } 
}); 

現在我認爲這會發送JtextField的值到字符串Cust_Name。

任何人有任何想法做到這一點?

乾杯。

回答

3

ActionListener僅在按下Enter鍵時觸發。

也許你應該使用FocusListener並處理focusLost()事件。

或者,您也可以將DocumentListener添加到文本字段的Document中。每次對文本字段進行更改時都會觸發DocumentEvent。

0

通常情況下,JTextField坐在窗體上,用戶可以使用它,直到他擊中表單上的Ok按鈕。該按鈕的處理程序(ActionListener)然後從字段中抓取當前文本值並對其執行操作。

你想做些與衆不同的事嗎?您是否需要在輸入發生變化時對其進行響應,或者只有在用戶離開現場時才需要響應輸入?或者他碰到ENTER很重要嗎?

請注意,這樣的非標準行爲可能會混淆現實生活中的用戶。如果你只是爲自己做這件事,當然,任何事情都會發生。

1

你在哪裏都需要實際使用字符串變量,你可以說:

String cust_Name = txt_cust_Name.getText(); 

這是假設在時間點您嘗試訪問它已經進入了這個值.. (與之相對嘗試每一個按鍵時更新變量)

2

感謝所有,我選擇做的是當按下一個按鈕分配值:

JButton btn_cust_Save = new JButton("Save Customer"); 
         btn_cust_Save.addActionListener(new ActionListener() 
         { 
          public void actionPerformed(ActionEvent ae) 
          { 
           final String cust_Name = txt_cust_Name.getText(); 
           final String cust_Door = txt_cust_Door.getText(); 
           final String cust_Street1 = txt_cust_Street1.getText(); 
           final String cust_Street2 = txt_cust_Street2.getText(); 
           final String cust_City = txt_cust_City.getText(); 
           final String cust_PCode = txt_cust_PCode.getText(); 
           final String cust_Phone = txt_cust_Phone.getText(); 
           final String cust_Email = txt_cust_Email.getText(); 
          } 
         }); 

釷尋求所有的幫助。

0

我發現這個代碼工作得很好:

package test; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 

public class Test extends JFrame { 

private static final long serialVersionUID = -5624404136485946868L; 

String userWord = ""; 
JTextField userInput; 

public Test() { 
    JFrame jf = new JFrame(); 
    JPanel panel = new JPanel(); 
    JLabel jl = new JLabel("Test"); 
    JButton jButton = new JButton("Click"); 
    userInput = new JTextField("", 30); 
    jButton.addActionListener((e) -> { 
     submitAction(); 
    }); 
    jf.setSize(500, 500); 
    jf.setVisible(true); 
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    jf.add(panel); 
    panel.add(jl); 
    panel.add(userInput); 
    panel.add(jButton); 
} 

private void submitAction() { 
    userWord = userInput.getText(); 
    System.out.println(userWord);//do whatever you want with the variable, I just printed it to the console 
} 

public static void main(String[] args) { 
    new Test(); 
} 

}