2013-10-10 40 views
0

我使用Eclipse,我想使圖形行成的JFrame通過下面的代碼:如何在JFrame中生成圖形行?

public void Makeline() { 
    Graphics g=new Graphics(); // has error 
    Graphics2D g2 = (Graphics2D) g; 
    g2.draw(new Line2D.Double(0, 0, 20, 20)); 
} 

但給跟隨着錯誤:

Cannot instantiate the type Graphics 
+0

圖形是抽象的,你必須擴展它實現所需的方法。 – DSquare

回答

3

Graphics是一個抽象類,定義了整個API的要求。

Swing中的繪畫是在繪畫鏈的上下文中完成的。這通常是從JComponent

延長部件的paintComponent方法中進行看一看Perfoming Custom Painting更多細節

你也可以使用一個BufferdImage生成一個Graphics背景,但你仍然需要的地方畫圖像,所以它會降低你想要達到的效果。

3

的解決方案是覆蓋的paintComponent方法,但JFrame的不是JComponent,因此而不是JFrame,請使用JPanel,然後將JPanel添加到JFrame。

paintComponent(Graphics g) { 
    super.paintComponent(g) 

    //here goes your code 
    Graphics2D g2 = (Graphics2D) g; 
    ... 
} 
+0

@SamieyMehdi你如何實施它? – MadProgrammer

+0

@SamieyMehdi我的評論不是回答你的問題,而是建議改善這個答案。 – Pshemo

+0

@SamieyMehdi開始閱讀[執行自定義繪畫](http://docs.oracle.com/javase/tutorial/uiswing/painting/) – MadProgrammer

0

圖形是一個抽象類。你不能以下面的方式實例化。

Graphics g=new Graphics(); 

要訪問Graphics2D,首先你需要重寫paint(Graphics)方法。

@Override 
public void paint(Graphics g) { 
    Graphics2D g2 = (Graphics2D) g; 
} 
+0

編號1-您通常應避免重寫塗料,尤其是頂層容器。你應該總是打電話給super.paintXxx – MadProgrammer