java中使用Graphics绘制线条
下面是一个在两个点中绘制 1 条线的方法的示例
public void paintComponent(Graphics comp) {
Graphics2D comp2D = (Graphics2D)comp;
comp2D.drawLine(0,60,100,60);
}
我试图为这些点传递一个构造函数,但是当我在 main 中运行它时,我无法确定当我调用 PaintComponent 时应该为 comp 传递什么
public class DrawLines{
public void paintComponent(Graphics comp,int x0, int y0, int x1, int y1) {
Graphics2D comp2D = (Graphics2D)comp;
comp2D.drawLine(x0,y0,x1,y1);
}
public static void main(String[]args){
drawLine(?,100,200,200,300);
}
}
值我通过在?
Heres an example of a method to draw 1 line passing in two points
public void paintComponent(Graphics comp) {
Graphics2D comp2D = (Graphics2D)comp;
comp2D.drawLine(0,60,100,60);
}
Im trying to pass in a constructor for the points but when I go to run it in main I cannot figure what value I should pass in for comp when I call paintComponent
public class DrawLines{
public void paintComponent(Graphics comp,int x0, int y0, int x1, int y1) {
Graphics2D comp2D = (Graphics2D)comp;
comp2D.drawLine(x0,y0,x1,y1);
}
public static void main(String[]args){
drawLine(?,100,200,200,300);
}
}
What should I pass in at the ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要一个
Graphics
(使用 Swing 时通常是一个Graphics2D
实例)对象,它为您提供了一些实际绘制的上下文。看看你的主类...你想画一条线,但是你必须在什么上画呢?不会神奇地弹出一些窗口或画布供您绘画,您需要设置这些东西。我建议查看 Java Swing 教程。也就是说,如果您已经相当精通 Java。如果没有,请确保您的 Java 知识首先达到了适当的水平。
You need a
Graphics
(will normally be aGraphics2D
instance when using Swing) object, which gives you some context to actually draw with. Take a look at your main class... You want to draw a line, but what do you have to draw on? There isn't magically gonna be some window or canvas that pops up to draw on, you'll need to set that stuff up.I suggest checking the Java Swing tutorial. That is, if you're already reasonably well versed in Java. If not, make sure your Java knowledge is first brought up to a decent level.
您需要为您的类提供两个 Point 字段,或者四个 int 字段,x1、y1、x2、y2,传递用于在构造函数中初始化这些字段的值,然后最重要的是,使用该值绘图时保留在这些字段中。
例如,
You'll want to give your class two Point fields, either that or four int fields, x1, y1, x2, y2, pass the values used to initialize these fields in your constructor, and then most important, use the value held in these fields when doing your drawing.
e.g.,