Hi guys, im new to GUI in Java and to this website. Ive self taught myself Java so far, I would consider myself knowing the basics of Java and I am ready to learn more advanced things in java.
Im currently making this Java GUI game which has a simple concept; the user clicks on the the screen when the small circle is in the center of the big circle and gains a point. I made a black circle by 100x100 and a white circle 50x50. This my code so far:
GUI
import java.awt.Color; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import java.util.Random; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.Timer; import javax.swing.JPanel; public class gui extends JPanel implements ActionListener, MouseListener { static final int permanentposx = 75; static final int permanentposy = 75; int posy = 75; int posx = 75; int score; Timer t = new Timer(500, this); public gui() { t.start(); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.black); g.fillOval(50, 50, 100, 100); g.setColor(Color.WHITE); g.fillOval(posx, posy, 50, 50); } public void actionPerformed(ActionEvent e) { posy = permanentposy; posx = permanentposx; boolean checkifmoved = false; int x; Random rnd = new Random(); x = rnd.nextInt(999); if (x % 3 == 0) { posy = posy - 25; posx = permanentposx; checkifmoved = true; } else if (x % 27 == 0) { posy = posy + 25; posx = permanentposx; checkifmoved = true; } else if (x % 13 == 0) { posx = posx + 25; posy = permanentposy; checkifmoved = true; } else { posx = posx - 25; posy = permanentposy; checkifmoved = true; } this.repaint(); if (checkifmoved == true) { int y; y = rnd.nextInt(10); if(y % 3 == 0){ posy = permanentposy; posx = permanentposx; checkifmoved = false; } this.repaint(); } } @Override public void mouseClicked(MouseEvent ee) { }
MAIN
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; public class main { public static void main(String[] args) { JFrame frame = new JFrame("Circle enlarger"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400,400); frame.setVisible(true); gui guiobject = new gui(); frame.add(guiobject); } }
As you can see, on my actionlistener method in my GUI class, I tried making the circle move up,down,left or right randomly by creating a random number and dividing that by a certain number. The problem im currently having is that I dont really know how code the part where the computer knows when the user has clicked and when the small circle is in the center of the black circle...
Ive tried implementing mouselistener but dont know which statement to use. I was thinking of MOUSE_CLICKED but that didnt work out right...