What i want do is,
I have a class named 'TestPanel' that extends from JPanel. and want to make it draggable by a method. But method returns JPanel type and shows this error when compiling.
cannot convert from JPanel to testpanel
Method cannot be make for return 'TestPanel' type because i hope to make more classes like testpanel. Here is the RegisterAsDraggable
method that returns JPanel.
public static JPanel RegisterAsDraggable(){
final JPanel panel = new JPanel();
...
return panel;
}
Here is the class that extends from JPanel.
public class testpanel extends JPanel {
JLabel titlelabel;
public testpanel(){
initsettings();
GroupLayout layout = new GroupLayout(this);
this.setLayout(layout);
...
}
}
And here is my main class.
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);
}
}
I removed some of codes because for make this not too long.
-- Edit --
I tried to do that by casting testpanel into JPanel.( Accouding to your answers). But it showed this error
Exception in thread "main" java.lang.ClassCastException: javax.swing.JPanel cannot be cast to testpanel
Can anyone help? Please excuse my English.
Please do yourself a favor: Learn and follow Java coding standards.
You just need to make one change:
JPanel tstpan = DragsExternal.RegisterAsDraggable();
or
testpanel tstpan = (testpanel) DragsExternal.RegisterAsDraggable();
you need to cast the Jpanel to a testpanel
private void initcomponent() {
testpanel tstpan = (testpanel) DragsExternal.RegisterAsDraggable();
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.