Java 在维护JPanel类型的同时设置配置

Java 在维护JPanel类型的同时设置配置,java,swing,oop,applet,jpanel,Java,Swing,Oop,Applet,Jpanel,我尝试运行以下源代码,但得到 类型不匹配:无法从CustomJPan转换为JPanel 错误。有人能帮忙吗?请原谅消息来源,我是凭空做的 public class rebuiltgui extends JApplet { public void init() { JPanel jpan = new CustomJPan(); } } class CustomJPan { public JPanel CustomJPan() { thispan

我尝试运行以下源代码,但得到

类型不匹配:无法从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
  }
}

您的代码不直接进行子类化,因为CustomJPan不扩展任何内容。相反,您似乎有一个与类CustomJPan同名的“伪”构造函数,它试图返回一些东西,您当然知道构造函数被声明为不返回任何东西

如果您想要子类化,您必须扩展另一个类

i、 e

子类化在任何Java入门教材中都有很好的介绍,您最好阅读这一章

警告:除非您有明确的需求,例如希望更改类的固有行为,特别是当您希望重写方法时,否则您将希望避免子类化

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

对不起,我以为我在子类化(facepalm)对不起!我是一个C++的家伙和Owing的摆动有点new@RolandSams:同样,你会想阅读上面的文字,因为这里已经解释得很清楚了。我只想找到一种整洁的方法来清理主Java文件中的碎片。(比如设置组件属性)我想在其他类中隐藏各种JPanel之类的东西顺便说一下:这些JPanel将包含其他类components@RolandSams:有时创建一个简单的工厂方法来实现这一点更简单。太好了!它可以工作!我在网上没有选择。这真的让我很困扰。Tyvm你是我最好的朋友
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
  }
}