我正在做一个关于图形着色(使用 GUI)的项目。我有一张分成小多边形的地图。当我单击其中一个多边形时,我希望它填充特定的颜色。我怎样才能做到这一点?
我已经设置好了我的事件监听器。我可以识别我点击的区域。所以,我对要着色的多边形没有任何问题。我尝试了 fillPolygon(Polygon p) 方法来做到这一点,它没有用。实际上,它填充了我想要的多边形;但是,当我单击另一个多边形时,它会为新的多边形着色并擦除旧的多边形。我想我知道是什么原因造成的:我将 fillPolygon(Polygon p) 放置在 paintComponent(Graphics g) 方法中,该方法每次启动程序时都会在我的面板上绘制完整的地图。
我的 Map 类中有这个方法,可以在面板上绘制地图。
public void draw ( Graphics screen ) {
screen.setColor ( Color.BLACK );
for ( Polygon thePoly : theShapes )
screen.drawPolygon ( thePoly.getPolygon() );
}
另外,我的 MapPanel 类中有以下几行。
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 */
}
如何单独使用 fillPolygon(Polygon p) 方法?
提前致谢。