繁体   English   中英

使用Java中的AWT和组件进行绘图

[英]Drawing with AWT and components in Java

我目前正在使用AWT在Java中进行游戏。 主类扩展了Frame,我一直在使用它通过.getGraphics()和.drawRect()绘制图形。 这样做一直很好,只不过当我在框架中添加标签之类的组件时,它停止渲染图形并仅显示组件。

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

代替

  • 在JPanel或JComponent上绘画(我更喜欢前者)
  • 重写paintComponent(Graphics g)方法。 使用此方法进行所有绘画,并使用隐式传递的Graphics上下文。 您无需实际调用 paintComponent因为它将为您隐式调用。

看到

编辑

  • 刚注意到您正在使用AWT。 您确实应该考虑升级到Swing。 否则,代替paintComponent ,你将要覆盖paint ,如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();
            }
        });
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM