[英]Extending JPanel or returning JPanel
我目前正在尝试重新创建 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
}
}
在我相信的大多数情况下,您应该明确使用扩展。
这也是错误的:
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;
}
}
你应该这样做的一个原因是很容易@override thepaint(),并处理它里面的JPanel所需的东西。
如果您想让事情保持简单并且不需要覆盖任何您可能不需要扩展的东西,但我不会考虑创建一个类只是为了让 JPanel 成为一个选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.