Ross Murphy
Ross Murphy

Reputation: 1

How can I get the JTextArea to appear above the JTextField?

When I add both of them to SOUTH using BorderLayout, only the JTextArea appears. I'm using the text field as an input which is then displayed in the text area as an output above it with some other text.

It works if I set the text area to NORTH but it doesn't look great.

JPanel cmdPanel = new JPanel(new BorderLayout());

field = new JTextField(20);
cmdPanel.add(field, BorderLayout.SOUTH);

JTextArea output=new JTextArea();
output.setEditable(false);
output.setLineWrap(true);
cmdPanel.add(output, BorderLayout.SOUTH);

This image shows how it looks now with the TextArea set to NORTH. I'm just trying to have it appear over the TextField and move up the screen as outputs are added.

Image

Upvotes: 0

Views: 126

Answers (2)

Abra
Abra

Reputation: 20914

You have not provided a minimal, reproducible example but from the screen capture of your running app, it looks like you are explicitly setting the size of the JFrame. Rather than doing that, you should call method pack. Note that you should call that method after you have added both your JTextField and JTextArea to the cmdPanel and also after you have added cmdPanel to the JFrame. Also you should call method setVisible on the JFrame after calling method pack().

You should also make sure that the JTextArea has a preferred size before adding it to cmdPanel. One way to do this is by calling the constructor that takes the number of rows and columns parameters.

Maybe also wrap the JTextArea in a JScrollPane and make that the "center" component of cmdPanel?

JPanel cmdPanel = new JPanel(new BorderLayout());

field = new JTextField(20);
cmdPanel.add(field, BorderLayout.SOUTH);

JTextArea output=new JTextArea(10, 20);
output.setEditable(false);
output.setLineWrap(true);
JScrollPane scrollPane = new JScrollPane(output);
cmdPanel.add(scrollPane, BorderLayout.CENTER);

Upvotes: 1

Aislan Nadrowski
Aislan Nadrowski

Reputation: 11

It is not possible to add two components in the same position (i.e BorderLayout.PAGE_END). To add more components in the same position, you should create a JPanel, add the components on it and then add the JPanel to the desirable position (i.e BorderLayout.PAGE_END).

Upvotes: 0

Related Questions