public void paint(Graphics g){
Graphics2D g2 = (Graphics2D)g; //
double r = 100; //the radius of the circle
//draw the circle
Ellipse2D.Double circle = new Ellipse2D.Double(0, 0, 2 * r, 2 * r);
g2.draw(circle);
这是我程序中一个类的一部分,我的问题在于
Graphics2D g2 = (Graphics2D)g;
为什么必须在 (Graphics2D) 之后加上“g”,以及括号内的“Graphics2D”到底是什么意思,我正在从一本书中学习,但这些都没有得到充分解释。
最佳答案
您正在将 Graphics2D
转换为 Graphics
上下文 g
。在 Inheritance 中阅读有关类型转换的更多信息在 Casting 部分。
这最终所做的是分配您使用 Graphics2D
的可用方法以及传递给 paintComponent
方法的 Graphics
上下文。如果没有转换,您将仅限于 Graphics
类的方法
Graphics2D
是 Graphics
的子类,因此通过使用 Graphics2D
您可以获得 Graphics
的所有方法,同时获取Graphics2D
类中方法的优势。
边注
你不应该覆盖
paint
。此外,如果您是,则不应在像JApplet
这样的顶级容器上绘制。而是在
JPanel
或JComponent
上绘制并覆盖paintComponent
而不是paint
并调用super.paintComponent
。然后只需将JPanel
添加到父容器即可。public DrawPanel extends JPanel { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; } }
查看更多信息 Custom Painting和 Graphics2D
关于java - 获取 Graphics2D?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21710323/