Set size of JTable in JScrollPane and in JPanel with the size of the JFrame

Posted by user1761818 on Stack Overflow See other posts from Stack Overflow or by user1761818
Published on 2012-11-03T21:24:51Z Indexed on 2012/11/03 23:01 UTC
Read the original article Hit count: 247

Filed under:
|
|
|
|

I want the table with the same width as the frame and also when I resize the frame the table need to be resized too. I think setSize() of JTable doesn't work correctly. Can you help me?

import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;

public class Main extends JFrame {

    public Main() {
        setSize(400, 600);
        String[] columnNames = {"A", "B", "C"};
        Object[][] data = {
            {"Moni", "adsad", 2},
            {"Jhon", "ewrewr", 4},
            {"Max", "zxczxc", 6}
        };

        JTable table = new JTable(data, columnNames);
        JScrollPane tableSP = new JScrollPane(table);

        int A = this.getWidth();
        int B = this.getHeight();

        table.setSize(A, B);
        JPanel tablePanel = new JPanel();
        tablePanel.add(tableSP);
        tablePanel.setBackground(Color.red);

        add(tablePanel);
        setTitle("Marks");

        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                Main ex = new Main();
                ex.setVisible(true);
            }
        });
    }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about swing