How can I set up a JFrame button to open another JFrame, and then receive information once the second jframe is closed?

huangapple go评论76阅读模式
英文:

How can I set up a JFrame button to open another JFrame, and then receive information once the second jframe is closed?

问题

以下是翻译好的部分:

public class MathFactsGUI extends JFrame
{
    // 实例变量...
    
    /**
     * 构造方法
     */
    public MathFactsGUI()
    {
        super("数学事实测验");

        // ...

        // 按钮的动作监听器
        additionJButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
               quiz = new Quiz('+');
               // ...
            }            
        }); 

        multiplicationJButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
               quiz = new Quiz('x');
               // ...
            }            
        });

        signinJButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                // ...
            }
        });

        signupJButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                MathFactsSignUpGUI signUpGUI = new MathFactsSignUpGUI();
                gui.setVisible(true);
            }
        });
    }
}
public class MathFactsSignUpGUI extends JDialog {
    // 实例变量...

    public MathFactsSignUpGUI(){
        // ...

        submitJButton = new JButton("提交");
        submitJButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                username = usernameJTextField.getText();
                userPass = userPassJTextField.getText();
                userFirstName = userFirstNameJTextField.getText();

                if (!checkValid(username) || !checkValid(userPass) || !checkValid(userFirstName)){
                    JOptionPane.showMessageDialog(null, "所有字段都必须填写。");
                } else if (Userbase.getUserbase().userExist(username)){
                    JOptionPane.showMessageDialog(null, "用户名已被使用,请选择另一个。");
                } else {
                    Userbase.getUserbase().addUser(username, new User(username, userPass, userFirstName));
                    MathFactsGUI.setUsername(username);
                }
            }
        });

        JPanel mfSignUp = new JPanel();
        mfSignUp.setLayout(new GridLayout(0,1));
        mfSignUp.add(usernameBox);
        mfSignUp.add(userPassBox);
        mfSignUp.add(userFirstBox);
        mfSignUp.add(submitJButton);
    }

    public String signIn(){
        return username;
    }

    public boolean checkValid(String a){
        if (a == null || a.length() == 0){
            return false;
        } else {
            return true;
        }
    }
}

你提到想通过WindowListener在登录或注册窗口关闭时执行操作,这是一个不错的想法。你可以在MathFactsSignUpGUI类中添加一个WindowListener来监听窗口关闭事件,并在窗口关闭时处理所需的逻辑。例如:

addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent e) {
        // 处理窗口关闭时的逻辑,例如回传用户名
        // 可以通过 MathFactsGUI 的方法来处理
        MathFactsGUI.setUsername(username);
    }
});

另外,关于JDialog的布局和文本验证,你可以在MathFactsSignUpGUI类中使用JDialog的布局管理器和输入验证,就像你在代码中所做的那样。JDialogJFrame在这方面没有太大的区别。你已经在MathFactsSignUpGUI类中设置了合适的布局和文本验证,所以可以继续使用这些设置。

英文:

This is part of a project for school, and I'm stuck and need someone to bounce ideas off of. I have a game where there is an option to sign up or sign in for a machine-local game so a record can be kept of the person's scores. The game is run from a base GUI JFrame, and I want to make buttons to bring up secondary windows for the person to sign in or sign up, before closing out of them. I need to pass the validated username back to the initial GUI/game class so I can store it for the following game so the game score can be added under that user. I just need to pass the username back and I'm not sure how to go about it. This is the main GUI code up to where I'm having my issue:

public class MathFactsGUI extends JFrame
{
// instance variables
private JTextField problemJTextField, answerJTextField;
private JLabel equalJLabel;
private JButton  additionJButton, multiplicationJButton;
private JButton signupJButton, signinJButton; 
private JButton submitJButton;
private JLabel scoreJLabel,resultJLabel;
//private JButton reviewButton;
private String username;
private Userbase userbase;
private JLabel introJLabel;
Quiz quiz;
/**
* Constructor for objects of class MathFactsGUI
*/
public MathFactsGUI()
{
super("Math Facts Quiz");
userbase = Userbase.getUserbase();
username = "guest";
/* code here has been removed to be abbreviated */
// Action listener for buttons
additionJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
quiz = new Quiz('+');
problemJTextField.setText(quiz.getCurrentProblem());
additionJButton.setEnabled(false);
multiplicationJButton.setEnabled(false);
signupJButton.setEnabled(false);
signinJButton.setEnabled(false);
}            
}); 
multiplicationJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
quiz = new Quiz('x');
problemJTextField.setText(quiz.getCurrentProblem());
additionJButton.setEnabled(false);
multiplicationJButton.setEnabled(false);
signupJButton.setEnabled(false);
signinJButton.setEnabled(false);
}            
});
signinJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JDialo
}
});
signupJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
MathFactsSignUpGUI signUpGUI = new MathFactsSignUpGUI();
gui.setVisible(true);
}
});
}

