在Java中,可以使用JOptionPane
类创建一个模态对话框
import javax.swing.*;
public class ModalDialogExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGUI());
}
private static void createAndShowGUI() {
// 创建一个 JFrame,作为主窗口
JFrame frame = new JFrame("Modal Dialog Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
// 创建一个 JButton,点击时会显示模态对话框
JButton showDialogButton = new JButton("Show Modal Dialog");
showDialogButton.addActionListener(e -> {
JOptionPane.showMessageDialog(frame, "This is a modal dialog!", "Modal Dialog", JOptionPane.INFORMATION_MESSAGE);
});
// 将按钮添加到主窗口的内容面板中
frame.getContentPane().add(showDialogButton);
}
}
这个例子首先创建了一个JFrame
作为主窗口。然后,我们创建了一个JButton
,当用户点击该按钮时,会显示一个模态对话框。JOptionPane.showMessageDialog()
方法用于创建并显示模态对话框。该方法接受四个参数:
JOptionPane.INFORMATION_MESSAGE
,表示信息类型的对话框)运行此代码后,你将看到一个包含按钮的主窗口。点击按钮后,将显示一个模态对话框,直到用户关闭它。在这个例子中,对话框是一个简单的信息对话框,但你也可以根据需要创建其他类型的模态对话框,如警告、错误或确认对话框。