简体   繁体   English

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

[英]Drawing with AWT and components in Java

I'm currently making a game in Java with AWT. 我目前正在使用AWT在Java中进行游戏。 The main class extends Frame, and I've been using it to draw the graphics using .getGraphics() and .drawRect(). 主类扩展了Frame,我一直在使用它通过.getGraphics()和.drawRect()绘制图形。 This has been working fine, except that when I add components like labels to the frame it stops rendering the graphics and only displays the components. 这样做一直很好,只不过当我在框架中添加标签之类的组件时,它停止渲染图形并仅显示组件。

Don't

  • Use getGraphics() to paint. 使用getGraphics()进行绘制。 That is not the proper way. 那不是正确的方法。
  • Try and paint on top-level containers like JFrame 尝试在顶级容器(如JFrame)上绘画

Instead 代替

  • Paint on a JPanel or JComponent (I prefer the former) 在JPanel或JComponent上绘画(我更喜欢前者)
  • Override the paintComponent(Graphics g) method of the JPanel. 重写paintComponent(Graphics g)方法。 Do all your painting in this method, use the implicitly passed Graphics context. 使用此方法进行所有绘画,并使用隐式传递的Graphics上下文。 You never have to actually call paintComponent as it will be implicitly called for you. 您无需实际调用 paintComponent因为它将为您隐式调用。

See 看到

Edit 编辑

  • Just noticed you are using AWT. 刚注意到您正在使用AWT。 You really should consider upgrading to Swing. 您确实应该考虑升级到Swing。 Otherwise, instead of paintComponent , you're going to want to override paint , as AWT components don't have a paintComponent method. 否则,代替paintComponent ,你将要覆盖paint ,如AWT组件不具有paintComponent方法。 But I strongly urge you to use Swing 但我强烈建议您使用Swing

Example (Using 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