Search code examples
javaswingjpaneldoublegraphics2d

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.


Solution

  • 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 e.g. 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();
        }
    }