[英]Why can't paintComponent accept a Graphics2D object?
public class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g){
Graphics2D gd2 = (Graphics2D) g;
GradientPaint gradient = new GradientPaint(70,70,Color.blue,150,150,Color.red);
}
}
Why is this valid but not this: 为什么这是有效的,但不是这样的:
public class MyDrawPanel extends JPanel {
public void paintComponent(Graphics2D g){
GradientPaint gradient = new GradientPaint(70,70,Color.blue,150,150,Color.red);
g.setPaint(gradient);
g.fillOval(70,70,100,100);
}
}
First one renders, but the second one renders no graphics other than the frame. 第一个渲染,但是第二个渲染除框架以外的任何图形。 I noticed that paintComponent() requires a Graphics object, but if Graphics2D is a subclass of the Graphics object why can I not call a subclass of Graphics?
我注意到paintComponent()需要一个Graphics对象,但是如果Graphics2D是Graphics对象的子类,为什么不能调用Graphics的子类呢?
Is there some concept I am not picking up as to why this is? 关于这是为什么,我是否有一些概念不了解?
It says that you should implement it this way, because Graphics2D is Graphics, while Graphics is not Graphics2D. 它说您应该以这种方式实现,因为Graphics2D是Graphics,而Graphics不是Graphics2D。
If you find casting disturbing, you can always create your own eg. 如果发现投放干扰,可以随时创建自己的示例。 MyJPanel that extends JPanel, define your own method, and subclass it in the future, overriding your defined method.
扩展JPanel的MyJPanel,定义您自己的方法,并在将来子类化,覆盖您定义的方法。
public class MyJPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
paintComponent((Graphics2D) g);
}
protected void paintComponent(Graphics2D g) {
}
}
Basically, when you override a method, you can be equally or less specific. 基本上,当您覆盖方法时,您可以具有相同或更少的特定性。
Think about this: 考虑一下:
JPanel p = new MyPanel();
p.paintComponent(someGraphicsInstance);
A reference to a JPanel
is expected to be able to accept a Graphics reference as a parameter to the paintComponent
method. 希望对
JPanel
的引用能够接受Graphics引用作为paintComponent
方法的参数。 Your method, however, violates that requirement as it will not accept a Graphics
instance, but only a Graphics2D
. 但是,您的方法违反了该要求,因为它不接受
Graphics
实例,而仅接受Graphics2D
。
More information about this can be found https://stackoverflow.com/a/9950538/567864 有关此的更多信息,请参见https://stackoverflow.com/a/9950538/567864
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.