Java Graphique, modification de la couleur des dessins à l'aide d'événement click

Ok donc en gros je suis en train d'écrire une application graphique qui attire les 2 cercles et 2 rectangles dans la fenêtre principale. J'essaie de faire en sorte que chaque fois que l'utilisateur clique dans la des cercles ou des rectangles, ce cercle ou rectangle changements à l'autre de couleur aléatoire.

Actuellement j'ai en sorte que le Clic de souris événement (n'importe où sur l'écran) les causes de tous les cercles ou des rectangles de changer de couleur, de la même couleur.
C'est ce que j'ai obtenu jusqu'à présent:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Question2 {
public static void main(String[] args) {
SecondFrame f = new SecondFrame("Draw and Fill");
f.init();
}
}   
class SecondFrame extends JFrame{
SecondFrame(String title) {
super(title);
}   
private JPanel mainPanel;
private GridBagConstraints gbc = new GridBagConstraints();
private GridBagLayout gbLayout = new GridBagLayout();
void init() {
mainPanel = new JPanel();
mainPanel.setLayout(gbLayout);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setContentPane(mainPanel);
gbc.gridheight = 1;
mainPanel.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent e) {
Point mousePosition;
mousePosition = mainPanel.getMousePosition();
repaint();
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent arg0) {
//TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
//TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
//TODO Auto-generated method stub
}
});
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void paint(Graphics g){
super.paint(g);
Random ran = new Random();
//Assumes max and min are non-negative.
int red = 0 + ran.nextInt(255 - 0 + 1);
int green = 0 + ran.nextInt(255 - 0 + 1);
int blue = 0 + ran.nextInt(255 - 0 + 1);
Color myColor = new Color(red,green,blue);
g.setColor(myColor);
g.fillOval(50,50,200,200);
g.fillOval(50, 255, 200, 200);
g.fillRect(255,50,200,200);
g.fillRect(255, 255, 200, 200);
}
}

Si vous pouviez me pointer dans la bonne direction, ce qui serait très apprécié. Merci.

InformationsquelleAutor user3352349 | 2014-03-02