我很难让一个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();
}
});
}
}发布于 2015-09-12 01:14:21
JDesktop不使用布局管理器,因此它的默认/首选大小是0x0JPanel默认使用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); https://stackoverflow.com/questions/32534101
复制相似问题