Reputation: 2051
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
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
Reputation: 44250
JFrame
instanceJFrame
instanceJFrame
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