简体   繁体   English

调整JFrame的大小以适应添加的组件

[英]Resizing a JFrame to fit added components

I'm making a program for fun, it's basically a computer navigation GUI, details not required :) 我正在制作一个有趣的程序,它基本上是一个计算机导航GUI,不需要细节:)

Anyway, so far, I have a button called "new button" that, when clicked, it creates a new button named "test", to an infinite amount. 无论如何,到目前为止,我有一个名为“新按钮”的按钮,当点击它时,它会创建一个名为“test”的新按钮,无限量。 Right now, i have my GUI set up like this: 现在,我的GUI设置如下:

Class Main extends JPanel (the main panel that holds everything in it, size set as) Dimension size = new Dimension(300, 200); Class Main扩展了JPanel(包含所有内容的主面板,尺寸设置为) Dimension size = new Dimension(300, 200); setPreferredSize(size);

JFrame holding the Main JPanel, called like: JFrame持有主JPanel,称为:

panel.frame = new JFrame();
panel.frame.setResizable(false);
panel.frame.setTitle(panel.title);
panel.frame.add(panel);
panel.frame.pack();
panel.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.frame.setLocationRelativeTo(null);
panel.frame.setVisible(true);

So, how would i have the JFrame/JPanel set their size based on the components inside it? 那么,我如何让JFrame / JPanel根据其中的组件设置它们的大小? I've tried to use panel.frame.pack(); 我试过使用panel.frame.pack(); but i get an error most of the time, and the other times it doesnt wrap, it is just a staight line. 但是我大多数时候都会收到错误,而有时它不会包装错误,这只是一个直线。 I want it to resize in the form of a square. 我希望它以正方形的形式调整大小。 Any ideas? 有任何想法吗? Sorry if my question isnt clear/poorly phrased, i've always had issues articulating questions online, much better in person cause i can use my hands! 对不起,如果我的问题不清楚/措辞不好,我总是有问题在网上表达问题,更好的是因为我可以用我的双手! :) Thanks in advance! :) 提前致谢!

Class Main extends JPanel (the main panel that holds everything in it, size set as) Dimension size = new Dimension(300, 200); Class Main扩展了JPanel(包含所有内容的主面板,尺寸设置为)Dimension size = new Dimension(300,200); setPreferredSize(size); 了setPreferredSize(大小);

Don't set the preferred size of the panel. 不要设置面板​​的首选大小。 The layout manager will determine the preferred size based on the components that you add to the panel. 布局管理器将根据您添加到面板的组件确定首选大小。

and the other times it doesnt wrap, 而其他时候它没有包裹,

The default layout manager for a JPanel is a FlowLayout. JPanel的默认布局管理器是FlowLayout。 It is not designed to wrap automatically. 它不是为自动换行而设计的。 Maybe use a different layout manager. 也许使用不同的布局管理器。 Or you can try the Wrap Layout which extends FlowLayout to provide dynamic wrapping. 或者您可以尝试使用Wrap Layout扩展FlowLayout以提供动态包装。

I've tried to use panel.frame.pack(); 我试过使用panel.frame.pack(); but i get an error most of the time 但我大部分时间都会收到错误

What error. 什么错误 I've never seen an error when using the pack() method. 我在使用pack()方法时从未见过错误。

Post a proper SSCCE if you need more help. 如果您需要更多帮助,请发布适当的SSCCE

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

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