Search code examples
javaswinguser-interfacejscrollpanejlabel

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);

Solution

    • 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