I'm making a 'game' of sorts where the player has to click on an image bouncing around the screen. The catch is that the screen is in darkness and the mouse cursor is a 'flashlight' which 'light up' a small circle around it.
I have a JFrame
in one class consisting of:
public class GameFrame {
public static void main(String[] args) throws IOException {
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
JFrame jf = new JFrame("Flashlight Game");
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(d);
jf.setLocationRelativeTo(null);
GamePanel gp = new GamePanel();
jf.add(gp);
}
}
I have another class which extends
JPanel
. Here are its fields relevant to my problems:
private Point mouse; //location set by a MouseMotionListener
private BufferedImage myImage;
private int imageX;
private int imageY;
private int imageSpeedX;
private int imageSpeedY;
My first problem lies in the flashlight. In my paint
method, I set the graphics background color to the panel background color and use the clearRect
method to clear an area around the mouse cursor.
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paint(g2);
checkBounce();
move();
g2.drawImage(myImage, imageX, imageY, null);
g2.setColor(Color.BLACK);
g2.fillRect(0, 0, this.getWidth(), this.getHeight());
g2.setBackground(Color.WHITE);
g2.clearRect((int) mouse.getX() - 25, (int) mouse.getY() - 25, 50, 50);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
repaint();
}
There are actually two problems here.
1.) How can I create a clearOval
effect since a flashlight doesn't shine in a rectangle, and
2.) How can I get the bouncing image to show up through the flashlight beam? I know that calling g2.setBackground(Color.WHITE)
will use the set color as the 'background' for the cleared area, but I need a way to clear all graphics except for the backmost JFrame
or JPanel
background color.
My last problem is sorta weird, but occasionally when I change the value of an int
, the window will appear as blank and needs resizing before any of the code will execute.
JPanel
overridepaintComponent()
rather thanpaint()
. – Baste