我无法获取我在Jtextfield中输入的信息,从这个类到主类,我只是得到null
public class FirstWindow extends JFrame {
private static final long serialVersionUID = 1L;
private static final String TEXT_FIELD = "text field";
private static final String TEXT2_FIELD = "text field";
private static final String PASS_FIELD = "pass field";
private String loginname;
private String loginlname;
private String loginpass;
public FirstWindow() {
super("login");
setSize(375, 125);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
final JTextField textField = new JTextField(10);// information inputs
final JTextField textField2 = new JTextField(10);// information inputs
final JPasswordField passwordField = new JPasswordField(10);// information
// inputs
JPanel p = new JPanel(new GridBagLayout());
JPanel p1 = new JPanel();
JPanel p2 = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
JButton showNamePasswordBtn = new JButton("Ok");
showNamePasswordBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
loginname = textField.getText();// setting first value
loginlname = textField2.getText();// setting sc value
loginpass = new String(passwordField.getPassword());// setting
// th value
// System.out.println ("vardas " +loginname);//information
// holders works on this class
// System.out.println ("varda " +loginlname);
// System.out.println ("vard " +loginpass);
System.exit(0);
}
});
JLabel label = new JLabel("Vartotojo Vardas ");
JLabel label2 = new JLabel("Vartotojo Pavarde");
JLabel label3 = new JLabel(" Vartotojo Slaptazodis");
gbc.gridx = 0;
gbc.gridy = 0;
p.add(label, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
p.add(label2, gbc);
gbc.gridx = 2;
gbc.gridy = 0;
p.add(label3, gbc);
p1.add(textField, TEXT_FIELD);
p1.add(textField2, TEXT2_FIELD);
p1.add(passwordField, PASS_FIELD);
p2.add(showNamePasswordBtn);
add(p2, BorderLayout.SOUTH);
add(p1, BorderLayout.CENTER);
add(p, BorderLayout.NORTH);
}
public String back() { // tried getting back info
return loginname;
}// val1
public String back1() {
return loginlname;
}// val2
public String back2() {
return loginpass;// val3
}
}
这是我想要获取我的信息的主要课程
public class GUImain {
public static void main(String[] args) throws Exception {
FirstWindow fw = new FirstWindow();
fw.setVisible(true);
String a, b, c;// creating strings
a = fw.back();// setting val
b = fw.back1();// setting val
c = fw.back2();// setting val
System.out.println("vardas " + a);
System.out.println("pavard " + b);
System.out.println("pass " + c);
}
}
所以主要的问题是所有id工作正常,期望我无法从Jframe类中获取任何最重要的信息
答案 0 :(得分:0)
运行此代码时,main()
方法会执行。它构建了您想要的GUI,您可以根据需要检索信息。例如:textField.getText();
但是当main()
方法执行时,TextField
全部为空,因此返回null
。您键入的值仅在您单击按钮时存储在变量中,因为您在其上添加了侦听器。点击按钮后,尝试输出 后的值。
要查看它:首先从侦听器中移除此行:System.exit(0);
(停止您的程序),并将其添加到main()
,以查看您可以从fw.back()
获取值在你的主要班级:
while(fw.back() == null){}
System.out.println(fw.back());
您将看到值