打印JTextField在控制台上显示空白
我是 Java 新手,刚刚尝试了 Java 的摆动,我尝试制作一个登录表单,将 JTextField 的内容打印到控制台,但是当我尝试时控制台没有显示任何内容。
这是我的代码:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
public class JavaTextField {
private JFrame frame;
private JTextField text1;
private JTextField text2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JavaTextField window = new JavaTextField();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public JavaTextField() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
text1 = new JTextField();
text1.setBounds(114, 38, 122, 40);
frame.getContentPane().add(text1);
text1.setColumns(10);
String majorText = text1.getText();
text2 = new JTextField();
text2.setBounds(114, 117, 86, 20);
frame.getContentPane().add(text2);
text2.setColumns(10);
String minorText = text2.getText();
JButton btnButton = new JButton("Button");
btnButton.setBounds(132, 192, 159, 40);
frame.getContentPane().add(btnButton);
btnButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(majorText);
System.out.println(minorText);
}
}
);
}
}
如果有人能指出我正确的方向,我很高兴,因为我还没有在互联网上看到这个问题的解决方案。
回答
这里的问题是,您JTextField在错误的时间从s检索内容。当前,您getText()在初始化组件时立即调用。当然,从返回的内容getText()将是一个空的String。
因此,要解决逻辑中的问题,您实际上应该仅在按下s 后才从s 中检索majorText和。因为在那个时间点,当您按下按钮时,文本字段的内容应该是正确的。为此,请将文本的检索移至.minorTextJTextFieldJButtonActionListener
更新后ActionListener应如下所示:
btnButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String majorText = text1.getText();
String minorText = text2.getText();
System.out.println(majorText);
System.out.println(minorText);
}
}
或者干脆:
btnButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(text1.getText());
System.out.println(text2.getText());
}
}
旁注(正如另一个答案所提到的):
null强烈建议不要使用布局,因为它是不必要错误的常见来源。查看可用的不同LayoutManager以及如何以及何时使用它们。