我在将 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
不使用布局管理器,因此它的默认/首选尺寸为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);
关于java - 在 JPanel 中显示 JDesktopPane,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32534101/