2

I have a class that extends Thread, and need to extend JFrame on the same class. since multiple inheritance is not possible in Java, how do it use JFrame objects inside of a class that already extends Thread?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Kevik
  • 9,181
  • 19
  • 92
  • 148
  • 3
    Swing GUI objects should be constructed and manipulated _only_ on the [event dispatch thread](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html). Why extend `JFrame`? – trashgod Feb 08 '13 at 01:38
  • 6
    Why do you need to extend JFrame in the first place? It is usually not necessary. – Cyrille Ka Feb 08 '13 at 01:39
  • 2
    See this question on extending JFrame: http://stackoverflow.com/questions/1143923/why-shouldnt-you-extend-jframe-and-other-components – Cyrille Ka Feb 08 '13 at 01:42
  • 2
    You should usually extend ***neither*** JFrame or Thread. Problem solved. – Hovercraft Full Of Eels Feb 08 '13 at 02:21

3 Answers3

13

Instead of extending either JFrame or Thread, use composition, it is a lot less limiting:

public class MyApplication {
    JFrame applicationFrame;

    Thread someThread;

    MyApplication() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override void run() {
                applicationFrame = new JFrame();

                // some more GUI initialization.
                applicationFrame.setVisible(true);
            }
        });

        someThread = new Thread(new Runnable() {
            @Override void run() {
                // do my work.
            }
        });

        someThread.start();
    }

    public static void main(String... args) {

        new MyApplication();
    }
}
Cyrille Ka
  • 15,328
  • 5
  • 38
  • 58
3

Rather than extending Thread, can you make the class implement Runnable? This way, you could extend JFrame instead, pass it to a Thread.

public class MyFrameThread extends JFrame implements Runnable {

    @Override
    public void run() {
        ...
    }
}

public static void main(String... args) {
    Thread myThread = new Thread(new MyFrameThread());
    myThread.start();
    myThread.join();
}
Bracket
  • 432
  • 1
  • 4
  • 9
  • 3
    extending JFrame is bad idea in general – Nikolay Kuznetsov Feb 08 '13 at 02:14
  • i am making a socket program in java. my only experience is in Android so java swing is vary different from what I am used to. so instead of extending JFrame I will make console application without any GUI. I am doing this to test some code for sockets that i will later use in Android. – Kevik Feb 08 '13 at 02:21
2

You can use JFrames and Threads easily without extending them, and as has been suggested by most, you are usually better off not extending them. Extending them binds your class to the JFrame preventing you from later using it in a JPanel, JDialog, etc. Why restrict yourself like this if not necessary?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373