I have a JPanel
with several JLabel
s in it and a JTextPane
. I want them to be below each other (so no two two labels on the same line), and aligned to the left. I have tried several things:
- Using a
BoxLayout
withBoxLayout.Y_AXIS
works for properly getting all elements below each other. However, while theJTextPane
correctly aligns to the left, theJLabel
s stay centered, even when calling several methods to try and get the alignment to the left (see code below). - Using a
GridLayout
will correctly put the elements below each other and align them to the left, but then the elements will be vertically spread all over theJPanel
with huge spaces between the text lines. I want all elements to be in the top of the panel as far as possible.
private final void init() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(new JLabel("a"));
final JLabel label = new JLabel();
final JTextPane pane = new JTextPane();
add(label);
add(pane);
// these three lines seem to be ignored
label.setHorizontalAlignment(SwingConstants.LEFT);
label.setAlignmentX(LEFT_ALIGNMENT);
label.setHorizontalTextPosition(SwingConstants.LEFT);
pane.setForeground(Color.RED);
pane.setEditable(false);
}
How can I get this right?