Amit Eyal
Amit Eyal

Reputation: 459

Drawing with AWT and components in Java

I'm currently making a game in Java with AWT. The main class extends Frame, and I've been using it to draw the graphics using .getGraphics() and .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.

Upvotes: 0

Views: 624

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208984

Don't

  • Use getGraphics() to paint. That is not the proper way.
  • Try and paint on top-level containers like JFrame

Instead

  • Paint on a JPanel or JComponent (I prefer the former)
  • Override the paintComponent(Graphics g) method of the JPanel. Do all your painting in this method, use the implicitly passed Graphics context. You never have to actually call paintComponent as it will be implicitly called for you.

See

Edit

  • Just noticed you are using AWT. You really should consider upgrading to Swing. Otherwise, instead of paintComponent, you're going to want to override paint, as AWT components don't have a paintComponent method. But I strongly urge you to use Swing

Example (Using 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();
            }
        });
    }
}

Upvotes: 2

Related Questions