我是Java新手,刚刚尝试了Java的swing,我尝试制作一个登录表单,将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
是在错误的时间。目前您致电getText()
就在组件初始化时。当然,返回的内容是getText()
将是一个空的String
.
因此,要解决逻辑中的问题,您实际上应该检索majorText
and minorText
来自JTextField
只有一次你的JButton
已被按下。因为在那个时间点,当按下按钮时,文本字段的内容should是正确的。为此,请将文本检索移至ActionListener
.
更新后的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());
}
}
Sidenote(正如另一个答案也提到的):
Using null
强烈建议不要使用布局,因为它是不必要错误的常见来源。看看不一样的布局管理器 https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html可用以及如何以及何时使用它们。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)