user1794564
user1794564

Reputation: 33

JLabel on top of JScrollpane

No matter what alignment I use, the JLabel is always displayed on the left of my JScrollpane and not on top of it. Here is the code:

final JPanel choseTypeOfAnswerText = new JPanel();
JLabel label = new JLabel("Answer:");

label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.TOP);
choseTypeOfAnswerText.add(label);

//now a scroll pane for the answer area
JScrollPane answerScroller = new JScrollPane(answerArea);
answerScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
answerScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
choseTypeOfAnswerText.add(answerScroller, BorderLayout.CENTER);
//add(answerScroller);
choseTypeOfAnswerText.setVisible(true);

Upvotes: 1

Views: 1509

Answers (3)

Chris
Chris

Reputation: 1643

You forgot to tell, that label is supposed to be added in the top area of the panel:

choseTypeOfAnswerText.add(label, BorderLayout.PAGE_START);

And, like mKorbel stated, you have to set the LayoutManager to BorderLayout

Upvotes: 1

Random42
Random42

Reputation: 9159

If you use a JScrollPane you do not need to put it in a JPanel; it actually replaces the JPanel. You can add your label to the JScrollPane.

Upvotes: 0

mKorbel
mKorbel

Reputation: 109823

  • choseTypeOfAnswerText.add(answerScroller, BorderLayout.CENTER);

  • have to change LayoutManger to the BorderLayout (JPanel.setLayout(new BorderLayout()))

  • JPanel has implemented FlowLayout, corresponding with a.m. described issue

  • only Top-Level Containers have got implemented BorderLayout by default

Upvotes: 4

Related Questions