I have a combobox in my program, with three options CIRCLE, RECTANGLE, FREEHAND. Each option is connected to a mouselistener. If I swich between the three options the mouselisteners are causing me some problems. Therefore I would like to add a mouselistener only once (for example in the constructor or in the beginning of the method, or somewhere else). Is it even possible, and how would the code look like? If it is not possible, is there any other way I can solve it?
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(comboBox)) {
JComboBox cb = (JComboBox)e.getSource();
if (cb.getSelectedItem().equals("Rectangle")) {
contentPane.addMouseListener(new MouseAdapter() { //First mouseListener
@Override
public void mousePressed(MouseEvent e) {
startX = e.getX();
startY = e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {
endX = e.getX();
endY = e.getY();
int width = startX - endX;
int height = startY - endY;
w = Math.abs(width);
h = Math.abs(height);
Rectangle r = new Rectangle(startX, startY, w, h, pickedColor, thickness);
shapeList.add(r);
repaint();
}
});
}
else if (cb.getSelectedItem().equals("Circle")) {
contentPane.addMouseListener(new MouseAdapter() { //Second
@Override
public void mousePressed(MouseEvent e) {
startX = e.getX();
startY = e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {
endX = e.getX();
endY = e.getY();
int width = startX - endX;
int height = startY - endY;
w = Math.abs(width);
h = Math.abs(height);
Circle c = new Circle(startX, startY, w, h, pickedColor, thickness);
shapeList.add(c);
repaint();
}
});
}
else if (cb.getSelectedItem().equals("Freehand")) {
contentPane.addMouseListener(new MouseAdapter() { //Third
@Override
public void mousePressed(MouseEvent e) {
startX = e.getX();
startY = e.getY();
}
@Override
public void mouseDragged(MouseEvent e) {
FreeHand fh = new FreeHand(startX, startY, e.getX(), e.getY(), pickedColor, thickness);
shapeList.add(fh);
repaint();
}
});
}
}