This is the JFrame I wrote for the sign-up button:

public class MathFactsSignUpGUI extends JDialog {
private JTextField usernameJTextField, userPassJTextField, userFirstNameJTextField;
private JLabel usernameJLabel, userPassJLabel, userFirstNameJLabel;
private JButton  submitJButton;
private String username;
private String userPass;
private String userFirstName;
public MathFactsSignUpGUI(){
usernameJLabel = new JLabel("Username:");
usernameJTextField = new JTextField();
userPassJLabel = new JLabel("Password:");
userPassJTextField = new JTextField();
userFirstNameJLabel = new JLabel("Player First Name:");
userFirstNameJTextField = new JTextField();
Box usernameBox = Box.createHorizontalBox();
usernameBox.add(usernameJLabel);
usernameBox.add(usernameJTextField);
Box userPassBox = Box.createHorizontalBox();
userPassBox.add(userPassJLabel);
userPassBox.add(userPassJTextField);
Box userFirstBox = Box.createHorizontalBox();
userFirstBox.add(userFirstNameJLabel);
userFirstBox.add(userFirstNameJTextField);
submitJButton = new JButton("Submit");
submitJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
username = usernameJTextField.getText();
userPass = userPassJTextField.getText();
userFirstName = userFirstNameJTextField.getText();
if (!checkValid(username) || !checkValid(userPass) || !checkValid(userFirstName)){
JOptionPane.showMessageDialog(null, "All fields must have values.");
} else if (Userbase.getUserbase().userExist(username)==true){
JOptionPane.showMessageDialog(null, "Username is taken, please choose another.");
} else {
Userbase.getUserbase().addUser(username, new User(username, userPass, userFirstName));
MathFactsGUI.setUsername(username);
}
}
});
JPanel mfSignUp = new JPanel()
mfSignUp.setLayout(new GridLayout(0,1));
mfSignUp.add(usernameBox);
mfSignUp.add(userPassBox);
mfSignUp.add(userFirstBox);
mfSignUp.add(submitJButton);
}
public String signIn(){
return username;
}
public boolean checkValid(String a){
if (a == null || a.length() == 0){
return false;
} else {
return true;
}
}
}```

I was thinking of implementing a WindowListener action for when the sign-up/sign-in frames close, but I'm not sure that will work. I was also looking into JDialog, but I'm not sure if it has the layout/text verification properties I need.

答案1

得分: 1

使用 JOptionPane。它将简化您的布局,无需创建单独的 JFrame,并且可以轻松地将值传递回调用它的位置。然后,您可以使其在单击“确定”时检查有效的用户名。

尝试这个网站。它提供了很好的概述,附有示例图片

英文:

Use a JOptionPane. It will simplify your layout without the need for creating a separate JFrame and easily pass values back to wherever it was called from. You can then make it check for valid username when you click OK.

Try this site. It gives a good rundown with example images

答案2

得分: 0

首先,您需要理解这是一个对象,因此您可以创建一些全局变量来包含这些信息(用户名、密码、昵称)。我建议使用ScheduledExecutorService从MathFactsSignUpGUI中获取信息。它将会每隔100毫秒从这个注册界面获取信息,然后销毁自身,以下是一个示例:

MathFactsSignUpGUI su = new MathFactsSignUpGUI();
su.setVisible(true);
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule(new Runnable(){
    public void run(){
        if(!su.username.isEmpty() && !su.userPass.isEmpty() && !su.userFirstName.isEmpty()){
            if(su.isLogin){ //如果玩家正在登录
                //在此处执行一些操作
            }else{//如果用户已注册
                //在此处执行一些操作
            }
            System.out.println("检查完成");
            service.shutdown();//在接收数据后销毁此服务
        }
    }
}, 100, TimeUnit.MICROSECONDS);
英文:

First you need to understand that this is an object, so you can create some global variables which will contains this information(username,password,Nickname), i recommend to pull info from MathFactsSignUpGUI by using ScheduledExecutorService. It will pull info from this sign up gui in every 100ms, than it will destroy itself, here is an example:

MathFactsSignUpGUI su = new MathFactsSignUpGUI ();
su.setVisible(true);
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule(new Runnable(){
public void run(){
if(!su.username.isEmpty() && !su.userPass.isEmpty() && !su.userFirstName.isEmpty() ){
if(su.isLogin){ //if player is loggining
//do something here
}else{//if user is registered
//do something here
}
System.out.println("Check complete");
service.shutdown();//to destroy this service after recieving the data
}
}
}, 100, TimeUnit.MICROSECONDS);

huangapple
  • 本文由 发表于 2020年7月27日 12:29:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63108728.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定