Developer Android
Developer Android

Reputation: 595

Adding a table to java swing

I already have a panel to which I have added buttons and a text area. Now I need to display a table below it . The panel's layout is AbsoluteLayout and if I use the following method to inflate the table it shows up empty

        String data[][] = { { "vinod", "BCA", "A" }, { "Raju", "MCA", "b" },
                { "Ranjan", "MBA", "c" }, { "Rinku", "BCA", "d" } };

        String col[] = { "Name", "Course", "Grade" };
        JTable table = new JTable(data, col);
        table.setLocation(25,343);
        panel.add(table, BorderLayout.CENTER);

However when I use setbounds the table display okay but it takes up more space than it requires and the lines dont show in the empty space and it looks bad. Does anyone know how to set only the x,y location of a table and leave the rest of the positioning (width and height to accommodate just what is required)

String data[][] = { { "vinod", "BCA", "A" }, { "Raju", "MCA", "b" },
        { "Ranjan", "MBA", "c" }, { "Rinku", "BCA", "d" } };

String col[] = { "Name", "Course", "Grade" };
JTable table = new JTable(data, col);
table.setBounds(25,343,122,122);
panel.add(table, BorderLayout.CENTER);

Upvotes: 1

Views: 2093

Answers (2)

mKorbel
mKorbel

Reputation: 109813

Upvotes: 5

Mikhail Vladimirov
Mikhail Vladimirov

Reputation: 13890

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
frame.add (Box.createVerticalStrut(343), BorderLayout.NORTH);
frame.add (Box.createHorizontalStrut(25), BorderLayout.WEST);
frame.add (new JTable (5, 5), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);

Upvotes: 0

Related Questions