【发布时间】:2014-06-08 15:48:03
【问题描述】:
我是 java 初学者,遇到以下问题。 目的是在按下注销按钮时显示登录窗口。
显示的第一个 JFrame 窗口是“Plain”,包含 2 个字段用户名和密码(稍后我将添加登录功能)
当我按下提交按钮时,JFrame“NEw Window”与按钮“LOGOUT”一起显示
我想做的是,当按下“LOGOUT”时,“NEw Window”应该关闭,“Plain”窗口应该打开。
当前问题:当按下“注销”按钮时,“新窗口”正在打开。
请更正代码,以便我获得所需的功能
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();
}
}
【问题讨论】:
-
Java GUI 可能必须在多个平台、不同的屏幕分辨率和使用不同的 PLAF 上工作。因此,它们不利于组件的精确放置。为强大的 GUI 组织组件,而不是 use layout managers 或 combinations of them,以及 white space 的布局填充和边框。