我正在使用Java进行一些面向对象编程。
我只想写一个带有一些图形对象的游戏,但我想用一些类来结构化它。
整体布局应如下:
MainClass -> new MainPanel(扩展JPanel)- > new StartWindow(扩展抽象GameWindow,其中包含gameloop)
这样,我应该能够创建StartWindow、Level1Window、Level2Window等窗口。我的StartWindow现在应该绘制第一级别的布局。StartWindow将创建其他对象(例如玩家、敌人等),它们以后将负责绘制自己。
所以,我想创建“每个对象都负责绘制自己”的东西。
我希望我已经清楚地解释了这个过程。问题是,我无法弄清楚如何委派这个任务。
目前我的代码看起来像这样:
public class MainClass extends JFrame implements ActionListener {
//..... other stuff
public MainClass () {
MainPanel mainPanel = new MainPanel();
}
//.... other stuff
}
class MainPanel extends JPanel {
private GameWindow currentWindow;
public MainPanel () {
currentWindow = new StartWindow(this);
}
public void paintComponent(Graphics g) {
g.drawRect (10, 10, 200, 200); // <-- can see on the window
}
}
abstract class GameWindow {
// contains game loop and update functions and so on
}
public class StartWindow extends GameWindow {
GamePanel _parentWindow;
public StartWindow(GamePanel parentWindow) {
super();
_parentWindow = parentWindow;
}
public void paintComponent(Graphics g) {
//Does not work
g.drawRect (20, 20, 100, 100);
}
}
"_parentWindow" 包含 MainPanel,因此我应该拥有在其面板上绘制所需的所有信息,但我无法弄清如何实现。
编辑: 最小示例可以正常工作:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainClass extends JFrame implements ActionListener {
public static void main(String[] args)
{
System.out.println("Program Window1");
MainClass glt = new MainClass();
glt.setVisible(true);
}
//..... other stuff
public MainClass () {
super("Fixed Timestep Game Loop Test");
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
JPanel p = new JPanel();
p.setLayout(new GridLayout(1,2));
System.out.println("Program Window2");
MainPanel gamePanel= new MainPanel();
cp.add(gamePanel, BorderLayout.CENTER);
cp.add(p, BorderLayout.SOUTH);
setSize(500, 500);
}
//.... other stuff
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
class MainPanel extends JPanel {
private GameWindow currentWindow;
public MainPanel () {
currentWindow = new StartWindow(this);
}
public void paintComponent(Graphics g) {
g.drawRect (0, 0, 200, 200); // <-- can see on the window
}
}
abstract class GameWindow {
// contains game loop and update functions and so on
}
class StartWindow extends GameWindow {
MainPanel _parentWindow;
public StartWindow(MainPanel parentWindow) {
super();
_parentWindow = parentWindow;
}
public void paintComponent(Graphics g) {
//Does not work
g.drawRect (20, 20, 100, 100);
}
}