2

I have been trying to learn how to draw to a Jpanel for a game. I want to draw to it from different classes (like a class that manages maps and a class that manages player models).

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main
{
public static void main (String[] args)
{
    JFrame frame = new JFrame ("Java Game");
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    frame.setSize (1000, 600);
    JPanel panel = new JPanel();
    panel.setBackground (Color.WHITE);
    Dimension size = new Dimension(1000,500);
    panel.add (new Player()); // Class with paintComponent method.
    panel.setPreferredSize(size);
    panel.setBackground(Color.BLUE);
    frame.getContentPane().add(panel);
    frame.setVisible(true);
}
}

next class

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;

@SuppressWarnings ("serial")
public class Player extends JComponent
{
int x = 50;
int y = 450;
public void paintComponent (Graphics g)
{
    super.paintComponent(g);
    g.setColor (Color.BLACK);
    g.fillRect (x, y, 50, 50);
}
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Joshua Unrau
  • 313
  • 1
  • 2
  • 13

1 Answers1

2

You probably want to extend JPanel. It's already opaque, and it can handle the background color for you. Also give your panel a size like they do here, then you can do the drawing relative to the size.

image

Player p = new Player();
p.setBackground(Color.cyan);
frame.add(p);
frame.pack();
frame.setVisible(true);
…
public class Player extends JPanel {

    private static final int X = 320;
    private static final int Y = 240;

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.BLACK);
        g.fillRect(getWidth() / 2 - 25, getHeight() / 2 - 25, 50, 50);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(X, Y);
    }
}
Community
  • 1
  • 1
Catalina Island
  • 7,027
  • 2
  • 23
  • 42