【问题标题】:Adding multiple graphics to a single JPanel将多个图形添加到单个 JPanel
【发布时间】:2015-03-02 12:04:35
【问题描述】:

我正在尝试添加 3 个图形,其中两个必须移动(可能相互穿过,在一个轴上移动),只有最后一个添加到面板显示。

换句话说,我在 JFrame 中添加了许多面板,并且在最大的面板中,我使用特定坐标放置了图形对象。显示代码可能更有帮助。

//the gameArea is the referred-to JPanel, above this code    
TankOne tank1 = new TankOne(Color.GREEN);
TankTwo tank2 = new TankTwo(Color.MAGENTA);
FieldBar fieldb = new FieldBar(Color.getHSBColor((float) Math.random(),(float) Math.random(),(float) Math.random()));
JPanel tank1panel = new JPanel();
JPanel tank2panel = new JPanel();
tank1panel.add(tank1);
tank2panel.add(tank2);
gameArea.add(tank1panel);
gameArea.add(tank2panel);
gameArea.add(fieldb);
//repaint code here

如您所见,这是一款坦克游戏。 GUI 上显示的是最后一个 gameArea.add。 [这里是 fieldb,一个显示比赛场地的酒吧]。

这里的尝试是我尝试将两个新面板放入 gameArea Jpanel 中,然后将两个坦克对象放入其中。还是没有骰子。

是否有解决方法可以让我将坦克移动像素? 我已经看到一些答案包括切换到 gridlayout,但我认为这无助于看到额外的面板什么也没做。

感谢您的回答。

【问题讨论】:

    标签: java swing graphics awt


    【解决方案1】:

    我猜每个坦克 JPanel 都显示一个坦克的图像(?不是 100% 肯定)。一些建议,但请告诉我我的假设是否离题:

    • 保持逻辑和视图按照 M-V-C 分开。
    • 在其paintComponent(...) 方法中在单个JPanel(可能称为DrawingPanel)中处理所有图形。
    • 背景图像将是在 DrawingPanel 的 paintComponent(...) 方法中绘制的 BufferedImage。
    • 坦克本身不会由 JPanel 表示,而是它自己的小型 BufferedImage 精灵,再次在 paintComponent 方法中绘制,但在背景图像之后绘制
    • 每个坦克至少需要 4 个精灵,每个方向一个。
    • 如果您的坦克要沿对角线移动,您可能需要更多精灵。
    • 还有一个单独的炮塔精灵/图像。
    • 您可以移动精灵的绘制位置以响应其模型表示位置的变化。
    • 炮塔旋转也是如此。

    【讨论】:

    • 谢谢,这太棒了。
    猜你喜欢
    • 2012-05-02
    • 2011-09-13
    • 2013-12-12
    • 2012-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多