I am just simply trying to draw an object to my JPanel
but it will not appear. The method that is being used to create the Rectangle that is representing the object is being called, but the object will not appear on screen.
This is my main class that sets up the JFrame
and the JPanel
and has the paintComponent
method that is being used to draw everything.
This is my main class
public class BrickBreaker extends JPanel
{
private static int WIDTH = 600;
private static int HEIGHT = 400;
private Paddle paddle = new Paddle(WIDTH/2 - 25, HEIGHT - 25);
public BrickBreaker()
{
JFrame frame = new JFrame();
Dimension size = new Dimension(WIDTH, HEIGHT);
frame.setSize(size);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
setBackground(Color.BLACK);
frame.add(this, BorderLayout.CENTER);
frame.addKeyListener(paddle);
}
public static void main(String[] args)
{
BrickBreaker game = new BrickBreaker();
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
paddle.draw(g);
}
I also have my Paddle
class that is used to create a paddle object, and it has a draw
method that I am using to try and just draw a basic Rectangle
public class Paddle
{
private int x, y;
private Rectangle paddle;
public Paddle(int x, int y)
{
this.x = x;
this.y = y;
paddle = new Rectangle(x, y, 50, 10);
}
public void draw(Graphics g)
{
g.setColor(Color.WHITE);
g.drawRect(paddle.x, paddle.y, 75, 10);
g.fillRect(paddle.x, paddle.y, 75, 10);
}
}
I have done basic tests like changing the paddle.x, paddle.y
to hard-coded coordinates, but the Rectangle will not show up
I have also added a BufferedImage
to the paintComponent
method in my main class, and that gets drawn to the screen. I have also added checks to make sure the draw
method is being called, and it is.
I am assuming I setup the JPanel
incorrectly, but I am not too sure what I did wrong.