2009-11-13 49 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(); 
} 

}

相关问题