0

I have a 2 JPanels, 1 a button Panel and one a Graphic Panel. I would like the button panel to situated right below the graphic panel but the button panel cuts off the Graphics Panel in the middle. I've been trying the box layout which seems from discussions seems like the best format for what I am trying to do. Can anyone please give me some advice on my formatting problem.

    JFrame canvas = new JFrame("Baseball Strike K");


    JFrame canvas = new JFrame ("GraphicBoard");
      canvas.setVisible(true);
      canvas.setSize(1000,1000);
      canvas.setDefaultCloseOperation(EXIT_ON_CLOSE);
//create two panels
//add them to contentPane

//set Layout
      JPanel buttonPanel = createButtons();
      JPanel mainPanel = new Graphic(); //extends JPanel and writes the paint method
      mainPanel.setSize(1000, 1000);

      Container content = canvas.getContentPane();
      content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
      content.add(mainPanel);
      content.add(buttonPanel);
4

1 回答 1

1
mainPanel.setSize(1000, 1000);

布局管理器的工作是确定组件的大小,因此您永远不会调用组件的 setSize() 方法。

相反,您向布局管理器提示尺寸应该是多少。为此,您可以重写 getPreferredSize() 方法以返回适当的值。另外,我会选择一个更合理的尺寸(1000、1000),以便在大多数屏幕上显示。如果您真的希望您的绘画区域这么大,那么我会将绘画面板添加到 JScrollPane,然后将滚动窗格添加到框架中。

尝试使用 BoxLayout 让您的代码正常工作。然后我建议更好的布局管理器是使用 BorderLayout。然后您将绘画面板添加到 CENTER 并将按钮添加到 SOUTH。现在,当您调整框架大小时,将调整油漆面板的大小。

canvas.setVisible(true);

此外,该行代码的位置是错误的。在使框架可见之前,您应该首先将所有组件添加到框架中。

于 2013-03-17T20:33:18.340 回答