Reputation: 334
I'm trying to create two threads, with one using keylistener and pipedoutputstream to give input to the other thread(pipedinputstream). The way I implemented it: two Runnable classes in Main, at which main(String[] args) uses an ExecutorService to control those two threads. With little understanding of how to use a few of these classes, I barely put up something as follow (skipped some code):
public class Main {
final static PipedOutputStream pipedOut = new PipedOutputStream();
final static PipedInputStream pipedIn = new PipedInputStream();
class ListenerOutput extends JPanel implements KeyListener, Runnable {
int eventKey;
char c;
ListenerOutput() {
this.setPreferredSize(new Dimension(500, 500));
addKeyListener(this);
JFrame f = new JFrame();
f.getContentPane().add(new ListenerOutput());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
@Override
{...}
}
class GameLoop implements Runnable {...}
main(String[] args){
try {
pipedOut.connect(pipedIn);
} catch (IOException e) {
e.printStackTrace();
}
ExecutorService service = Executors.newFixedThreadPool(2);
service.execute(new Main().new ListenerOutput());
service.execute(new Main().new GameLoop());
}
The problem is on the line f.getContentPane().add(new ListenerOutput());
.It's recursive, to no end. I know it would throw the StackOverflow error. But still, I'm quite confused with what to do. Thanks in advance!
Upvotes: 1
Views: 89
Reputation: 2801
From the constructor, this line provides a hint:
addKeyListener(this);
To avoid the recursion:
// f.getContentPane().add(new ListenerOutput());
f.getContentPane().add(this);
So the JFrame f
uses the object under construction similar as the KeyListener.
Upvotes: 2