简体   繁体   English

JPanel格式问题

[英]JPanel Format Problems

I have a 2 JPanels, 1 a button Panel and one a Graphic Panel. 我有2个JPanels,1个按钮面板和1个图形面板。 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);
mainPanel.setSize(1000, 1000);

The job of the layout manager is to determine the size of the component, so you would never invoke the setSize() method of a components. 布局管理器的工作是确定组件的大小,因此您永远不会调用组件的setSize()方法。

Instead you give hints to the layout manager on what the size should be. 相反,您可以提示布局管理器大小。 You would do this by overriding the getPreferredSize() method to return an appropriate value. 您可以通过重写getPreferredSize()方法来返回适当的值来实现此目的。 Also, I would pick a more reasonable size (1000, 1000) is a little big to display on most screens. 另外,我会选择一个更合理的尺寸(1000、1000),以便在大多数屏幕上显示。 If you really want your painting area this large then I would add the paint panel to a JScrollPane and then add the scrollpane to the frame. 如果您确实想要如此大的绘画区域,则可以将绘画面板添加到JScrollPane中,然后将滚动窗格添加到框架中。

Try getting your code to work using a BoxLayout. 尝试使用BoxLayout使代码正常工作。 Then I would suggest a better layout manager would be to use a BorderLayout. 然后我建议一个更好的布局管理器是使用BorderLayout。 Then you add the paint panel to the CENTER and the buttons to the SOUTH. 然后将绘画面板添加到CENTER,将按钮添加到SOUTH。 Now as you resize the frame the paint panel will be adjusted in size. 现在,当您调整框架大小时,将调整绘画面板的大小。

canvas.setVisible(true);

Also, the placement of that line of code is wrong. 而且,该行代码的位置是错误的。 You should add all your components to the frame first, before making the frame visible. 在使框架可见之前,应首先将所有组件添加到框架。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM