Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fitting a JTable Inside a Panel

Tags:

java

swing

jtable

I'm using a JTable and adding it to a panel which uses a gridbaglayout like so:

JTable qdbs = new JTable(rowData, columnNamesVector);
qdbs.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

panel.add(qdbs, c);

I don't want the table to be in a scroll pane, but I do want the table to take up the entire width of the panel. How would I accomplish this?

An SSCCE as requested:

import javax.swing.*;
import java.awt.*;

public class Main{

    public static void main(String[] args) {
    new TestFrame();
    }

    public static class TestFrame extends JFrame{
    public TestFrame() {
        this.setTitle("SSCCE");

        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();

        c.gridx = 0;
        c.gridy = 0;

        c.insets = new Insets(10,10,10,10);
        JTable testTable = new JTable(10,2);
        panel.add(testTable, c);

        this.add(panel);
        this.pack();
        this.setVisible(true);
    }
    }

}

I would like this table to always take up the entire width of the panel (except the insets). Currently the table does not change size when the frame is resized.

like image 272
Alex Bliskovsky Avatar asked May 18 '11 20:05

Alex Bliskovsky


People also ask

How do you add a table to a panel?

I writing blog to add JTable in Jpanel. JTable is an component of the swing package in java technology and also it's a class, so we need to create instance and using add() method add the JTable in JPanel. Here, add() method used for adding the components in swing container.

How do you make a JTable column invisible?

To hide a column (or more) in a JTable, do not give the column name. To get the hidden data, you must use the TableModel.

What is JTable and its purpose?

In Java, JTable is used to edit or display 2-D data which consists of rows and columns. It is almost similar to a spreadsheet that contains data in a tabular form. JTable can be created by instantiating the class javax. swing. JTable.


1 Answers

You need to add constrains to tell the layout what to do with more space. In your SSCCE add these items:

  c.fill = GridBagConstraints.BOTH;
  c.weightx = 1;
  c.weighty = 0;
like image 160
jzd Avatar answered Oct 14 '22 18:10

jzd