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.
Layout
– MonostomeRows
andColumns
, which also can determine the size for the same. Use the appropriateConstructor
while initializing or setRows
andColumns
as suggested in the answers. UsingFlowLayout (default for the JPanel)
so no change needed on the Layout concerned as noted in some answers (IMHO), you will be able to see yourJTextArea
once you specifyRow and Column
for the same. – LemastersetXxXSize()
methods, let the Layout used by you, worry about that part. – Lemaster