【发布时间】: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
有人可以帮忙吗? 请原谅我的英语。
【问题讨论】:
-
TestPanel或testpanel? , 如果是 testpanel 那么你应该遵循 Java 编码标准。
标签: java swing class jpanel type-conversion