扩展 Graphics2D 类而不实现所有方法
我有一个名为 MyClass 的类,我希望该类扩展 Graphics2D (在 java.awt 中)。但是,当我输入 public class MyClass extends Graphics2D { .... } 时,我必须添加未实现的方法 draw、drawImage、addRenderingHints 等,因为 Eclipse 显示此错误并且无法编译。
这就是我想到的问题:我只想使用 Graphics2D 的 draw、setBackground 和其他一些方法,我不希望其余的代码出现与其他未实现的强制方法。
有办法避免这种情况吗?因为我在代码方面非常干净和简单,我不想要其他 100 行我什至不使用的代码。
您有什么建议?
I have a class named MyClass and I want this class to extend Graphics2D (in java.awt). However when I type public class MyClass extends Graphics2D { .... }
I have to add the unimplemented methods draw, drawImage, addRenderingHints, etc. because Eclipse shows this error and it won't compile.
This is where the question comes to my mind: I just want to use draw, setBackground and other few methods of Graphics2D, I don't want the rest of the code coming with other unimplemented methods which are mandatory.
Is there a way to avoid this? Because I'm extremely clean and simple when it comes to code and I don't want other 100 lines of code which I don't even use.
What are your suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以让它扩展 Graphics,并且每当您需要 Graphics2D 时,只需进行转换即可。
图形 g = this.create()
;Graphics2D g2d = (Graphics2D) g;
但是,您需要在其中创建一个 Graphics 变量,因为您无法转换
this
。所以对于“setBackground”:
确实,不管你做什么,它都会变得混乱。我什至不确定你是否可以在不发生不好的事情的情况下执行 this.create() 事情,所以请记住这一点。
You could have it extend Graphics, and whenever you need a Graphics2D, just cast.
Graphics g = this.create()
;Graphics2D g2d = (Graphics2D) g;
You'd need to make a Graphics variable within however, as you cannot cast
this
.So for "setBackground":
Really, though, no matter what you do, it's going to be messy. I'm not even sure if you can do the this.create() thing without bad stuff happening, so keep that in mind.
请参阅 http://download.oracle.com/javase/ 6/docs/api/java/awt/Graphics2D.html
Graphics2D是一个抽象类,很多方法都不是抽象的,必须定义所有这些方法才能获得可以实例化的子类。
如果你想尝试,你可以尝试扩展一些实现 Graphics2D 的类。但是,如果您不小心,您将面临您想要的方法的实现可能与您不重写的方法不一致的风险......
See http://download.oracle.com/javase/6/docs/api/java/awt/Graphics2D.html
Graphics2D is an abstract class, lots of methods are not abstract and all of them must be defined in order to get a subclass that can be instantiated.
If you want to try, you could try extending some class that implements Graphics2D. But then, if you are not careful you will be risking that your implementation of the methods that you want may not be coherent with the methods that you do not override...