[英]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.