2013-10-10 37 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