[英]Can't get Java2D to render a simple line to a Graphics object
因為我想調用不同類的繪圖方法並在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(“Call draw method?\\ 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引用畫布,為什么
to_draw.setColor(Color.BLACK); to_draw.drawLine(31,41,131,768); //沒用......?
任何其他方法來滿足我的要求:
“調用不同類的繪圖方法並在JPanel上繪制不同的圖形,因此我需要將繪圖板(JPanel或其他東西)作為參數,將其傳遞給我的繪圖方法。”
您應該覆蓋面板的paintComponent(Graphics g)
方法。 在方法中調用super.paintComponent(g)
然后調用draw()
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.