绘图时使用 JPanel 坐标

Using JPanel coordinates while drawing

我正在 Java 中制作简单的游戏,并且我正在使用 Swing。我有 JFrame 并且在其中我想要两个 JPanels - 一个用于得分等,第二个用于实际游戏。我读到每个 JPanel 都有自己的坐标,所以点 (0, 0) 位于该面板的左上角。

我重写方法 paintComponent() 在我的 class GameView 中显示游戏(所以这是我提到的第二个 JPanel)。但是当我想在 gameView 的左上角绘制一些东西并将该图像的坐标设置为 (0,0) 时,它会在 BarView 上绘制。

我阅读了很多关于绘画的教程和帖子,但我不明白我做错了什么。所以我的问题是,如何使用 JPanel 坐标而不是 JFrame 坐标绘制内容?这是一些代码:

将扩展 JPanel 的对象添加到 JFrame:

GameView v = new GameView();
    BarView bv = new BarView();
    frame.getContentPane().add(bv);
    frame.getContentPane().add(v);
    frame.setVisible(true);
    v.requestFocus();
    v.repaint();
    bv.repaint();

在 JPanel 中绘图:

public class GameView extends JPanel implements View, Commons{

    public static final int WIDTH=WINDOW_WIDTH, HEIGHT=ARENA_HEIGHT;
    private GameScene gameScene;
    private TexturePaint paint;
    private BufferedImage bi;

    public GameView(){
    addKeyListener(new CustomKeyListener());
    addMouseMotionListener(new CustomMouseListener());
    setSize(WINDOW_WIDTH, ARENA_HEIGHT);
    setFocusable(true);
    try {
        bi = ImageIO.read(new File("src/res/texture.png"));
    } catch (IOException e) {
            // TODO Auto-generated catch block
        e.printStackTrace();
    }
     this.paint = new TexturePaint(bi, new Rectangle(0, 0, bi.getWidth(), bi.getHeight()));
    }

    @Override
    public void paintComponent(Graphics g1) {

    Graphics2D g = (Graphics2D) g1;
    g.setPaint(paint);
    g.fillRect(0, 0, WINDOW_WIDTH, ARENA_HEIGHT);
    for(Iterator<Drawable> it = gameScene.models.iterator(); it.hasNext();)
    {
        Drawable d = it.next();
        d.draw(g1);
    }
    Toolkit.getDefaultToolkit().sync();

    }

gameScene中model的绘制方法通常是这样的:

public void draw(Graphics g1){
    Graphics2D g = (Graphics2D) g1.create();
    int cx = image.getWidth(null) / 2;
    int cy = image.getHeight(null) / 2;
    g.rotate(rotation, cx+x, cy+y);
    g.drawImage(image, x, y, null);
}

您似乎没有指定 LayoutManager for your frame, so it will default to BorderLayout

当您随后调用 frame.getContentPane().add(component) 而不传递位置常量时,位置 BorderLayout.CENTER 将被默认。

结果是您的 GameViewBarView 组件将在彼此之上呈现。

作为快速测试,尝试按如下方式指定组件位置:

GameView v = new GameView();
BarView bv = new BarView();
frame.getContentPane().add(bv, BorderLayout.LINE_START);
frame.getContentPane().add(v, BorderLayout.LINE_END);

除非您的 UI 非常简单,否则您可能会发现需要使用其他一些布局管理器。有关此主题的更多信息,请参阅 'How to Use Various Layout Managers'