Search code examples
javaswinglayout-managerboxlayout

JTable change position of other components on BoxLayout


My problem is that when I add JTable to panel all other components are moved to right side for about 20% of panel lenght, code is:

JFrame frame = new JFrame("my frame");

JPanel panel = new JPanel();
BoxLayout layout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
panel.setLayout(layout);

JButton but1 = new JButton("button1");
but1.setAligmentX(0);
panel.add(but1);

String[] columnNames = {"kolumna 1", "kol 2", "kol3"};
JTable itemTable = new JTable(new DefaultTableModel(columnNames, 10));
panel.add(new JScrollPane(itemTable));

JButton but2 = new JButton("button2");
but2.setAligmentX(0);
panel.add(but2);

frame.setContentPane(panel);
frame.setVisible(true);

and the result is

    button1
TABLEEEEEEE
TABLEEEEEEE
TABLEEEEEEE
TABLEEEEEEE
    button2

instead of

button1
TABLEEEEEE
TABLEEEEEE
TABLEEEEEE
TABLEEEEEE
button2

what am i doing wrong?

/edit

i checked that JTextArea is fine, but JScrollPane and JTable cause this problem, used button with .setAligment(0) method but same result


Solution

  • try this code

        JButton b1 = new JButton("button1");
        String[] columnNames = { "kolumna 1", "kol 2", "kol3" };
        JTable itemTable = new JTable(new DefaultTableModel(columnNames, 10));
        JScrollPane scrollPane = new JScrollPane(itemTable);
    
        JButton b2 = new JButton("button2");
    
        b1.setAlignmentX(Component.LEFT_ALIGNMENT);
        scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);
        b2.setAlignmentX(Component.LEFT_ALIGNMENT);
    
        JPanel panel = new JPanel();
        BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
        panel.setLayout(layout);
    
        panel.add(b1);
        panel.add(scrollPane);
        panel.add(b2);
    

    There is more inforamtion here : java BoxLayout panel's alignment