This question is very similiar to this: JScrollPane doesn't top align when there is more than enough space to show the content I tried this solution, but it does not work.
When I add a jlabel to jscrollpane, when the jlabel is small, the label becomes centered. It works normally when the scrollbar shows. Setting boxlayout does not change anything. I feel like this isn't working properly because I'm setting a perferred size to the panel? But if I remove the line panel.setPreferredSize(new Dimension((int)(screenSize.width*0.7 - 50), screenSize.height-150));
The label becomes small when there is no text, and grows to accomdate text, which I don't want. If I add the panel instead of the label, it makes the screen scrollable even though there isn't text?
This is my code:
public class Test {
// JFrame
static JFrame frame = new JFrame("Test");
//panel 1
static JPanel panel = new JPanel(new BorderLayout());
// label to display text
static JLabel label = new JLabel();
//scroll panel in main method
public static void main(String[] args) throws Exception {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
label.setBorder(new EmptyBorder(5, 5, 5, 20));
label.setText("any text makes it centered beyond 40 lines");
//create panel
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(label, BorderLayout.NORTH);
panel.add(Box.createVerticalGlue());
panel.setPreferredSize(new Dimension((int)(screenSize.width*0.7 - 50), screenSize.height-150));
panel.setBorder(new EmptyBorder(5, 5, 5, 10));
JScrollPane jspanel = new JScrollPane(label, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
//jspanel.add(label, BorderLayout.CENTER);
jspanel.setPreferredSize(new Dimension((int)(screenSize.width*0.7 - 70), screenSize.height-180));
jspanel.getVerticalScrollBar().setUnitIncrement(20);
jspanel.setBorder(BorderFactory.createEmptyBorder());
jspanel.setAlignmentX(JScrollPane.LEFT_ALIGNMENT);
jspanel.setAlignmentY(JScrollPane.TOP_ALIGNMENT);
//panel.setPreferredSize(new Dimension(640, 480));
//frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(jspanel);
frame.setSize((int)(screenSize.width*0.7), screenSize.height - 50);
frame.revalidate();
frame.pack();
frame.setVisible(true);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…