Brian
Brian

Reputation: 2051

Java - Gui Components do not show up

I have this code to create a simple gui (by hand) and I am trying to display gui components on the frame. However, when I run the program, only the frame shows without showing the components, such as the JTable.

Any idea why ?

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

public class GUI extends JFrame {
    public void buildGui() {
        JFrame frame = new JFrame("Hotel TV Scheduler");    
        frame.setVisible(true);

        Container contentPane = frame.getContentPane();

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());

        JPanel listPanel = new JPanel();
        listPanel.setLayout(new FlowLayout());

        JTable chOneTable = new JTable();
        JTable chTwoTable = new JTable();
        JTable listTable = new JTable();

        listPanel.add(chOneTable);
        listPanel.add(chTwoTable);
        listPanel.add(listTable);

        contentPane.add(listPanel);
    }
}

Upvotes: 1

Views: 3398

Answers (2)

alexvetter
alexvetter

Reputation: 2006

You should set a preferredSize() on the JTables and do a pack() afterwards.

Edit:

Moved setVisible(true) after pack(). This is the order which is used by Sun/Oracle.

public class GUI extends JFrame {
    public void buildGui() {
        JFrame frame = new JFrame("Hotel TV Scheduler");

        Container contentPane = frame.getContentPane();

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());

        JPanel listPanel = new JPanel();
        listPanel.setLayout(new FlowLayout());

        Dimension d = new Dimension(100, 100);

        JTable chOneTable = new JTable();
        chOneTable.setPreferredSize(d);

        JTable chTwoTable = new JTable();
        chTwoTable.setPreferredSize(d);

        JTable listTable = new JTable();
        listTable.setPreferredSize(d);

        listPanel.add(chOneTable);
        listPanel.add(chTwoTable);
        listPanel.add(listTable);

        contentPane.add(listPanel);

        frame.pack();
        frame.setVisible(true);
    }
}

Upvotes: 3

mre
mre

Reputation: 44250

  1. Construct the JFrame instance
  2. Add the components to the JFrame instance
  3. Realize the JFrame instance (i.e. setVisible(true))

The reason none of the components show up when the JFrame instance is shown is because you add components to it after it has been realized. If you want to components to show up, either follow the steps above, or at the end of the buildGui method, revalidate/repaint the container.

Upvotes: 2

Related Questions