I am starting with Java Swing
for a second day. I have come across the post briefly explaining the approach with multiple JFrame
is not recommended. According the answer I started to explore the way using CardLayout
.
My trouble is when I call pack()
of the only and main JFrame
, it packs automatically according the main JPanel
, that contains the CardLayout
of several JPanels
created in the Netbeans GUI and not according to actual chosen JPanel
I wish to.
Here is an overview of my main class Main
:
private static String[] PANELS = {"A", "B"};
private static JFrame frame;
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new Main().initialize();
}
});
}
public void initialize() {
JPanel cards = new JPanel(new CardLayout());
JPanelA a = new JPanelA(cards);
cards.add(a, PANELS[0]);
Main.frame = new JFrame("GUI example");
Main.frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Main.frame.add(cards);
Main.frame.pack();
Main.frame.setLocationByPlatform(true);
Main.frame.setVisible(true);
JPanelB b = new JPanelB(cards);
cards.add(b, PANELS[1]);
}
public static JFrame getFrame() {
return Main.frame;
}
public static String getPanel(int i) {
return PANELS[i];
}
Each JPanel is created in the NetBeans GUI, having the following content:
public JPanelA(JPanel parent) {
initComponents();
this.parent = parent;
run();
}
private void run() {
jButton.addActionListener((ActionEvent ae) -> {
Main.getFrame().pack(); // nothing happens
CardLayout cl = (CardLayout) parent.getLayout();
cl.show(parent, Main.getPanel(1));
//Main.getFrame().pack(); // neither anything happens
});
}
The main logics is JFrame
contains the main JPanel cards
that is constructed with CardLayout
and contains both JPanelA a
and JPanelB b
. JPanelA a
is the starting one.
How to make to switch panels with their size, an not the maximum of their ones combined? And is this generally a good approach to start with Java Swing
and the following appliactions?