如何在TextField Java Swing上获得价值

die*_*UET 9 java swing jtextfield

我有一个简单的Java Swing表单JTextField,我JTextField通过getText()方法得到了值,但我不能将它用于主程序.你能帮我解决什么问题以及如何解决?这是我的代码:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class Login {
private String name;

public Login() {
    JFrame main = new JFrame("LOGIN");
    main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    main.setResizable(false);
    main.setLayout(null);
    main.setPreferredSize(new Dimension(200, 300));
    main.setLocation(400, 200);

    // Heading: LOGIN
    JLabel heading = new JLabel("LOGIN");
    heading.setBounds(80, 20, 50, 20);
    main.add(heading);

    // Label Username
    JLabel username_label = new JLabel("username: ");
    username_label.setBounds(5, 70, 80, 20);
    main.add(username_label);
    // Textfield Username
    final JTextField username_field = new JTextField();
    username_field.setBounds(70, 70, 120, 20);
    main.add(username_field);
    this.name = username_field.getText();

    // Button Login
    JButton loginBtn = new JButton("LOGIN");
    loginBtn.setBounds(40, 150, 120, 25);
    main.add(loginBtn);
    main.pack();
    main.setVisible(true);

    loginBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            name = username_field.getText();
            // System.out.println(name); //IT WORKS
        }
    });
}

public static void main(String[] args) {
    Login me = new Login();
    me.print();//I EXPECT IT WILL PRINT @name BUT NO, WHY? 
}

public void print() {
    System.out.println(name);
}
}
Run Code Online (Sandbox Code Playgroud)

非常感谢!

Kee*_*san 10

在用户单击按钮之前,不应打印该值

public static void main(String[] args) {
    HelloWorldSwing me = new HelloWorldSwing();
    //me.print();//DON't PRINT HERE
}
Run Code Online (Sandbox Code Playgroud)

相反,你可以在actionPerformed()方法中执行此操作,

 loginBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            name = username_field.getText();
            HelloWorldSwing.this.print();
        }
    });
Run Code Online (Sandbox Code Playgroud)

这将打印该值,您在文本字段中输入


Dun*_*nes 6

您正在尝试在显示GUI后立即打印名称值:

Login me = new Login();
me.print(); // This executes immediately after the statement above
Run Code Online (Sandbox Code Playgroud)

但是,在用户按下登录按钮之前,不会设置此值:

loginBtn.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        name = username_field.getText();
        // System.out.println(name); //IT WORKS
    }
});
Run Code Online (Sandbox Code Playgroud)


And*_*son 5

向GUI类添加文本字段并不会奇怪地getText()向该类添加方法.我的意思是考虑一下,如果有两个文本字段,哪一个应该用于getText()?该字段应声明为类的属性,并定义getText()该字段的方法.

BTW:

  1. JTextField当GUI实际需要时,不要使用JPasswordField.
  2. 而不是JFrame这应该是一个模态JDialog.有关详细信息,请参见如何在对话框中使用模态.