我有 Jframe 表单并创建了从中绘制图形的类,为此我需要将该 void 类扩展为 jframe 表单
package grafiktest;
import java.awt.Color;
import java.awt.Graphics;
public class testoutput extends javax.swing.JFrame{
Graphics g;
public testoutput() {
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
g=jPanel1.getGraphics();
test tod = new test();
tod.test();
}
我创建的类:
public class test extends testoutput{
void test(){
testoutput tod = new testoutput();
g=tod.jPanel1.getGraphics();
g.setColor(Color.decode("#7D9AB3"));
g.fillRect(3,3,3,3);
}
}
有什么办法可以扩展吗? 我是这方面的新手,谢谢
最佳答案
暂时忽略你画得不好,你应该先仔细看看Inheritance trail这将为您提供更多信息。
简而言之,不,这不是继承的工作原理。
我知道这可能会令人困惑,我强烈建议您通过使用JFrame
来简化您的示例。脱离图片并查看操作如何进行
让我们从一个足够简单的例子开始......
public class Parent {
public Parent() {
//...
}
public void performSomeAction() {
System.out.println("I'm called from within parent");
}
}
还有一些子类
public class Child extends Parent {
@Override
public void performSomeAction() {
// Action overridden from parent
// You can call super.performSomeAction()
// if you wish to maintain the functionality the parent class was
// performing as needed
System.out.println("I'm called from within child");
}
}
现在,让我们看看如果这样做会发生什么......
Parent parent = new Parent();
Child child = new Child();
parent.performSomeAction();
child.performSomeAction();
这输出...
I'm called from within parent
I'm called from within child
不是很令人兴奋,但你明白了。
但是,等等,让我们改变一下 Child
public class Child extends Parent {
@Override
public void performSomeAction() {
super.performSomeAction()
System.out.println("I'm called from within child");
}
}
现在,如果我们重新运行测试代码,我们会得到
I'm called from within parent
I'm called from within parent
I'm called from within child
额外的“家长”电话是从哪里来的!?它来自super.performSomeAction()
,这只是调用父级的方法 - 这就是如何重写方法来扩展其功能,甚至完全覆盖(如第一个示例中所做的那样)。
现在,让我们做一些非常奇怪的事情......
Parent parent = new Parent();
Parent child = new Child();
parent.performSomeAction();
child.performSomeAction();
你认为输出会是什么?!
我将其留给您进行测试,但您可能还想查看 Polymorphism并做好准备🤯
最后...去阅读 Performing Custom Painting和 Painting in AWT and Swing更好地了解绘画的工作原理以及使用它需要做什么
关于java - 将 Graphic Void 扩展到 Jframe?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49293307/