Reputation: 5
so I made a grid of 25 circles using Canvas paint, and I want them to be clickable. The clicks should be able to carry out a function. How can I do so?
My code:
import javax.swing.JFrame; //JFrame Class
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
public class Driver extends Canvas
{
public void paint( Graphics g) {
g.setColor(Color.RED);
int rows = 5;
for (int y=0;y< rows;y++)
{
for (int x=0;x<rows;x++)
{
g.drawOval((x + 1) * 150, (y + 1) *150, 100, 100);
}
}
}
public static void main(String[] args)
{
JFrame f = new JFrame("Flow"); //new JFrame
Driver t = new Driver();
f.setSize(900,900);//sets size of frame
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//sets default close operation
f.setVisible(true);//makes panel visible
f.add(t);
}
}
Upvotes: 0
Views: 1202
Reputation: 324098
First of all don't do the drawing on a Canvas. That is an AWT component and you are creating a Swing application. Use a JPanel
for the custom painting. You would then override the paintComponent(...)
method. Read the section from the Swing tutorial on Custom Paintingfor more information.
Now instead of using the drawOval(...) method to paint the Circles, you should change the painting code to draw objects from an ArrayList.
So in the constructor of your painting class you need to create the ArrayList to contain the objects you want to paint:
circles = new ArrayList<Shape>()
int rows = 5;
for (int y=0;y< rows;y++)
{
for (int x=0;x<rows;x++)
{
circles.add( new Ellipse2D.Double((x + 1) * 150, (y + 1) *150, 100, 100) );
}
}
This will create the ArrayList of shapes that you want to paint. In this case 25 circles.
Now the paintComponent()
code needs to be changed to paint each shape. So the code would be something like:
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
// Custom code to paint all the Circles from the List
Graphics2D g2d = (Graphics2D)g;
Color foreground = g2d.getColor();
g2d.setColor( Color.RED );
for (Shape shape : circles)
{
g2d.draw( shape );
}
}
I want them to be clickable.
The reason we made the above changes is so that you can now add a MouseListener to your panel and then in the mouseClicked event you can now search through the ArrayList containing the circles to see which circle clicked. The Shape
interface implements a contains(...)
method so you just need to check each circle to see if it contains the Point where the mouse was clicked.
So the basic logic in the `mouseClicked(...) method would be:
Point p = event.getPoint();
for (Shape shape: circles)
{
if (shape.contains(p))
// do something
}
Upvotes: 2