[英]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. 基本上如标题所述,我在解决如何添加将JPanel扩展到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! 我也有3个单独的文件,分别是main.java,frame.java和panel.java(为方便起见而缩写)显然,在不同文件中有公共类是一个好习惯(?),所以有人告诉我! 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.
我非常感谢您提供有关如何将JPanel实际添加到JFrame的帮助,甚至只是指向一些我可能没有看到的文档的链接。 Also I'm open to any constructive criticisms that anyone has about the way I've entered/laid out my code.
同时,我也欢迎任何人对我输入/布置我的代码的方式提出的建设性批评。
Thanks! 谢谢!
main.java main.java
public class MyGuiAttempt {
public static void main(String[] args) {
new mainFrame();
}
}
frame.java 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 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. JFrame
, JPanel
和mainScreenMenu
(应命名为MainScreenMenu
)是类。 To have a concrete frame, you need to create an object of type JFrame. 要拥有一个具体的框架,您需要创建一个JFrame类型的对象。 To have a concrete panel of type MainScreenMenu, you need to create an object of type MainScreenMenu:
要具有MainScreenMenu类型的具体面板,您需要创建MainScreenMenu类型的对象:
MainScreenMenu theMenu = new MainScreenMenu();
add(theMenu);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.