Moving Jtable in Java, Swing, Flowlayout

878 views Asked by At

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?

2

There are 2 answers

0
alex2410 On BEST ANSWER

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.

0
Chris On

With FlowLayout you can't move the object around. All objects are placed in one line.

Try to use the BorderLayout or GridBagLayout. Here's a visual guide to Layout Managers.

Panel myTable = new Panel(new GridBagLayout());
GridBagConstraints c1 = new GridBagConstraints();

c1.fill = GridBagConstraints.HORIZONTAL;    //area
c1.ipadx = 0;                               //spacing
c1.ipady = 0;                               //spacing
c1.weightx = 1.0;                           //horizontal
c1.weighty = 1.0;                           //vertical 
c1.anchor = GridBagConstraints.CENTER;      //orientation
c1.insets = new Insets(10,10,10,10);        //padding
c1.gridx = 0;                               //column
c1.gridy = 0;                               //line
c1.gridheight = 1;                          //number of lines
c1.gridwidth = 1;                           //number of columns

myTable.add(new JScrollPane(table),c1);

You can move your table if you change the orientation.