因为我想调用不同类的绘图方法并在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("调用draw方法?\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);
}
}
请有人告诉我为什么这行“Graphics m=frame.canvas.getGraphics();” 不起作用...如果 m 引用 Canvas ,为什么
to_draw.setColor(Color.BLACK); to_draw.drawLine(31, 41, 131, 768);//没用...?
满足我的要求的任何其他方法:
“调用不同类的绘图方法并在 JPanel 上绘制不同的图形,因此我需要将绘图板(JPanel 或其他东西)作为参数,将其传递给我的绘图方法。”
最佳答案
您应该重写面板的 paintComponent(Graphics g)
方法。在方法中调用 super.paintComponent(g)
,然后调用 draw()
方法。
关于java - 无法让 Java2D 将简单的线条渲染到 Graphics 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8037006/