无法让Java2D渲染到Graphics对象的简单行

时间:2011-11-07 13:17:53

标签: java swing drawing java-2d

因为我想调用不同类的绘图方法并在JPanel上绘制不同的图形所以我需要将绘图板(JPanel或其他东西)作为参数,将其传递给我的绘图方法。(但我不知道如果我能做到这一点......这里的案例是另一次尝试...)

这是我实施的一部分。

我创建了一个类class_diagram,如下所示:

public class class_diagram extends Object
{

private final int width = 60;  
private final int height = 80; 
private final int first_separate_line_distance= 30; 
private final int second_separate_line_distance= 55;
private int left_up_x = 0;
private int left_up_y = 0; 

public void setLeft_up(int left_up_x,int left_up_y) 
{
    this.left_up_x = left_up_x;
    this.left_up_y = left_up_y;
}


//private Graphics to_draw ;
//private JPanel place_to_draw; 

public class_diagram()
{
     // instance variable "point to" the reference which was passed in.  
}

@Override
//the parameters stands for the left-up point's coordinate. 
public void draw(Graphics to_draw) {
    // TODO Auto-generated method stub

    System.out.println("Call draw method?\n");
    to_draw.setColor(Color.BLACK);
    to_draw.drawLine(31, 41, 131, 768);     
}

}

以上是类定义及其绘图方法。

在另一个班级:

我调用draw方法,它确实被调用了,因为  System.out.println(“调用绘制方法?\ n”);在那个绘制方法向我显示消息。

然而!!!在我的JPanel上绘图......它让我失望了。  因为我尝试了至少4-5种方法....

import java.awt.BorderLayout;

public class UML_Editor_13 extends JFrame {

private Edit_panel canvas = new Edit_panel();

public static void main(String[] args) {                    

UML_Editor_13 frame = new UML_Editor_13();

frame.setVisible(true);

Graphics m= frame.canvas.getGraphics();                 

Object n = new class_diagram();

n.draw(m);

}
}
  1. 请有人告诉我为什么这行“Graphics m = frame.canvas.getGraphics();” 不起作用...如果m引用画布,为什么

    to_draw.setColor(Color.BLACK); to_draw.drawLine(31,41,131,768); //没用......?

  2. 满足我要求的任何其他方法:

  3. “调用不同类的绘图方法并在JPanel上绘制不同的图形,所以我需要将绘图板(JPanel或其他东西)作为参数,将其传递给我的绘图方法。”

1 个答案:

答案 0 :(得分:2)

您应该覆盖面板的paintComponent(Graphics g)方法。在方法中调用super.paintComponent(g),然后调用draw()方法。