2010-07-30 113 views
1

任何人都可以診斷我面臨的問題嗎? 當你運行你可以看到中間部分留空演示中,我需要填補整個區域..提前java swing:多邊形填充顏色問題

import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Polygon; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 


public class FillDemo 
{ 
    public static void main(String aths[]) 
    { 
     JFrame f = new JFrame(); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     JPanel pnl = new PolygonDemo(); 
     pnl.setSize(100, 200); 
     f.getContentPane().add(pnl); 
     f.setSize(400,280); 
     f.setLocation(200,200); 
     f.setVisible(true); 
    } 
} 

class PolygonDemo extends JPanel 
{ 
    public PolygonDemo() 
    { 
     setBackground(Color.white); 
    } 

    protected void paintComponent(Graphics g) 
    { 
     super.paintComponent(g); 
     Graphics2D g2 = (Graphics2D)g; 
     Polygon p=new Polygon(); 

     p.addPoint(100,0); 
     p.addPoint(100,100); 
     p.addPoint(0,100); 
     p.addPoint(0,0); 

     p.addPoint(80,0); 
     p.addPoint(80,20); 
     p.addPoint(40,20); 
     p.addPoint(40,40); 
     p.addPoint(80,40); 
     p.addPoint(80,100); 
     p.addPoint(20,100); 
     p.addPoint(20,80); 
     p.addPoint(60,80); 
     p.addPoint(60,60); 
     p.addPoint(20,60); 
     p.addPoint(20,0); 
     p.addPoint(0,0); 

     g2.setColor(Color.BLACK); 
     g2.draw(p); 
     g2.setColor(new Color(120,250,100)); 
     g2.fillPolygon(p); 
     //g2.fillPolygon(p.xpoints,p.ypoints,p.npoints); 

    } 

} 

非常感謝

回答

2

你的多邊形本身相交。 fillPolygon方法不能清楚地確定哪個點在哪個點,哪個點在外面。來自fillPolygon javadoc:

多邊形內的區域是使用偶數填充規則(也稱爲交替規則)定義的。

也許你可以將你的多邊形分成三個單一的多邊形。

+0

感謝Nokul立即和答辯權 我可以能夠與下面填寫正改變 g2.fillPolygon(p.xpoints頁。 ypoints中,4); \t g2.fillPolygon(p); 但現在我的畫線不可見。我的意思是我可以簡單地將不同的顏色應用於我的曲線,以便可以看到它? 再次感謝 – lifeline2 2010-07-30 08:46:28

+0

嘗試在調用draw之前調用fillPolygon。 – nokul 2010-07-30 09:56:33

+0

太棒了!非常感謝你的工作。根據您的建議進行以下更改: g2.setColor(new Color(120,250,100)); \t g2.fillPolygon(p.xpoints,p.ypoints,4); \t g2.fillPolygon(p); \t g2.setColor(Color.BLACK); \t g2.draw(p); – lifeline2 2010-07-30 10:31:32

1

繪製矩形並填充顏色.....

public void paint(Graphics g) 
    { 
int[] xPoints = {100,50,150}; 
int[] yPoints = {100,200,200}; 

     g.setColor(Color.black); 
     g.drawPolygon(xPoints, yPoints, 3); 
     g.setColor(Color.red); 
     g.fillPolygon(xPoints, yPoints, 3); 

    }