java - 无法为 JOptionPane.createDialog 创建的 JDialog 设置未修饰

标签 java swing joptionpane jdialog awt-eventqueue

我从 JOptionPane 创建了 JDiolog

        var pane = new JOptionPane(e.getMessage(),JOptionPane.ERROR_MESSAGE,JOptionPane.DEFAULT_OPTION);
        var dialog = pane.createDialog("Error");
        dialog.setUndecorated(true);
        dialog.setBackground(new Color(0, 0,0,78));
        dialog.setVisible(true);
        return;

但是这段代码抛出异常

Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: The dialog is displayable.
  at java.desktop/java.awt.Dialog.setUndecorated(Dialog.java:1265)
  at com.quiz.server.LoginDialog.lambda$new$1(LoginDialog.java:56)
  blalablablabla.....

但我注释掉了这些行

    dialog.setUndecorated(true);
    dialog.setBackground(new Color(0, 0,0,78));

然后就可以了

最佳答案

以下代码片段将显示没有修饰的 JOptionPane 对话框:

    boolean defaultLFDecorated = JDialog.isDefaultLookAndFeelDecorated();
    try {
        JDialog.setDefaultLookAndFeelDecorated(true);
        JOptionPane pane = new JOptionPane("This is a message", JOptionPane.ERROR_MESSAGE, JOptionPane.DEFAULT_OPTION);
        JDialog dialog = pane.createDialog("Error");
        dialog.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
        pane.setOpaque(false);
        ArrayList<Component> components = new ArrayList<Component>(Arrays.asList(pane.getComponents()));
        while(!components.isEmpty()) {
            Component c = components.remove(0);
            if(c instanceof JComponent) {
                ((JComponent)c).setOpaque(false);
            }

            if(c instanceof Container) {
                components.addAll(Arrays.asList(((Container)c).getComponents()));
            }
        }
        dialog.setBackground(new Color(0, 0, 0, 78));
        dialog.setVisible(true);
        dialog.dispose();
    }
    finally {
        JDialog.setDefaultLookAndFeelDecorated(defaultLFDecorated);
    }

关于java - 无法为 JOptionPane.createDialog 创建的 JDialog 设置未修饰,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56739063/

相关文章:

java - 在java中输入带分数

java - JOptionPane 内的 JPanel 内的 JTable 不会根据需要调整大小

java - 在 Solr DataImportHandler 中从 Oracle 日期获取正确的时间

java - JTextarea 不使用 miglayout 垂直增长

java - 在运行时更新组件位置

Java:通过 JOptionPane 添加到数组

java - 如何在 C/OpenGL 中从整数数组创建位图

java - 日期时间格式中的小写 z 返回偏移量,而不是缩写

java - 移动应用程序的服务器端设计选项

java - 如何对某个区域内的非GUI对象实现MouseListener?