Search code examples
javaswinggraphicsgraphics2dpaintcomponent

DrawRect in a JPanel not Showing


I am trying to create a simple game wherein a box(alien) is going on each row(left to right / right to left) then going downward and in a mouse click there will be a ball(fire) and when the box and ball meets, the player wins else the alien invades the planet.

I got the idea of the game from [http://www.stanford.edu/class/cs106a/cgi-bin/classhandouts/23-ufo-game.pdf][1] stanford lecture [1]:

so i tried making like that using my code.

    package spaceInvader;

import javax.swing.JFrame;

public class Main {
public static void main(String args[]) throws InterruptedException{
    JFrame jf = new JFrame("YY");
    Space_GUI sg = new Space_GUI();
    jf.add(sg);
    jf.setSize(500,500);
    jf.setVisible(true);
    jf.setContentPane(sg);
    Thread.sleep(2000);
    sg.rc.move();

}
}




package spaceInvader;

import javax.swing.JButton;
import javax.swing.JPanel;

public class Space_GUI extends JPanel{
    public RectangleComponent rc;

 public Space_GUI(){
    rc = new RectangleComponent();
    add(rc);    
}

}




package spaceInvader;

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

import javax.swing.JComponent;

public class RectangleComponent extends JComponent{

    private int _xCoord;
    private int _yCoord;
    private  static final int SIZE = 50;
    public RectangleComponent(){
        _xCoord = 10;
        _yCoord = 10;
        repaint();
    }

    public void move(){
        _xCoord = 20;
        _yCoord = 20;
        repaint();
    }
    public void paintComponent(Graphics g){
        _xCoord = getWidth()/2;
        _yCoord = getHeight()/2;
        super.paintComponent(g);
        g.setColor(Color.black);
        g.drawRect(_xCoord, _yCoord, SIZE, SIZE);
        g.fillRect(_xCoord, _yCoord, SIZE, SIZE);
    }
}

in my code i am trying to just show the box but then there is none showing. I tried adding up JButton and only that button shows , it doesnt show the box.


Solution

  • OK for some reason I'm seeing the RectangleComponent code now, and I see problems:

    • RectangleComponent extends JComponent, and a JComponent's preferredSize is [0, 0], so if you don't do anything about this, nothing will of course show.
    • One solution is to give RectangleComponent a getPreferredSize method that tells the layout managers what size it should be.
    • Another possible solution is to use a different layout manager for the Space_GUI JPanel that holds the RectangleComponent object. For instance if you had it use BorderLayout and added RectangleComponent BorderLayout.CENTER, then the RectangleComponent would fill the Space_GUI JPanel.
    • Another problem is that you're careful to set the _xCoord and _yCoord variables and to then change them in move(), but it is all for naught since you set them to something completely different in RectangleComponent's paintComponent method.