我正在開發一個關於圖形着色(使用GUI)的項目。我有一張分成小多邊形的地圖。當我點擊其中一個多邊形時,我希望它填充特定的顏色。我怎樣才能做到這一點?在Java中填充單擊的區域
我得到了我的事件監聽器全部設置。我可以識別我點擊的區域。所以,我對將要着色的多邊形沒有問題。我嘗試了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)方法?
在此先感謝。
我剛剛在我的第一條消息中添加了一些行。 – 629 2010-12-10 02:30:49
因此,正如您在上面看到的那樣,Map類中的顏色最初設置爲黑色,MapPanel類中的paintComponent()方法使用該顏色。當我在該方法中添加g.fillPolygon行時,我無法控制顏色。那麼,有沒有其他方法可以更有效地使用paintComponent()方法? – 629 2010-12-10 02:35:20