试图根据双打绘制线条,但没有显示?

时间:2015-05-03 20:39:32

标签: java swing jpanel double graphics2d

这是我尝试绘制线条的类

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循环之外的设置值绘制其他行实际上有效。

1 个答案:

答案 0 :(得分: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();
    }
}