MUHAMMAD Siyab
MUHAMMAD Siyab

Reputation: 446

JTable not showing in java

I'm new to java..I want to show a table in my GUI. I know there are several questions like this but that didn't help me. Any help would be appreciated.

Test.java

package test;

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


    class Test {

        JFrame frame;
        JTable table;
        Container pane;

        public void initGUI () {
            frame = new JFrame("Table");
            frame.setLayout(null);
            frame.setVisible(true);
            frame.setBounds(100, 100, 500, 500);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            pane = frame.getContentPane();

            Object[][] rows = {
                {"Amir", "Karachi"},
                {"Noman", "Quetta"},
                {"Salman", "Rawalpindi"}
            };
            Object[] cols = {"Name", "City"};

            table = new JTable(rows, cols);
            pane.add(new JScrollPane(table));
        }

        public static void main (String args[]) {
            Test obj = new Test();
            obj.initGUI();
        }

    }

Upvotes: 0

Views: 923

Answers (2)

Vasyl Lyashkevych
Vasyl Lyashkevych

Reputation: 2232

Except frame.setLayout(null); you can exclude getContentPane();. Here is worked one:

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

class Test {

    JFrame frame;
    JTable table;
    Container pane;

    public void initGUI() {
        frame = new JFrame("Table");
        frame.setVisible(true);
        frame.setBounds(100, 100, 500, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Object[][] rows = {
            {"Amir", "Karachi"},
            {"Noman", "Quetta"},
            {"Salman", "Rawalpindi"}
        };
        Object[] cols = {"Name", "City"};

        table = new JTable(rows, cols);
        frame.add(new JScrollPane(table));

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String args[]) {
        Test obj = new Test();
        obj.initGUI();
    }
}

OUTPUT: enter image description here

Upvotes: 0

camickr
camickr

Reputation: 324197

frame.setLayout(null);

Don't use a null layout.

Because you don't use a layout manager the size of the scrollpane is (0, 0) so there is nothing to paint.

Swing was designed to be used with layout managers. Leave the default layout manager of the frame as the BorderLayout.

Also, a frame should be made visible AFTER all components have been added to the frame.

Read the section from the Swing tutorial on How to Use Tables for working examples to get you started. Use the structure of the code found in the tutorials and then modify it.

Upvotes: 2

Related Questions