在 JPanel 中显示 JDesktopPane

Displaying JDesktopPane in a JPanel

我在将 JDesktopPane(包含 JInternalFrame)添加到 JPanel 时遇到一些困难。这样做的正确方法是什么?我做错了什么?

这是我的基本示例:

import javax.swing.*;
import java.awt.*;

public class MainPanel extends JPanel {

    JDesktopPane jDesktopPane = new JDesktopPane();
    JInternalFrame jInternalFrame = new JInternalFrame();

    public MainPanel() {

        jDesktopPane.add(jInternalFrame);
        add(jDesktopPane);
        setSize(400,400);
        setVisible(true);
    }

    private static void createAndShowGui() {

        JFrame frame = new JFrame("This isn't working...");
        MainPanel mainPanel = new MainPanel();
        frame.setLayout(new BorderLayout());

        frame.add(mainPanel, BorderLayout.CENTER);
        frame.setContentPane(mainPanel);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setLocationByPlatform(false);
        frame.setSize(500, 500);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}
  • JDesktop 不使用布局管理器,因此 default/preferred 大小为 0x0
  • JPanel 默认使用 FlowLayout,它在布局时尊重其子组件的 preferredSize

因此,在您的构造函数中,您可以尝试将默认布局管理器改为 BorderLayout...

public MainPanel() {
    setLayout(new BorderLayout());
    jDesktopPane.add(jInternalFrame);
    add(jDesktopPane); 
    // pointless
    //setSize(400,400);
    // pointless
    //setVisible(true);
}

现在,您因为没有任何东西真正为任何东西定义首选尺寸,您应该提供自己的...

public Dimension getPreferredSize() {
    return new Dimension(400, 400);
}

然后当您创建 UI 时,您可以简单地打包框架...

private static void createAndShowGui() {

    JFrame frame = new JFrame("This should be working now...");
    MainPanel mainPanel = new MainPanel();
    frame.setLayout(new BorderLayout());

    // pointless considering the setContentPane call
    //frame.add(mainPanel, BorderLayout.CENTER);
    frame.setContentPane(mainPanel);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.pack();
    frame.setLocationByPlatform(false);
    //frame.setSize(500, 500);
    frame.setVisible(true);
}

现在因为 JDesktopPane 不使用任何布局管理器,所以您要负责确保添加到其中的任何内容的位置和大小

jInternalFrame.setBounds(10, 10, 200, 200);
// Just like any frame, it's not visible when it's first created
jInternalFrame.setVisible(true);