我正在编写一个程序,我可以绘制一些行,并且我正在测试Canvas
和awt.Frame
如何合作。这是代码:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.ArrayList;
public class Drawing extends Canvas{
Point2D pt1, pt2;
private ArrayList<Shape> linesList;
private Shape shape = null;
public Drawing(){
linesList = new ArrayList<Shape>();
Point p1 = new Point();p1.x = 200;p1.y = 200;
Point p2 = new Point();p2.x = 300;p2.y = 300;
pt1 = (Point2D) p1;
pt2 = (Point2D) p2;
//Line k = new Line(p1,p2,Color.BLUE);
shape = new Line2D.Double ( pt1, pt2 );
linesList.add(shape);
}
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D) g;
//g2d.drawLine(200, 200, 200, 300);
//Shape k = null;
//k = new Shape();
//g2d.setPaint(Color.BLACK );
g2d.setColor(Color.GREEN);
for ( Shape line : linesList )
{
g2d.draw(line);
}
}
public static void main(String[] args){
Frame f = new Frame("Rysuje");
f.setResizable(false);
f.setSize(600, 600);
f.setVisible(true);
Drawing myFrame = new Drawing();
f.add(myFrame);
}
}
我的问题是:g2d.draw(line);
方法中的paint()
为什么不划线?事实上它并没有画任何东西。但是当我写g2d.drawLine(200, 200, 200, 300);
时,它有效......
答案 0 :(得分:1)
使用此来源..
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.ArrayList;
public class Drawing extends Canvas{
Point2D pt1, pt2;
private ArrayList<Shape> linesList;
private Shape shape = null;
public Drawing(){
linesList = new ArrayList<Shape>();
Point p1 = new Point();p1.x = 200;p1.y = 200;
Point p2 = new Point();p2.x = 300;p2.y = 300;
pt1 = (Point2D) p1;
pt2 = (Point2D) p2;
//Line k = new Line(p1,p2,Color.BLUE);
shape = new Line2D.Double ( pt1, pt2 );
linesList.add(shape);
}
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.drawLine(20, 20, 100, 100);
//Shape k = null;
//k = new Shape();
//g2d.setPaint(Color.BLACK );
g2d.setColor(Color.GREEN);
for ( Shape line : linesList )
{
g2d.draw(line);
}
g2d.setColor(Color.BLUE);
}
public static void main(String[] args){
Frame f = new Frame("Rysuje");
f.setResizable(false);
f.setSize(400, 400);
f.setVisible(true);
Drawing myFrame = new Drawing();
f.add(myFrame);
}
}
..我明白这一点:
现在我觉得绿色线出现了,所以我对你期望看到的不同之处感到有些困惑。你看到了同样的事吗?