0

I have some classes that extends Jframe and implements same interface.

public class classe extends JFrame implements Elenco{
@Override
   public void prova(){
   .......
   }       

}

In another class i have:

 public class Selezione{
 Elenco e;
 e.Prova();
 }

In this class how can i show class that implements interface elenco?
i can't do e.setVisible(true);

I try this solution but it doesn't work

 public class Selezione{
Elenco e;
 public Modifica(){
 e.Prova();

 }

public void Transfert(JFrame frame) {
   frame = (JFrame) e;  

}

3 Answers3

0

You have to add the setVisible method to the interface Elenco. Or you change the type from Elenco to JFrame this would also be possible with casting.

Also your code does not work this way, you have to change it to:

public interface Elenco {
    ...
    public void setVisible(boolean visible);
}

public class Selezione {
    Elenco e;

    public void do() {
        e.prova();
        e.setVisible(true);
    }
}
wake-0
  • 3,918
  • 5
  • 28
  • 45
0

If you want to check whether an Elenco object is actually a JFrame, you can use the instanceof operator with an if statement:

if (e instanceof JFrame) {
    // Here I cast e to type JFrame
    JFrame frame = (JFrame)e;
    // Now you can call setVisible!
    frame.setVisible(true);
}

It's basically just a cast.

Alternatively, you can add a method to Elenco called setVisible:

interface Elenco {
    void prova();
    void setVisible(boolean visible);
}

Since your classe extends JFrame and JFrame already contains the setVisble method, you don't need to add any extra methods.

If you use the second approach, you can call setVisible directly on e, without the cast:

e.setVisible(true);

If you wish to use other methods in JFrame, you can add them to your interface, too.

The third approach is to directly store a JFrame in Selezione:

public class Selezione {
    JFrame frame;
}

But this is not very recommended because we should keep the abstraction in a class consistent.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

Your problem is the the field e has the reference type Elenco and at compile time you can't call other methods but those found in that interface. If you wish to call setVisible, you should cast e to class classe (which is an awful class name). After casting you could call dirrectly setVisible(). Other method would be to add the setVisible code in the classes's implementation of the prova method

Slimu
  • 2,301
  • 1
  • 22
  • 28