我想从GUI窗口获取输入并存储



这是我的GUI

  1. 在启动窗口期间将打开并获取iput HOST、PORT和持续时间
  2. 单击"连接"按钮将关闭窗口
public class Frame1 {

public String userText;
public String pwdText;
public JFrame frame;
public JTextField textField;
public JTextField textField_1;
public JTextField textField_2;
public JLabel lblNewLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame1 window = new Frame1();
window.frame.setVisible(true);

} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Frame1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
public void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground( new Color(240, 240, 240));
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Connect");
btnNewButton.setForeground(Color.BLACK);
btnNewButton.setBackground(Color.GRAY);
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 16));
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//messape

userText = textField.getText();
pwdText = textField_1.getText();
System.out.println(userText);

if(e.getSource()==btnNewButton) {
frame.dispose();

// This exit Your GUI 
}

}
});

这是我的主程序,我在Connection2中调用Frame1

在这里,当从文本字段中检索值时,它显示空

public class Connection2{
//  public static final String HOST = "localhost";
//  public static final String PORT = "5555";
public static String HOST;
public static String PORT;
public static long START;
public static long END;
public static void main(String[] args) throws InterruptedException, ClassNotFoundException, SQLException, IOException {

Frame1 frame = new Frame1();

Scanner sc = new Scanner(System.in);
System.out.println("JMX CONNECTION:");
System.out.println("HOST AND PORT");
frame.main(args);


HOST =frame.userText;
PORT =frame.pwdText;
Thread.sleep(10000);
System.out.println(HOST);
System.out.println(PORT);


Thread.sleep(20000);
System.out.println(HOST);
System.out.println("TEST DURATION IN SECONDS");
System.out.println("DURATON(sec): ");
int Duration = sc.nextInt();

输出

JMX CONNECTION
HOST AND PORT
localhost
null
null

在给线程暂停时间后,这个输出正在得到。

在这段代码中,它不会等到用户按下按钮,所以我会返回一个null值。

因此,修复这种情况的一种可能方法是在连接类中添加一个方法,该方法在按下按钮时调用

最新更新