user8521521
user8521521

Reputation:

Graphics not drawing to JFrame

I feel like I went through everything I needed to do:

I can't find anything wrong with this, so I'm a little confused.
My code is here:

public static void main(String[] args) {
    DragonEscape game = new DragonEscape();
    frame.setTitle(title);
    frame.setSize(1000, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.add(new Graphicsa());
    frame.add(game);
}

and

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JComponent;

public class Graphicsa extends JComponent {
    private static final long serialVersionUID = 1L;

    public Graphics g;

    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g.fillRect(0, 0, 1000, 500);
        g.setColor(Color.gray);
        g.fillRect(0, 0, 100, 100);
    }

}

Upvotes: 0

Views: 605

Answers (1)

camickr
camickr

Reputation: 324108

frame.add(new Graphicsa());
frame.add(game);

Only one component can be added to the CENTER of the BorderLayout of the JFrame. So your game component replaces the graphics component.

Read the Swing tutorial for Swing basics. There are sections on:

  1. How to use BorderLayout
  2. Custom Painting

that directly related to this question.

Also, why are you even trying to do graphics painting? If looks to me like you are just trying to paint the background a certain color. Just use the setBackground(...) method on your game component.

Upvotes: 0

Related Questions