Reputation: 9361
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?
Upvotes: 2
Views: 7145
Reputation: 15533
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();
}
}
Upvotes: 13
Reputation: 285430
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?
Upvotes: 2
Reputation: 432
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();
}
Upvotes: 3