Home > Enterprise >  Add a jpanel from another class
Add a jpanel from another class

Time:06-13

I am a newbie in java. I want to add a jpanel placed in another class but don't know how to do it. Thank you so much!

GUIFile.java

    import java.awt.*;
    import javax.swing.*;
    
    public class GUIFile {
        public void GUIFile() {
            JFrame MainFrame = new JFrame("Prova");
            MainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            MainFrame.setLayout(null);
            MainFrame.setSize(400, 300);
            MainFrame.setLocationRelativeTo(null);
            MainFrame.setResizable(false);
            MainFrame.setVisible(true);
        }
    public static void main(String[] args) {
        GUIFile interfaccia = new GUIFile();
        interfaccia.GUIFile();        
    }
}

PanelFile.java

import java.awt.*;
import javax.swing.*;

public class PanelFile {
    public void PanelFile() {
        JPanel panel=new JPanel();
        panel.setLayout(null);
        panel.setVisible(true);
        panel.setBounds(0, 0, 400, 300);
        JButton b1=new JButton("Button 1");
        b1.setBounds(10, 10, 80, 30);
        panel.add(b1);
    }
}

CodePudding user response:

What you can do is let PanelFile extend the JPanel class, meaning it becomes a JPanel which you can add your own stuff to (like your buttons). You can then make an instance of your panel class and set that as the content pane (using frame.setContentPane() for your frame you create in GUIFile.

GUIFile.java

public class GUIFile {
    public GUIFile() {
        JFrame MainFrame = new JFrame("Prova");
        MainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        MainFrame.setSize(400, 300);
        PanelFile panel = new PanelFile();
        MainFrame.setContentPane(panel);
        MainFrame.setLocationRelativeTo(null);
        MainFrame.setResizable(false);
        MainFrame.setVisible(true);
    }

    public static void main(String[] args) {
        GUIFile interfaccia = new GUIFile();
    }
}

PanelFile.java

public class PanelFile extends JPanel {
    public PanelFile() {
        setLayout(null);
        setVisible(true);
        setBounds(0, 0, 400, 300);
        JButton b1 = new JButton("Button 1");
        b1.setBounds(10, 10, 80, 30);
        add(b1);
    }
}
  • Related