Imported Class of Components are Hidden
I'm not sure how to word this, but I did my best in the title. I'm creating a GUI and for simplicity it has a frame, a tabbed pane, a panel, and a button. Originally, they started in the same class, but I want to try splitting them into two classes.
So now I have this...
Code java:
import FirstPanel.java
public class GUI extends JFrame{
private JFrame frame;
private JTabbedPane tabs;
private FirstPanel firstPanel;
//Constructor
public GUI(){
frame = new JFrame();
tabs = new JTabbedPane();
firstPanel = new FirstPanel();
tabs.add("Tab #1", firstPanel);
frame.add(tabs);
//Set frame visible and the size etc...
}
public static void main(String[] args){
GUI gui = new GUI();
gui.setVisible(true);
}
What is FirstPanel? It's the second class!
Code java:
public class FirstPanel extends JPanel{
private JPanel panel;
private JButton button;
//Constructor
public FirstPanel(){
panel = new JPanel();
button = new JButton("Why can't you see me?");
panel.add(button);
}
}
The output I am looking for is a frame with a tab with a panel with a button.
Now, when I run GUI, I get a frame with a tab with a panel but there is no button displayed. I thought at first that it was because all components need to be in the same class, but I dismiss that because I am at least getting ONE panel.
I get no errors or output from this, only a missing button.
Any help is greatly appreciated!
Cheers!
-Polaris395 :confused:
Re: Imported Class of Components are Hidden
FirstPanel IS A JPanel (it extends JPanel). It also HAS A JPanel (named panel). You're adding the JButton to the HAS A JPanel, but you're adding the IS A JPanel to the JFrame.
Re: Imported Class of Components are Hidden
Oh! Duh! I guess I've been looking at my code to long to notice that, lol.
Thanks!
Re: Imported Class of Components are Hidden
Quote:
Originally Posted by
polaris395
Oh! Duh! I guess I've been looking at my code to long to notice that, lol.
Thanks!
No problem. This is one reason people argue for "composition over inheritance". If FirstPanel doesn't actually modify the functionality of JPanel, there's no reason for it to extend JPanel. Instead, just have a getPanel() method that returns the JPanel after whatever initialization is done. I might not be explaining it that great, but a google of "composition over inheritance" brings back some good results.