我正在用Java编写一个简单的应用程序,它可以对一堆绵羊进行一些粒子模拟(不要问)。为此,我想要一个带有JPanel图形的窗口(可以使用包含一些标准分辨率的简单组合框进行调整)以及其他一些元素,如按钮来启动和暂停模拟等。
我的问题:我正在使用JFrame.pack方法使用borderLayout很好地将所有内容打包在一起。但由于某种原因,JPanel包装错误,似乎包装忽略它,所以窗口大小调整到适合我现在只有两个按钮的大小。我做错了什么?
这是到目前为止的代码(一个新手的位,所以如果有的话,我的哑巴没有评论;)):
public class Window {
public Sheepness sheepness;
public ButtonPanel buttonPanel;
public PaintPanel paintPanel;
public JFrame frame;
public Window(Sheepness sheepness, int width, int height) {
this.sheepness = sheepness;
frame = new JFrame("Sheepness simulation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setSize(width, height);
BorderLayout frameLayout = new BorderLayout();
JPanel background = new JPanel(frameLayout);
background.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
buttonPanel = new ButtonPanel(this);
background.add(BorderLayout.SOUTH, buttonPanel.buttonBox);
paintPanel = new PaintPanel(this);
paintPanel.setSize(600, 600);
background.add(BorderLayout.CENTER, paintPanel);
frame.getContentPane().add(background);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
}
public class PaintPanel extends JPanel {
public Window window;
public PaintPanel(Window window) {
this.window = window;
}
@Override
public void paintComponent(Graphics g) {
g.setColor(Color.blue);
g.fillRect(0, 0, 300, 200);
}
}
public class ButtonPanel {
public Window window;
public Box buttonBox;
public JButton startButton;
public JButton resetButton;
public ButtonPanel(Window window) {
this.window = window;
buttonBox = new Box(BoxLayout.X_AXIS);
startButton = new JButton("Start");
startButton.addActionListener(new startButtonListener());
buttonBox.add(startButton);
resetButton = new JButton("Reset");
resetButton.addActionListener(new resetButtonListener());
buttonBox.add(resetButton);
}
}
答案 0 :(得分:4)
尝试:
paintPanel.setPreferredSize(600, 600);
当Window.pack()
大小与其子组件的首选大小相同时,JPanel
从其子组件获得其首选大小(在您的情况下没有)。