2015-05-03 40 views
0

下面是我嘗試繪製線條試圖根據雙打畫線,但沒有顯示?

package gps; 
import java.awt.*; 
import java.awt.geom.Line2D; 
import java.util.*; 

import javax.swing.*; 

public class RoadMap extends JPanel { 

    public void paintComponent(Graphics2D g) 
    { 
     super.paintComponent(g); 
     g.setColor(Color.blue); 

     for(int i = 0; i < Graph.getEdges().length; i++) 
     { 
      Shape s = new Line2D.Double(Graph.vMap.get(Graph.getEdges()[i].i1).x, 
        Graph.vMap.get(Graph.getEdges()[i].i1).y, 
        Graph.vMap.get(Graph.getEdges()[i].i2).x, 
        Graph.vMap.get(Graph.getEdges()[i].i2).y); 

      g.draw(s); 
     } 
    } 
} 

Graph.vMap.get(Graph.getEdges()[i].i2).xGraph.vMap.get(Graph.getEdges()[i].i2).y訪問xy值線的端點類,我已經測試,它返回正確的價值觀。然而,沒有什麼在我的JFrame中顯示出來。嘗試在for循環之外繪製其他具有設置值的行實際工作。

+0

什麼是你的畫線典型'x'和'y'值? – copeg

+0

x1 = 43.12929,x2 = 43.12976,y1 = -77.626956,y2 = -77.62679 – kevsta322

+0

由這些值定義的線的端點相差一個像素的分數。如果你想看到這麼小的線條,你將不得不縮放它們,以便線條的長度變得大於一個像素。 – copeg

回答

2

X1 = 43.12929,X2 = 43.12976,Y1 = -77.626956,Y2 = -77.62679

這些y值是在面板外。 AWT/Swing組件的可視座標空間從(0, 0)延伸到(width-1, height-1)

檢查您計算值的位置。如果你想(0, 0)爲中心,你需要通過例如一些算術或翻譯。 Graphics2D#translate(int, int)

此外:

public void paintComponent(Graphics2D g) 

如果你想覆蓋paintComponent,你還沒有這樣做。 paintComponent需要Graphics,而不是一個Graphics2D

@Override 
protected void paintComponent(Graphics g) { 
    Graphics2D g2 = (Graphics2D) g; 

始終使用@Override註釋當您試圖重寫,因爲它會導致一個錯誤,告訴你,如果它不是一個替代。請參閱https://docs.oracle.com/javase/tutorial/java/IandI/override.html

也許你的意思是用這樣的:

public class RoadMap extends JPanel { 
    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 

     Graphics2D g2 = (Graphics2D) g.create(); 
     g2.translate(getWidth()/2, getHeight()/2); 

     g2.setColor(Color.blue); 

     for(int i = 0; i < Graph.getEdges().length; i++) { 
      Shape s = new Line2D.Double(
       Graph.vMap.get(Graph.getEdges()[i].i1).x, 
       Graph.vMap.get(Graph.getEdges()[i].i1).y, 
       Graph.vMap.get(Graph.getEdges()[i].i2).x, 
       Graph.vMap.get(Graph.getEdges()[i].i2).y); 

      g2.draw(s); 
     } 

     g2.dispose(); 
    } 
}