繁体   English   中英

将使用JPanel扩展的类转换为JPanel

[英]Convert classes that extends with JPanel into JPanel

我想做的是

我有一个名为“ TestPanel”的类,它是从JPanel扩展的。 并希望通过某种方法使其可拖动。 但是方法返回JPanel类型并在编译时显示此错误。

cannot convert from JPanel to testpanel

无法将方法设为返回“ TestPanel”类型,因为我希望创建更多类似testpanel的类。 这是返回JPanel的RegisterAsDraggable方法。

    public static JPanel RegisterAsDraggable(){
        final JPanel panel = new JPanel();
        ...
        return panel;
    }

这是从JPanel扩展的类。

public class testpanel extends JPanel {
    JLabel titlelabel;

    public testpanel(){
        initsettings();

        GroupLayout layout = new GroupLayout(this);
        this.setLayout(layout);
        ...
    }
}

这是我的主班。

public class HelloWorld extends JFrame {

    public HelloWorld(){
        initcomponent();
        ...
    }

    private void initcomponent() {
        testpanel tstpan = DragsExternal.RegisterAsDraggable();
        ...
    }

    public static void main(String[] args){
        new HelloWorld().setVisible(true);
    }
}

我删除了一些代码,因为这样做的时间不太长。

-编辑-

我试图通过将testpanel投放到JPanel中来做到这一点(根据您的回答)。 但是它显示了这个错误

Exception in thread "main" java.lang.ClassCastException: javax.swing.JPanel cannot be cast to testpanel

有人可以帮忙吗? 请原谅我的英语。

请帮个忙:学习并遵循Java编码标准。

您只需要进行一项更改:

 JPanel tstpan = DragsExternal.RegisterAsDraggable();

要么

 testpanel tstpan = (testpanel) DragsExternal.RegisterAsDraggable();

你需要 JPanel中的パ

private void initcomponent() {
    testpanel tstpan = (testpanel) DragsExternal.RegisterAsDraggable();
    ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM