2017-04-15 42 views
2

我正在學習Java圖形。我試圖畫出簡單的數字。不過我注意到,下面的代碼將無法正確得出:爲什麼不能用fillPolygon()繪製一個矩形

public class Draw extends JPanel { 

    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     int[] xpoints = new int[] { 20, 50, 80 }; 
     int[] ypoints = new int[] { 40, 10, 40 }; 

     g.fillPolygon(xpoints, ypoints, 3); 

     int[] recXp = new int[] { 20, 80, 20, 80 }; 
     int[] recYp = new int[] { 50, 60, 50, 60 }; 

     g.fillPolygon(recXp, recYp, 4); 

    } 

    public static void main(String[] args) { 
     JFrame frame = new JFrame(); 
     Draw panel = new Draw(); 
     frame.add(panel); 
     frame.setVisible(true); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(800, 600); 

    } 
} 

爲了達到我想要什麼,我不得不使用

import java.awt.Graphics; 

import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class Draw extends JPanel { 

    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     int[] xpoints = new int[] { 20, 50, 80 }; 
     int[] ypoints = new int[] { 40, 10, 40 }; 

     g.fillPolygon(xpoints, ypoints, 3); 

     g.fillRect(20, 50, 60, 10); 

    } 

    public static void main(String[] args) { 
     JFrame frame = new JFrame(); 
     Draw panel = new Draw(); 
     frame.add(panel); 
     frame.setVisible(true); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(800, 600); 

    } 
} 

這究竟是爲什麼?我錯過了什麼嗎?對不起,如果這是一個微不足道的問題,我只是想更好地理解Java。

回答

2
int[] recXp = new int[] { 20, 80, 20, 80 }; 
    int[] recYp = new int[] { 50, 60, 50, 60 }; 

您只有兩組積分。你需要4組不同的點。一個用於矩形的每個角落。

是這樣的:

  1. 頂部/左(20,50)
  2. 頂部/右(x是一個從上面不同,Y是相同的)
  3. 底/右(x是相同以上,y爲不同。
  4. 底/左(x是相同的第一,y是如上保存)
+0

我它在改變爲 \t \t t [] recXp = new int [] {20,80,80,20}; \t \t int [] recYp = new int [] {50,50,60,60}; 及其正確顯示,抱歉的愚蠢問題:) – Moe

+2

有沒有愚蠢的問題,如果你想學習。 – c0der

+1

@moe,同意c0der,有時使用方法會讓我們感到困惑。你創建了一個很好的簡單[mcve]來測試顯示你所嘗試的方法。我們很高興在您做出這些努力時提供幫助。 – camickr