Swing – How to fit a JTable into a JPanel and make it auto resizeable

grid layoutjframejpaneljtableswing

i'm adding a JTable into a JPanel wich is using a GridLayout but i don't get the same behavior like when you add a JButton…

I want to know how can i get the same auto resizing behavior with my JTable like when you add a JButton into a JPanel that uses a GridLayout and also I want the table use the whole space of the panel.

Sorry about spelling, english is not my maternal language. Hope you guys can help me!

This is my code:

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

    class Frame extends JFrame {

        private JPanel center;
        private JTable table;

        public Frame(){
            super("Test Jtable");
            this.setLayout(new BorderLayout());        

            this.center = new JPanel(); 
            this.center.setLayout(new GridLayout());

            this.table = new JTable(50,50);
            this.table.setGridColor(Color.black);
            this.table.setCellSelectionEnabled(true);                      

            this.center.add(this.table);
            this.add(this.center,BorderLayout.CENTER);
        }
    }

    public class TestFrame {

        public static void main(String... args) {
            Frame f =new Frame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize(400,400);
            f.setVisible(true);
        }
    }

Best Answer

Add your table to a scroll pane, as shown in this example.

this.center.add(new JScrollPane(this.table));

Addendum: I'd advocate something like this using pack(); other arrangements are possible, but less usable. The setPreferredScrollableViewportSize() method may be helpful, too.

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

class Frame extends JFrame {

    private JPanel center;
    private JTable table;

    public Frame() {
        super("Test Jtable");
        this.setLayout(new BorderLayout());
        this.center = new JPanel();
        this.center.setLayout(new GridLayout());
        this.table = new JTable(50, 10);
        this.table.setGridColor(Color.black);
        this.table.setCellSelectionEnabled(true);
        this.center.add(this.table);
        this.add(new JScrollPane(this.center), BorderLayout.CENTER);
    }
}

public class TestFrame {

    public static void main(String... args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                Frame f = new Frame();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.pack();
                f.setVisible(true);
            }
        });
    }
Related Topic