Question

I have three tabs in this program and on third of them, I have a JTalbe and JButton. I am using GridBagLayout as a LayoutManager but it's quite tricky to set where I want. (But it's really powerful rather than other LayoutManagers I think.) Anyway as you see the picture below. Left is the one that I've done and right one is the one that I'd like to set. Could you guys give me a hint please?

GridBagLayout

This is my code for the left window.

private static void thirdTab(JPanel panel) {
    panel.setLayout(new GridBagLayout());
    GridBagConstraints gbc=new GridBagConstraints();

    String[] columnNames={"name","number","Contents"};
    Object [][]data={
            {"ken","11","haha"},
            {"ben","22","hehe"},
    };

    DefaultTableModel defTableModel=new DefaultTableModel(data,columnNames){
        public boolean isCellEditable(int rowIndex, int mColIndex){
            return false;
        }
    };
    JTable table=new JTable(defTableModel);
    table.getTableHeader().setReorderingAllowed(false) ;

    JScrollPane sroll=new JScrollPane(table);

    //First Column
    gbc.anchor=GridBagConstraints.LAST_LINE_START;
    gbc.weightx=0.1;
    gbc.weighty=0.1;

    gbc.gridx=0;
    gbc.gridy=1;

    JButton button=new JButton("View/Edit");
    panel.add(button,gbc);

    gbc.gridx=0;
    gbc.gridy=0;

    gbc.fill=GridBagConstraints.BOTH;

    panel.add(sroll,gbc);


    panel.setVisible(true);

}
Was it helpful?

Solution

Well, I'm don't use GridBagLayout much but I think you need to use the "anchor" constraint with a value "CENTER. Read the section from the Swing tutorial on How to Use GridBagLayout for a better description of the contraints.

Or, another option is to add the scrollpane containing the table to the CENTER of the BorderLayout. Then you create a JPanelm, which by default uses a FlowLayout. You add your button to this panel and then add the panel to the BorderLayout.SOUTH.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top