I’m working on a project about graph-coloring (with GUI). I have a map divided into little polygons. When I clicked on one of these polygons, I want it to be filled with a specific color. How can I do that?
I got my event listeners all set. I can recognize the area that I clicked on. So, I have no problem with which polygon I’m going to color. I tried the fillPolygon(Polygon p) method to do that, it didn’t work. Actually, it filled the polygon that I want; but, when I clicked on another polygon, it colored the new one and erased the older one. I think I know what is causing this: I placed the fillPolygon(Polygon p) in the paintComponent(Graphics g) method which draws the complete map on my panel everytime I started the program.
I have this method in my Map class, to draw the map on the panel.
public void draw ( Graphics screen ) {
screen.setColor ( Color.BLACK );
for ( Polygon thePoly : theShapes )
screen.drawPolygon ( thePoly.getPolygon() );
}
Also, I have following lines in my MapPanel class.
import java.awt.*;
import javax.swing.JPanel;
import javax.swing.*;
import java.awt.event.*;
public class MapPanel extends JPanel {
private Map theMap; // collection of Regions to be colored
/* Some other variables here */
public MapPanel() {
theMap = new Map( );
this.addMouseListener( new ClickListener() );
}
public JMenuBar getMenu() {
/* Bunch of lines for the main panel, menus etc... */
}
public void paintComponent( Graphics g ) {
super.paintComponent(g);
theMap.draw ( g );
if( j != null )
g.fillPolygon( j.getPolygon() );
}
private class ClickListener implements MouseListener
{
public void mousePressed (MouseEvent event)
{
Point p = event.getPoint();
for(int i = 0; i < theMap.theShapes.size(); i++){
if( theMap.theShapes.get(i).getPolygon().contains( p ) ) {
j = theMap.theShapes.get(i);
}
}
repaint();
}
public void mouseClicked (MouseEvent event) {}
public void mouseReleased (MouseEvent event) {}
public void mouseEntered (MouseEvent event) {}
public void mouseExited (MouseEvent event) {}
}
/* Other listener classes */
}
How can I use the fillPolygon(Polygon p) method individually?
Thanks in advance.
As Tim says, you need an ancillary data structure to keep track of the color and selection state of each polygon. See my example code here