在 Java 中绘制多段线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19857624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Drawing a polyline in Java
提问by Surangie
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? :)
我正在我的程序员课程中做一项任务,需要绘制折线。我正在使用 Eclipse,但这段代码没有出现语法错误。但是我不明白为什么我的 polyLine 在运行程序时没有显示。有人想启发一个新的程序员吗?:)
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);
}
}
采纳答案by Ash
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);