Reputation: 109
For Java GUI homework extra credit, I am trying to add a couple of Panels to a JTabbedPane. Actually, they were JFrames, but I just changed to extend JPanel instead of JFrame and removed the main(). Anyway, the when I run the main(),the JTabbedPane, and both panels show up, but separate. What am I missing?
import javax.swing.*;
public class TabbedPane extends JFrame
{
JPanel DayGui = new JPanel();
JPanel OfficeAreaCalculator = new JPanel();
JLabel firstLabel = new JLabel("First tabbed pane");
JLabel secondLabel = new JLabel("Second tabbed pane");
JTabbedPane tabbedPane = new JTabbedPane();
// constructor
public TabbedPane()
{
DayGui.add(firstLabel);
OfficeAreaCalculator.add(secondLabel);
tabbedPane.add("First Panel", DayGui);
tabbedPane.add("Second Panel", OfficeAreaCalculator);
add(tabbedPane);
}
public static void main(String[] args)
{
TabbedPane tab = new TabbedPane();
tab.pack();
tab.setVisible(true);
JTabbedPane DayGui = new JTabbedPane();
JTabbedPane OfficeAreaCalculator = new JTabbedPane();
DayGui dg = new DayGui();
OfficeAreaCalculator oac = new OfficeAreaCalculator();
}
}
Upvotes: 0
Views: 2293
Reputation: 159864
You're creating 2 pairs of variables for referencing components to add to the JFrame
but adding the ones that point to blank JPanels
. Study this code based on the official tutorial
public class TabbedPaneApp {
private static void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane firstPanel = new JTabbedPane();
JTabbedPane secondPanel = new JTabbedPane();
JLabel firstLabel = new JLabel("First tabbed pane");
JLabel secondLabel = new JLabel("Second tabbed pane");
JTabbedPane tabbedPane = new JTabbedPane() {
public Dimension getPreferredSize() {
return new Dimension(500, 400);
};
};
firstPanel.add(firstLabel);
secondPanel.add(secondLabel);
tabbedPane.add("First Panel", firstPanel);
tabbedPane.add("Second Panel", secondPanel);
frame.add(tabbedPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Upvotes: 2