Question

I'm doing a task in my programmer course, and need to draw polyLines. I'm using Eclipse and I get no syntax errors with this code. But I don't understand why my polyLine isn't showing when I run the program. Anyone want to enlighten a fresh programmer? :)

Heres the code:

package oppgave4;
import javax.swing.*;
import java.awt.*;

class CoordinateSystem extends JPanel {
    @Override
    protected void paintComponent(Graphics g){
        super.paintComponent(g);
        int[] xSin = {1, 2, 3, 4, 5, 6};
        int[] ySin = {1, 2, 3, 4, 5, 6};

        g.drawPolyline(xSin, ySin, xSin.length);
        g.drawLine(150, 0, 150, 300);
        g.drawLine(0, 150, 300, 150);
    }   
}

and the Test Program:

package oppgave4;
import javax.swing.*;
import java.awt.*;

public class TestProgram extends JFrame{
    public TestProgram(){
        add(new CoordinateSystem());
    }

    public static void main(String[] args) {
        TestProgram grid = new TestProgram();
        grid.setSize(300, 300);
        grid.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        grid.setVisible(true);
    }
}
Was it helpful?

Solution

Before doing any drawing, you usually have to set an appropriate color in the graphics context. Otherwise it may be set to some random value from the previous user of the graphics context, or a default value like the background color.

In the example above, adding the following will make the graphics visible:

g.setColor(Color.RED);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top