java - 如何制作可调整大小的 JDialog?

标签 java swing size jdialog

我正在使用 JOptionPane.showOptionDialog 来显示 JDialog。我想知道如何:

  1. 设置对话框的尺寸(目前我在给定面板上使用 setPreferredSize() 方法,但我知道不应该使用这种方法)。
  2. 使显示的对话框可调整大小。

我的代码如下:

JPanel panel; //my JPanel built with dialog contents
int ret = JOptionPane.showOptionDialog(myFrame,
                    panel,
                        "titel",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.PLAIN_MESSAGE,
                    null,
                    options,
                    options[1]);

我知道我可以通过这种方式构建 JDialog 获得所需的结果:

JDialog dialog = new JDialog(panel);
dialog.setResizable(true);
dialog.setSize(800,600);
dialog.setVisible(true);

最后一个方案的问题是获取不到返回值。

编辑: 回应@camickr 的观察:

Why do you need to set the preferred size? If you build the panel properly is should be displayed at its preferred size.

我不确定在这一点上是否完全理解了 Swing。例如,问题是我通过 JDialog 显示使用 JFreeChart 构建的 ChartPanel。现在,我想该面板有它自己的首选尺寸,但我想看到它更大。在不显式使用 setPreferredSize() 的情况下如何做到这一点?

Read the JOptionPane API. Search for "Direct Use". It shows you how to directly access the dialog used by the option pane and you can

我读过它,但我找不到正确的方法来理解在 JDialog 上按下了哪个按钮(确定或取消)。

最佳答案

这种使用 HierarchyListener 来访问 JOptionPane 的 hack 也有效:

http://blogs.oracle.com/scblog/entry/tip_making_joptionpane_dialog_resizable

// TIP: Make the JOptionPane resizable using the HierarchyListener
pane.addHierarchyListener(new HierarchyListener() {
    public void hierarchyChanged(HierarchyEvent e) {
        Window window = SwingUtilities.getWindowAncestor(pane);
        if (window instanceof Dialog) {
            Dialog dialog = (Dialog)window;
            if (!dialog.isResizable()) {
                dialog.setResizable(true);
            }
        }
    }
});

关于java - 如何制作可调整大小的 JDialog?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7621255/

相关文章:

java - 如何集中日志配置,只使用 log4j.properties?

java - 在没有 appletviewer 的情况下在浏览器外部查看 java applet

c++ - 如何在 C++ 中找出内存中变量名称的大小?

java - 使用 Netbeans 可视化编辑器修改 JFrame 的大小

具有奇数(非偶数)大小的 Linux block 设备

java - 警告 : main methods should not be directly called

java - Android 自定义 View 滚动问题

java - 如何处理其他打开的 Jframe

java - 如何在 java 中创建自定义光标图像

java - 使用 JFrame 和 BufferedReader 获取文件内容