【问题标题】:Drawing with AWT and components in Java在 Java 中使用 AWT 和组件进行绘图
【发布时间】:2014-10-25 22:16:45
【问题描述】:

我目前正在使用 AWT 用 Ja​​va 制作游戏。主类扩展了 Frame,我一直使用它来使用 .getGraphics() 和 .drawRect() 绘制图形。这一直工作正常,除了当我向框架添加标签等组件时,它会停止渲染图形并只显示组件。

【问题讨论】:

  • 好的,现在你想让我们做什么?
  • 当你有 Swing 或类似的东西时,没有理由使用 AWT。

标签: java awt


【解决方案1】:

不要

  • 使用getGraphics() 绘画。这不是正确的方法。
  • 尝试在 JFrame 等顶级容器上进行绘制

改为

  • 在 JPanel 或 JComponent 上绘制(我更喜欢前者)
  • 覆盖 JPanel 的 paintComponent(Graphics g) 方法。使用此方法完成所有绘画,使用隐式传递的 Graphics 上下文。您不必真正调用 paintComponent,因为它会为您隐式调用。

编辑

  • 刚刚注意到您正在使用 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();
            }
        });
    }
}

【讨论】:

    猜你喜欢
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    相关资源
    最近更新 更多