我正在创建一个登录窗口,发现的示例难以实现,因为它们未显示尝试登录后如何进入下一个窗口。因为它不告诉我如何关闭“登录”窗口,然后在“登录完成”或“确认登录”消息后打开其他进程的窗口。
我使用IntelliJ进行了UI设计,这是我的代码。我知道此代码会引发错误。因为JOptionPane.showMessageDialog()返回void,但是我试图获取int返回值。我以它为例。
我了解我必须使用“ JOptionPane.showConfirmDialog”来接收整数类型的输入,但是我只想让用户知道他们已经登录,所以我不想显示其他任何东西。按钮。
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginForm {
private JPanel Login;
private JTextField IDField;
private JPasswordField PasswordField;
private JButton LoginOKBtn;
private JButton btnIDFind;
private JButton btnPWFind;
private JButton btnCreateAccount;
//Test ID and Password
final String testID="user";
final String testPW="pw";
public LoginForm() {
//Login Btn Event
LoginOKBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String ID=IDField.getText();
String PW=new String(PasswordField.getPassword());
System.out.println(ID);
System.out.println(PW);
//when ID and PW is collect then Show Dialog
if (ID.equals(testID) && PW.equals(testPW)){
int loginOKbtnclicked = JOptionPane.showMessageDialog(null, "Succesfully Loged in!", "Info", JOptionPane.YES_OPTION);
if (loginOKbtnclicked == JOptionPane.OK_OPTION){
System.out.println("TODO - Closing Window Code");
}
else{
}
}
else {
JOptionPane.showMessageDialog(null,"WRONG Password or ID","Alert!",JOptionPane.WARNING_MESSAGE);
}
}
});
}
public static void main(String[] args) {
JFrame frame = new JFrame("Login");
frame.setContentPane(new LoginForm().Login);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
只需将新框架放在消息框之后。并将当前帧放在此处,不要使用null发送。JOptionPane.showMessageDialog(**null**, "Succesfully Loged in!", "Info", JOptionPane.YES_OPTION);
然后更改当前帧的可见性,或执行您喜欢的操作。您无需检查他是否单击了按钮。由于该消息框除了说“您在”之外没有其他用途。
我使用JOptionPane.showOptionDialog()解决了这个问题。我发现JOptionPane.showMessageDialog()返回任何内容,但JOptionPane.showOptionDialog()返回int值。
这是我的测试代码
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Login {
private JPanel LoginPanel;
private JButton button1;
public static void main(String[] args) {
JFrame frame=new JFrame("LOGIN!");
frame.setContentPane(new Login().LoginPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public Login() {
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Object[] options={"OK"};
int in=-1;
in=JOptionPane.showOptionDialog(
LoginPanel,
"Give me your choice",
"Info",
JOptionPane.NO_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
options,
options[0]
);
if (in==0){
//Put Here closing old window code!
System.out.println("WAAAA");
}
}
});
}
}