我正在编写一个使用swing的java应用程序。我使用的两个主要方法称为Main和logInScreen。我在登录屏幕上有一个变量,最初设置为"清空#34;但是然后将设置为" Y"如果使用setter(动作监听器内部)按下按钮。我遇到的问题是我无法通过使用getter在main方法中访问此值。有谁知道问题是什么?
以下是main的相关代码:
while (cont == true) {
answer = login.getEntered();
if (answer.equals("Y")) {
cont = false;
} else {
cont = true;
}
}
以下是GUI的代码:
package com.company;
/*
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
public class logInScreen extends JFrame {
private static String usernameInput = "";
private static String passwordInput = "";
private static JPanel panel = new JPanel();
private static String entered = "";
public logInScreen() {
setEntered("empty");
this.setTitle("Log In");
this.setSize(400, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
usernameArea();
passwordArea();
button("Log In");
createNewAccount();
this.add(panel);
this.setVisible(true);
}
public static void usernameArea() {
JTextArea username = new JTextArea(1, 15);
username.setText("");
username.setLineWrap(true);
JScrollPane pane = new JScrollPane(username, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(pane);
}
public static void passwordArea() {
JTextArea password = new JTextArea(1, 15);
password.setText("");
password.setLineWrap(true);
JScrollPane pane2 = new JScrollPane(password, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(pane2);
}
public void button(String text) {
JButton btn = new JButton();
btn.setText(text);
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setEntered("Y");
System.out.println(getEntered());
}
});
panel.add(btn);
}
public static void createNewAccount(){
JTextArea label = new JTextArea(1,30);
label.setLineWrap(true);
label.setEditable(false);
label.setText(" New User?");
panel.add(label);
JButton newAccount = new JButton();
newAccount.setText("Create New Account!");
newAccount.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
createLoginScreen newAccount = new createLoginScreen();
}
});
panel.add(newAccount);
}
public void setEntered(String val){
entered = val;
}
public String getEntered() {
return entered;
}
public String getUsernameInput() {
return usernameInput;
}
public String getPasswordInput() {
return passwordInput;
}
public void close() {
this.setVisible(false);
this.dispose();
}
}
答案 0 :(得分:1)
while (cont == true) {
可能会阻止事件调度线程阻止运行任何事情。即使不是,也是一个坏主意。
使用模式对话框,该对话框将在对话框可见时阻止,并在关闭时继续运行,此时您可以确定已输入的值。
有关详细信息,请参阅How to make dialogs。
此外,删除所有static
声明,这对您没有帮助,并且随着解决方案变得更加复杂而不会导致问题的结束