After finishing and running a simple program that lets you change the color of a shape when it's clicked on:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyPanel extends JPanel{
int x = 200,y = 200,r = 50;
static Color co = Color.BLUE;
static final JFrame frame = new JFrame();
public static void main(String[] args){
frame.setTitle("Color Change with Mouse Click");
frame.setSize(500,500);
MyPanel pane = new MyPanel();
frame.add(pane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pane.setVisible(true);
}
public void Panel(){
addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(((e.getX() >= (x-r) && e.getX() < (x+r) && e.getY() >= (y-r) && e.getY() < (y+r))) & (co == Color.GREEN)){
co = Color.BLUE;
repaint();
};
if(((e.getX() >= (x-r) && e.getX() < (x+r) && e.getY() >= (y-r) && e.getY() < (y+r))) & (co == Color.BLUE)){
co = Color.GREEN;
repaint();
};
}
});
}
Timer timer = new Timer(1, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
Panel();
}
});
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
timer.start();
Panel();
g.setColor(co);
g.fillOval(x-r, y-r, 2*r, 2*r);
repaint();
}
}
I encountered a problem that I simply don't know how to fix. The JPanel never updates on the second mouse click, only on the first. I thought that adding the timer would take care of this, but apparently it didn't. Help is much appreciated.
edit: I changed my code per Aqua's suggestions:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyPanel extends JPanel{
int x = 200,y = 200,r = 50;
static Color co = Color.BLUE;
public static void main(String[] args){
final JFrame frame = new JFrame();
frame.setTitle("Color Change with Mouse Click");
MyPanel pane = new MyPanel();
frame.add(pane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
public void panel(){
addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(((e.getX() >= (x-r) && e.getX() < (x+r) && e.getY() >= (y-r) && e.getY() < (y+r))) && (co == Color.GREEN)){
co = Color.BLUE;
repaint();
}else if(((e.getX() >= (x-r) && e.getX() < (x+r) && e.getY() >= (y-r) && e.getY() < (y+r))) && (co == Color.BLUE)){
co = Color.GREEN;
repaint();
}else{
repaint();
};
}
});
}
public MyPanel(){
Timer timer = new Timer(20, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
panel();
}
});
timer.start();
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(co);
g.fillOval(x-r, y-r, 2*r, 2*r);
repaint();
}
}
And the color change works now, however the color change is a bit unpredictable. sometimes it has a delay, sometimes it doesn't, and sometimes it just outright won't change back. Is this a problem with my timer?