我正在用 Java 编写一个简单的应用程序,它对一群羊进行一些粒子模拟(不要问)。为此,我想要一个带有 JPanel 图形的窗口(可以使用包含一些标准分辨率的简单组合框调整大小)和其他一些元素,例如用于启动和暂停模拟等的按钮。
我的问题:我正在使用 JFrame.pack 方法使用边框布局将所有内容很好地打包在一起。但由于某种原因,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);
}
}