【问题标题】:Convert classes that extends with JPanel into JPanel将使用 JPanel 扩展的类转换为 JPanel
【发布时间】:2017-06-25 13:06:59
【问题描述】:

我想做的是,

我有一个从 JPanel 扩展而来的名为“TestPanel”的类。并希望通过一种方法使其可拖动。但是方法返回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

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

【问题讨论】:

  • TestPaneltestpanel ? , 如果是 testpanel 那么你应该遵循 Java 编码标准。

标签: java swing class jpanel type-conversion


【解决方案1】:

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

您只需要进行一项更改:

 JPanel tstpan = DragsExternal.RegisterAsDraggable();

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

【讨论】:

    【解决方案2】:

    你需要castJpanel 到一个测试面板

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-23
      • 1970-01-01
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多