Search code examples
javaswingflowlayout

Moving Jtable in Java, Swing, Flowlayout


I have this code so far:

public class Table extends JFrame {

    JTable table;

    public Table()  
    {
        setLayout (new FlowLayout());   //Default layout

        String[] columnNames = {"Fly model", "Fly kode",
                "Destination", "Tidspunkt"};

        Object[][] data = {
            {"Boeing 737", "Ab79SO", "Oslo", "22:00"},
            {"MD125", "Tb682O", "Stockholm", "15:21"},
            {"Boeing 737", "HJ72SR", "Reikjavic", "08:13"},
        };
        table = new JTable(data, columnNames);
        table.setPreferredScrollableViewportSize(new Dimension(500, 50));
        table.setFillsViewportHeight(true);
        setVisible(true);

        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
    }

    public JTable returnJTable()
    {
        setVisible(false);
        return table;
    }
}

I am not used to use FlowLayout, and I therefore don't know how to move this object around in the JFrame that I am using. I know that when you use a null (absolute) layout, you can use setBounds() to tell the JFrame where to position the elements. But how do I do that in FlowLayout?


Solution

  • You can't do that with FlowLayout. You can add new components horizontally or vertically one by another, but you can't to add component to specific position. You can try to use some tricks with blank panels or labels for spaces before/after your JTable, but better to use another layout.

    Try to use BorderLayout, it's simple and with help of that, you can positioning your JTable in different places. Read tutorial for that.

    Or you can use another LayoutManager, read about them and choose.