我目前正在使用 AWT 用 Java 制作游戏。主类扩展了 Frame,我一直使用它来使用 .getGraphics() 和 .drawRect() 来绘制图形。这一直工作得很好,除了当我向框架添加标签等组件时,它会停止渲染图形并仅显示组件。
最佳答案
不要
- 使用
getGraphics()
进行绘制。这不是正确的方法。 - 尝试在 JFrame 等顶级容器上绘画
相反
- 在 JPanel 或 JComponent 上绘画(我更喜欢前者)
- 重写 JPanel 的
paintComponent(Graphics g)
方法。在此方法中完成所有绘画,使用隐式传递的 Graphics 上下文。您永远不必实际调用paintComponent
,因为它将隐式为您调用。
参见
- Performing Custom Painting有关在 Swing 中绘画的更多详细信息
编辑
- 刚刚注意到您正在使用 AWT。您确实应该考虑升级到 Swing。否则,您将需要重写
paint
,而不是paintComponent
,因为 AWT 组件没有paintComponent
方法。但我强烈建议你使用 Swing
示例(使用 Swing)
public class SimplePaint {
public SimplePaint() {
JFrame frame = new JFrame();
frame.add(new DrawPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class DrawPanel extends JPanel {
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(50, 50, 150, 150);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new SimplePaint();
}
});
}
}
关于java - 使用 AWT 和 Java 组件进行绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26563202/