views:

161

answers:

2

I have a JPanel with a Grid Layout. In the "cells" of the grid I can put different elements (for example JButtons). There is no problems with that. But now I want to put a filled circle in some of the cells. I also would like to relate an ActionListener with these circles. In more details, if I click the circle it disappears from the current cell and appears in another one. How can I do it in Java? I am using Swing.

+2  A: 
public void paintComponent(Graphics g) {
   super.paintComponent(g);
   Graphics2D g2d = (Graphics2D)g;
   // Assume x, y, and diameter are instance variables.
   Ellipse2D.Double circle = new Ellipse2D.double(x, y, diameter, diameter);
   g2d.fill(circle);
   ...
}

Here is some docs about paintComponent (link).

You should override that method in your JPanel and do something similar to the code snippet above.

In your ActionListener you should specify x, y, diameter and call repaint().

Roman
Heh, thought it was a self-answer for a second there.
Michael Myers
@mmyers: yes, it's a bit confusing))
Roman
+1  A: 

In the article "Painting in AWT and Swing" you can find this snippet of code which draws a circle:

public void paint(Graphics g) {
    // Dynamically calculate size information
    Dimension size = getSize();
    // diameter
    int d = Math.min(size.width, size.height); 
    int x = (size.width - d)/2;
    int y = (size.height - d)/2;

    // draw circle (color already set to foreground)
    g.fillOval(x, y, d, d);
    g.setColor(Color.black);
    g.drawOval(x, y, d, d);
}

Add an action listener to the component which will remove this and draw a new circle somewhere else.

Boris Pavlović
this is an obsolete awt technique
Roman
yes indeed. it is obsolete
Boris Pavlović