The way you are approaching this seems to be pretty complex hence this weird behavior. (Looks like a look and feel problem? - show the part of the code that sets it)
However, I suggest you to create only one JFrame
(this question explains why you should do that), set the layout of its content pane to BorderLayout
and keep it like this. Its a rare situation to mess up with content panes. After that create independent JPanels
representing the tab(s) you would like to have. Finally create a JTabbedPane
with these panels and add it to the content frame of the JFrame
.
A small example would be:
public class TabbedPanelExample extends JFrame {
public TabbedPanelExample() {
super("test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JTabbedPane pane = new JTabbedPane();
pane.addTab("FirstTab", createFirstTab());
pane.addTab("SecondTab", createSecondTab());
add(pane);
setSize(400, 400);
setLocationRelativeTo(null);
}
private Component createFirstTab() {
JPanel panel = new JPanel(new FlowLayout());
panel.add(new JLabel("Some Component"));
panel.add(new JTextField("Some Other Component"));
return panel;
}
private Component createSecondTab() {
JPanel panel = new JPanel(new FlowLayout());
panel.add(new JLabel("Some Component"));
panel.add(new JButton("Some Other Component"));
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new TabbedPanelExample().setVisible(true);
});
}
}
Post edit based on this comment:
Well I do have a Jframe with a lot of elements added to it so it kinda
is a hassle to switch it all to panels;
A JFrame
cannot have a lot of elements. You take a look on how to use root panes. The container that "has a lot of elements" of a JFrame
is its rootpane which is mostly completed by its contentpane. When you frame.add(component)
, you add the component to its content pane. Guess what? A JFrame
's content pane is a JPanel. So are a already to panels.
Now in order to make this work, try to do as i said and frame.setLayout(new BorderLayout(); //changes layout to contentpane
. Assuming you have a bunch of components (lets say comp1,comp2) and you are adding them like:
frame.add(comp1);
frame.add(comp2);
You must do the following in order to make it clear. Create a JPanel
and instead of frame.add(comp1)
, do panel.add(comp1)
. So this JPanel has all the components you added in JFrame. After that create your JTabbedPane
:
JTabbedPane pane = new JTabbedPane();
pane.addTab("tab", panel);
and finally add this pane to the content pane of your JFrame
:
frame.add(pane);
In conclusion, you will move all the components you have added to your frame into a JPanel, add this JPanel to a JTabbedPane, and finally add this JTabbedPane to the frame (contentpane). Frame has only one component.