It’s my first Post here, so forgive me please if i’m doing something wrong.
My Problem is:
I am trying to add Components to a JPanel with defined values for Size etc.
But when i add them to the Panel, they do absolutely not have the Size and Location they should have.
For example:
public class Console extends JFrame {
private JPanel mainPanel = new JPanel();
private JTextArea textField = new JTextArea();
private JTextArea textField2 = new JTextArea();
public Console() {
this.setSize(500,300);
this.mainPanel.setSize(this.getWidth(),this.getHeight());
this.textField.setEditable(false);
this.textField.setSize(this.mainPanel.getWidth(), 100);
this.textField.setPreferredSize(new Dimension(this.mainPanel.getWidth(),this.mainPanel.getHeight()));
this.textField.setLocation(0, 0);
this.textField.setText("some text");
this.textField.setVisible(true);
this.textField2.setSize(this.mainPanel.getWidth(),200);
this.textField2.setPreferredSize(new Dimension(this.getWidth(),this.getHeight()));
this.textField2.setLocation(0,this.mainPanel.getHeight()-this.textField.getHeight());
this.textField2.setText("blabla");
this.textField2.setVisible(true);
this.mainPanel.add(textField);
this.mainPanel.add(textField2);
this.mainPanel.setVisible(true);
this.add(this.mainPanel);
// I know you should not call setVisible() in the Constructor, just for making Code more simple here.
this.setVisible(true);
}
}
When i start the Application, both JTextArea’s are really small and somewhere in the middle (not as set above) while the mainPanel is correct.I tried to call setSize() and setPreferredSize() in different Places in the Code, but it didn’t work. I know it is better to use a LayoutManager for doing this as far as i heard but to be honest, i do not get how to use it correctly. I checked it on Oracle Doc’s but i would appreciate it if someone could post a clean Solution for this, Thanks in Advance.
You need to set a proper
Layoutfor yourContainer. YousetLayoutfor a Container likeJFrame,JPaneland so on. You don’t add other components to layout, but to a container. Then it would layout them accordingly. It is how it works.With proper layout you would not need to call
setLocation(). AlsosetVisible(true)is excessive, because true is default values for those components in your code.Better not to extend
JFrame, extendJPanelinstead and add it to JFrame.Please, learn about EDT and
SwingUtilities.invoketLater()you need to use it.Also you can save some bytes, not typing
this.all the time.