Search code examples
javaswingintellij-idea

Java Swing - Show multiple panels


I'm using the Java Swing UI Designer in IntelliJ :( I designed something in the designer using multiple panels and spacers with 1 parent panel. When I add the main panel, the first one inside it shows, but the others don't.

Frame structure:

  • Panel1
    • GradientPanel
      • Panel
      • Spacers

What I designed What I designed

What I get What I get when I run it

import keeptoo.KGradientPanel;

import javax.swing.*;

public class LogIn extends JFrame{
private KGradientPanel KGradientPanel1; //Automatically added by the designer
private JPanel panel1; //Automatically added by the designer

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("CarbonTec Dashboard");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setSize(1800,1000);
    frame.setContentPane(new LogIn().panel1);
    frame.setVisible(true);

    ImageIcon imageIcon = new ImageIcon("Icon.png");
    frame.setIconImage(imageIcon.getImage());
}
}

Solution

  • First you need to know that your class is a JFrame, but in the main method you create a new JFrame.

    Better would be to have a class Program that has the main method. In this main method you make a new instance of LogIn.

    The Program class can look like this:

    public class MainProgram {
    
      public static void main(String[] args) {
        LogIn logIn = new LogIn();
      }
    }
    

    The LogIn class should then look like this:

        import keeptoo.KGradientPanel;
        import javax.swing.*;
    
        public class LogIn extends JFrame{
        private KGradientPanel KGradientPanel1 = new KGradientPanel(); //Automatically added by the designer
        private JPanel panel1 = new JPanel(); //Automatically added by the designer
        
    
        // This is the constructor.
        public LogIn {
        
            setTitle("CarbonTec Dashboard");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setResizable(false);
            setSize(1800,1000);
            setContentPane(panel1);
        
            ImageIcon imageIcon = new ImageIcon("Icon.png");
            setIconImage(imageIcon.getImage());
    
            // Here you can add the gradient panel to panel1.
            panel1.add(KGradientPanel1); // The name should be written in lower case.
           
            setVisible(true);
        }
    

    But I don't know why you need the panel1, you could add the KGradientPanel directly.