简体   繁体   中英

Trying to draw lines based on doubles but nothing shows?

Here's the class in which I try to draw the lines

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);
        }   
    }   
}

The Graph.vMap.get(Graph.getEdges()[i].i2).x and Graph.vMap.get(Graph.getEdges()[i].i2).y access the x and y values for the endpoints of the lines and I've tested it and it returned the correct values. However, nothing shows up in my JFrame with this. Trying to draw other lines with set values outside of the for loop actually worked.

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

These y values are outside the panel. AWT/Swing component visible coordinate space runs from (0, 0) to (width-1, height-1) .

Check where you are computing the values. If you want (0, 0) to be the center, you need to do some arithmetic or a translation via eg Graphics2D#translate(int, int) .

Furthermore:

public void paintComponent(Graphics2D g)

If you are trying to override paintComponent , you have not done so. paintComponent takes a Graphics , not a Graphics2D :

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

Always use the @Override annotation when you attempt to override, because it will cause an error and tell you if it's not an override. See https://docs.oracle.com/javase/tutorial/java/IandI/override.html .

Possibly you mean to use something like this:

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM