gpt4 book ai didi

java - 绘图时使用 JPanel 坐标

转载 作者:行者123 更新时间:2023-12-01 21:09:20 24 4
gpt4 key购买 nike

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

我在我的类 GameView 中重写了 PaintComponent() 方法,它显示了游戏(所以它是我提到的第二个 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();

}

游戏场景中模型的绘制方法通常如下所示:

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对于您的框架,因此它将默认为 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'了解有关此主题的更多信息。

关于java - 绘图时使用 JPanel 坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41472857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com