Pregunta

I'm making a program for fun, it's basically a computer navigation GUI, details not required :)

Anyway, so far, I have a button called "new button" that, when clicked, it creates a new button named "test", to an infinite amount. Right now, i have my GUI set up like this:

Class Main extends JPanel (the main panel that holds everything in it, size set as) Dimension size = new Dimension(300, 200); setPreferredSize(size);

JFrame holding the Main JPanel, called like:

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? I've tried to use 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!

¿Fue útil?

Solución

Class Main extends JPanel (the main panel that holds everything in it, size set as) Dimension size = new Dimension(300, 200); setPreferredSize(size);

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. 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.

I've tried to use 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.

Post a proper SSCCE if you need more help.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top