0

下面是一个在两点中绘制 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);
     }
}

我应该传递什么?

4

2 回答 2

4

您需要一个(在使用 Swing 时Graphics通常是一个 实例)对象,它为您提供一些实际绘制的上下文。Graphics2D看看你的主课......你想画一条线,但你必须画什么?不会神奇地弹出一些窗口或画布来绘制,你需要设置这些东西。

我建议查看Java Swing 教程。也就是说,如果您已经相当精通 Java。如果没有,请确保首先将您的 Java 知识提升到一个不错的水平。

于 2011-10-26T15:43:09.267 回答
3

您需要为您的类提供两个 Point 字段,或者是四个 int 字段,x1、y1、x2、y2,传递用于在构造函数中初始化这些字段的值,然后最重要的是,使用这些字段中保存的值绘图时的字段。

例如,

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

public class LinePanel extends JPanel {
   private Point p1; // java.awt.Point objects
   private Point p2;

   // TODO: create constructor that accepts
   // and updates the two points

   public void paintComponent(Graphics g) {

      super.paintComponent(g); // don't forget this!

      // TODO: Change the method below so that it uses
      // the two points to do the drawing with
      // rather than use hard coded magic numbers.
      g.drawLine(0, 0, 90, 90);
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(500, 500);
   }

   public static void main(String args[]) {
      JFrame jf = new JFrame();
      jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      jf.add(new LinePanel()); // TODO: add parameters to constructor call.
      // jf.setSize(500, 500);
      jf.pack();
      jf.setVisible(true);
   }
}
于 2011-10-26T16:09:58.617 回答