2013-02-23 15 views
-3

我尝试运行下面的源代码,但得到设置配置,同时保持的JPanel型

类型不匹配:不能从CustomJPan转换的JPanel

错误。有人可以帮忙吗?请原谅,我从头顶开始。

public class rebuiltgui extends JApplet { 

    public void init() { 

    JPanel jpan = new CustomJPan();  
    } 
} 

class CustomJPan { 

    public JPanel CustomJPan() { 

    thispan = new JPanel(); 
    thispan.setBackground(Color.red); 
    return thispan; 
    } 

    public changeColour() { 

    // Change colour to blue here 
    } 
} 
+0

http://docs.oracle.com/javase/tutorial/java/javaOO/classes.html – 2013-02-23 04:30:51

+0

对不起,我以为我是子类(facepalm) – 2013-02-23 04:33:22

回答

2

试着这么做

public class rebuiltgui extends JApplet { 

    public void init() { 

    JPanel jpan = new CustomJPan();  
    } 
} 

class CustomJPan extends JPanel { 

    public CustomJPan() { 
     super(); 
     setBackground(Color.red); 
    } 

    public void changeColour() { 

    // Change colour to blue here 
    } 
} 

我已经更改为扩展JPanel

+0

太棒了!我没有选择在线,这真的让我感到困扰。TYVM – 2013-02-23 05:00:40

+0

你是我最好的朋友 – 2013-02-23 05:45:48

2

因为CustomJPan没有扩展任何东西,所以你的代码不会直接创建子类。相反,你似乎有一个与该类名称相同的“伪”构造函数,CustomJPan试图返回一些东西,并且当然你知道构造函数被声明为不返回任何东西。

如果你想子类,你必须扩展另一类。

public class CustomJPan extends JPanel { 

    // a real constructor has no return type! 
    public CustomJPan() { 
     // ....   
    } 

    // ... etc 
} 

子类化很好地覆盖在任何Java的入门教材,你会很好地阅读本章节。

一个告诫:除非你有明确的需求,例如希望改变一个类的固有行为,特别是当你想要覆盖方法时,你会希望避免子类化。

+0

对不起!我是C++的家伙和OOP Swing有点新 – 2013-02-23 04:34:42

+0

@RolandSams:再次,你会想要阅读这个文本,因为它在这里都有很好的解释。 – 2013-02-23 04:35:36

+0

我只想要一个简洁的方式来清理我的主要Java文件中的碎片(像设置组件属性)我想隐藏其他类中的各种JPanels等 – 2013-02-23 04:39:54