我目前正在尝试重新创建Breakout,并想知道如何实现基本的gui。我的结构是一个包含JPanel的JFrame,而JPanel实际上包含游戏的元素。JFrame通过将其添加到其内容窗格frame.getContentPane().add(myPanel)中来获取此JPanel。
我的问题是,保存游戏元素的类应该扩展JPanel还是简单地返回JPanel?
public class myPanel {
private JPanel panel;
public myPanel() {
panel = new JPanel();
//do stuff with the panel
}
public JPanel getPanel() {
return panel;
}
}
public class myPanel extends JPanel{
public myPanel() {
panel = new JPanel();
//do stuff with the panel
}
}发布于 2021-06-26 11:48:26
我认为,在大多数情况下,您应该明确使用extend。
这也是错误的:
public class myPanel extends JPanel{
public myPanel() {
panel = new JPanel();
//do stuff with the panel
}
}应该是这样的:
public static void main(String[] args){
JFrame frame=new JFrame();
myPanel panel=new myPanel("hello");
frame.add(panel);
System.out.println(panel.getHello());
}
public class myPanel extends JPanel{
String hello;
//stuff you need in the panel
public myPanel(String hello) {
this.hello=hello;
}
public String getHello(){
return hello;
}
}这样做的一个原因是为了轻松地@覆盖paint(),并处理它内部的JPanel所需的东西。
如果您想让事情变得简单,并且不需要覆盖任何不需要扩展的东西,但我不会考虑仅仅为了保留JPanel而创建一个类。
https://stackoverflow.com/questions/47225895
复制相似问题