Aligning JLabel to Left or Right inside BoxLayout with Y_AXIS Constraint of JPanel

4.9k views Asked by At

I have a JPanel with Constraint's of Y_Axis so that whenever I add a new Component it will automatically be Added on a new Line.But the Problem is that the Label inside is not Aligned to Left or Right. It is displayed at some distance above the JTable. How can JLabel be displayed at desired Alginment.

JPanel panel = new JPanel();

panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));

Then I added a JLabel inside panel.

JLabel labelSemester = new JLabel("Semester 1: ",SwingConstants.LEFT);
panel.add(labelSemester);

After label, I added a new JTable inside panel,

// Column Names for the Table
Object[] col_names = {"ID", "Name", "CH", "Marks", "Grade"};
// row data for the table
Object[][] table_rows = {{"CS123","Introduction to Computing",3,80,"A-"}};// One row only

JTable table = new JTable(table_rows, col_names);

panel.add(new JScrollPane(table));

Then I added a JFrame and added the Panel to show in the frame

JFrame frame = new JFrame();
// frame Title
frame.setTitle("DMC");
frame.setSize(400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

// adding panel inside frame
frame.add(panel);

// displaying frame
frame.show()

Note: I have added code for auto Adjustment of column width of JTable. Output can be seen from attached Image

1

There are 1 answers

0
camickr On BEST ANSWER

All components added to the BoxLayout need the same alignmentX, otherwise you can get some weird layouts:

//JLabel labelSemester = new JLabel("Semester 1: ",SwingConstants.LEFT);
JLabel labelSemester = new JLabel("Semester 1: ");
label.semester.setAlignmentX(JLabel.LEFT_ALIGNMENT);
panel.add(labelSemester);

...

JTable table = new JTable(table_rows, col_names);
//panel.add(new JScrollPane(table));
JScrollPane scrollPane = new JScrollPane( table );
scrollPane.setAlignmentX(JScrollPane.LEFT_ALIGNMENT);
panel.add( scrollPane );

Read the section from the Swing BoxLayout tutorial on Fixing Alignment Problems for more information. Keep a link to the tutorial handy for all Swing basics.