グラフの色付け (GUI を使用) に関するプロジェクトに取り組んでいます。小さなポリゴンに分割されたマップがあります。これらのポリゴンの 1 つをクリックすると、特定の色で塗りつぶされます。どうやってやるの?
イベントリスナーをすべて設定しました。クリックした領域を認識できます。したがって、どのポリゴンに色を付けるかは問題ありません。それを行うために fillPolygon(Polygon p) メソッドを試しましたが、うまくいきませんでした。実際、私が望む多角形を塗りつぶしました。しかし、別のポリゴンをクリックすると、新しいポリゴンが色付けされ、古いポリゴンが消去されました。これの原因はわかっていると思います。プログラムを起動するたびに、パネルに完全なマップを描画する paintComponent(Graphics g) メソッドに fillPolygon(Polygon p) を配置しました。
パネルにマップを描画するために、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) メソッドを個別に使用するにはどうすればよいですか?
前もって感謝します。