我有一个将启动另一个窗口的父窗口。当子窗口启动时,我希望它显示为模态对话框。
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ModalDialogTest {
public void createUI(){
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
JPanel mainPanel = new JPanel();
mainPanel.setBorder(BorderFactory.createEmptyBorder(200, 200, 200, 200));
JButton openButton = new JButton("Open a frame");
openButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
AnotherWindow anotherWindow = new AnotherWindow();
anotherWindow.createUI();
}
});
mainPanel.add(openButton,BorderLayout.CENTER);
frame.add(mainPanel,BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
ModalDialogTest modelDialogTest = new ModalDialogTest();
modelDialogTest.createUI();
}
class AnotherWindow{
public void createUI(){
JFrame frame = new JFrame("Dialog");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
JPanel mainPanel = new JPanel();
mainPanel.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
JLabel label = new JLabel("I want to be a modal dialog");
mainPanel.add(label,BorderLayout.CENTER);
frame.add(mainPanel,BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
}
上面的demo描述了我的app的流程,架构是一样的,那怎么解决呢?
最佳答案
您不能设置JFrame
的模态;第二个窗口必须是 JDialog
。因此,将第二个 JFrame
更改为 JDialog
并使用方法 setModalityType()
在上面。
关于java - 如何实现模态对话框的效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24239642/