我正在编写一个应用程序,我想将我的登录表单设置为主表单的顶部,并始终位于主表单的顶部。我的意思是将其锁定在主表单前,直到登录表单关闭,这样用户可以在登录表单关闭后访问主表单。
答案 0 :(得分:3)
您可以使用JDialog
代替JFrame
来制作模态框架。以下两个链接可以帮助您入门。
答案 1 :(得分:0)
这遵循@Jabir概述的一般概念,但使用JOptionPane
(使用模态对话框作为显示组件),因为它有许多方便的方法来完成我们需要的繁重工作。在普通的模态对话框中实现。
另一方面,对话框的选项窗格更通用。一旦我们开始思考“那很好,但我想把它改成......”就是直接使用JDialog
的时候。选项窗格更难以在现有API提供的(多个)选项之外进行更改。
有关使用选项窗格的详细信息,请参阅How to Make Dialogs。
import java.awt.*;
import javax.swing.*;
class LoginForm {
private JPanel loginForm = new JPanel(new BorderLayout(5,5));
private JTextField userID = new JTextField(12);
private JPasswordField password = new JPasswordField(8);
LoginForm() {
initializeLoginForm();
}
/**
* Displays the log-in form inside a confirmation option pane.
* The result (OK/Cancel) of the option pane is returned for inspection.
*/
public final int displayLoginForm(Component parent) {
return JOptionPane.showConfirmDialog(
parent,
loginForm,
"Log In",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
}
private final void initializeLoginForm() {
JPanel labels = new JPanel(new GridLayout(0,1,5,5));
loginForm.add(labels, BorderLayout.LINE_START);
JPanel fields = new JPanel(new GridLayout(0,1,5,5));
loginForm.add(fields);
labels.add(new JLabel("User ID:", SwingConstants.TRAILING));
labels.add(new JLabel("Password:", SwingConstants.TRAILING));
JPanel userIdConstrain = new JPanel(
new FlowLayout(FlowLayout.LEADING));
userIdConstrain.add(userID);
fields.add(userIdConstrain);
JPanel passwordConstrain = new JPanel(
new FlowLayout(FlowLayout.LEADING));
passwordConstrain.add(password);
fields.add(passwordConstrain);
}
public final String getUserID() {
return userID.getText();
}
public final char[] getPasword() {
return password.getPassword();
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
JLabel l = new JLabel("<html>"
+ "<body style='width: 300px; height: 175px;>",
SwingConstants.CENTER);
JFrame f = new JFrame("Secure Application");
f.add(l);
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See http://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// ensures the minimum size is enforced.
f.setMinimumSize(f.getSize());
f.setVisible(true);
LoginForm lif = new LoginForm();
int result = lif.displayLoginForm(f);
// do the approrpaite action for this result
if (result==JOptionPane.OK_OPTION) {
l.setText("Welcome " + lif.getUserID());
} else {
l.setText("This application requires authentication!");
}
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}