You need to look at Performing Custom Painting. You kinda have the concept, but your changeColor
method isn't going to do anything for you.
Some things to note.
First you need to add a
MouseListener
. See more at How to Write MouseListenersSecond what you want to do is just have a
Color color
variable. You use that variable to set the color. Your methodchangeColor
should only change the color andrepaint()
. Something likepublic class MyComponentNew extends JPanel { private Color color = Color.BLUE; protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(color); } public void changeColor() { if (color == Color.BLUE) { color = Color.RED: } else { color = color.BLUE; } repaint(); } }
Third notice how I use
JPanel
instead ofJFrame
. This is the preferred approach.Fourth you should be using Swing and not AWT.
Here's a full example, with those points above
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CircleChangeColor extends JPanel {
private Ellipse2D circle = new Ellipse2D.Double(0, 0, 200, 200);
private Color color = Color.blue;
public CircleChangeColor() {
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e) {
if (circle.contains(e.getPoint())) {
changeColor();
}
}
});
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setColor(color);
g2.fill(circle);
}
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public void changeColor() {
if (color == Color.BLUE) {
color = Color.RED;
} else {
color = color.BLUE;
}
repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
JFrame frame = new JFrame();
frame.add(new CircleChangeColor());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}