gpt4 book ai didi

java - 关闭当前窗口并打开上一个窗口?

转载 作者:行者123 更新时间:2023-12-01 12:52:39 25 4
gpt4 key购买 nike

我是java初学者,并遇到了以下问题。目的是在按下注销按钮时显示登录窗口。

显示的第一个 JFrame 窗口是“Plain”,包含 2 个字段用户名和密码(稍后我将添加登录功能)

当我按下提交按钮时,JFrame“新窗口”将显示,并带有“注销”按钮

我想做的是,当按下“注销”时,“新窗口”应该关闭,“普通”窗口应该打开。

当前问题:按下“注销”按钮时,将打开“新窗口”。

请更正代码,以便我获得所需的功能

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

import javax.swing.*;

class Test implements ActionListener{
JButton submit;
JFrame j;
JFrame jf;

public Test()
{
j = new JFrame("PLAIN");
j.setBounds(500,150,300,400);
j.setVisible(true);
j.setDefaultCloseOperation(j.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
j.add(panel);
panel.setSize(50, 50);
panel.setLayout(null);

JLabel label = new JLabel("User Name");
label.setSize(10,10);
label.setBounds(100, 30, 400, 30);
panel.add(label);

JTextField username = new JTextField(10);
username.setSize(10,10);
username.setBounds(300, 30, 400, 30);
panel.add(username);

JLabel password= new JLabel("Password");
password.setBounds(100, 90, 400, 30);
panel.add(password);

JPasswordField pass = new JPasswordField(10);
pass.setBounds(300, 90, 400, 30);
panel.add(pass);

submit = new JButton("Submit");
submit.setSize(10, 10);
submit.setBounds(300, 160, 200, 40);
panel.add(submit);

submit.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub

j.setVisible(false);
jf = new JFrame("NEw Window");
jf.setVisible(true);
jf.setBounds(500,150,300,400);
JPanel panel2 = new JPanel();
panel2.setLayout(null);
jf.add(panel2);

JButton logout = new JButton("LOGOUT");
logout.setBounds(100, 30, 400, 30);
panel2.add(logout);
logout.addActionListener(this);
jf.setDefaultCloseOperation(j.EXIT_ON_CLOSE);

}

public void actionPerformed1(ActionEvent e1) {

jf.dispose();
j.setVisible(true);


}

public static void main(String args[])
{

new Test();

}

}

最佳答案

一些要点:

  1. 添加完所有组件后最后调用JFrame#setVisible()

  2. 永远不要使用 null 布局,而是使用正确的布局管理器。

    了解更多 A Visual Guide to Layout Managers其中详细描述了所有布局管理器以及示例代码。

  3. 使用 SwingUtilities.invokeLater() 确保 EDT已正确初始化。

    了解更多

尝试使用WindowConstants.DISPOSE_ON_CLOSE而不是JFrame.EXIT_ON_CLOSE .

关于java - 关闭当前窗口并打开上一个窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24107895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com