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);
    }
}
有帮助吗?

解决方案

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top