简体   繁体   中英

Adding a public class that extends JPanel to JFrame

Basically as the title says, I'm having a bit of an issue working out how to add a class that extends JPanel to a JFrame.

I've looked on here and on other forums, but no answer that I've tried out has work.

I've also got 3 separate files, my main.java my frame.java and panel.java (abbreviated for convenience) Apparently it's good practice to have public classes in different files(?) or so I've been told! I'd appreciate any help on how to actually add the JPanel to the JFrame, even just a link to some documentation I may not have seen. Also I'm open to any constructive criticisms that anyone has about the way I've entered/laid out my code.

Thanks!

main.java

public class MyGuiAttempt {
    public static void main(String[] args) {

        new mainFrame();                

    }
}

frame.java

public class mainFrame extends JFrame {

    public mainFrame() {
        setVisible(true);
        setTitle("My Game");
        setSize(800, 600);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
        add(mainScreenMenu); //This is where I'm clearly going wrong.
    }
} 

panel.java

public class mainScreenMenu extends JPanel {

    public mainScreenMenu() {
        JLabel homeMenuBackground = new JLabel(new ImageIcon("images/my_image.jpg"));
        setPreferredSize(new Dimension(800,600));
        add(homeMenuBackground);
        setVisible(true);
    }

}

您需要创建课程的新实例

 add(new mainScreenMenu());

You're confusing classes and objects . JFrame , JPanel and mainScreenMenu (which should be named MainScreenMenu ) are classes. To have a concrete frame, you need to create an object of type JFrame. To have a concrete panel of type MainScreenMenu, you need to create an object of type MainScreenMenu:

MainScreenMenu theMenu = new MainScreenMenu();
add(theMenu);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM