【问题标题】:separate class that implements keylistener and jpanel实现 keylistener 和 jpanel 的单独类
【发布时间】:2017-11-01 17:24:32
【问题描述】:

我正在尝试创建两个线程,其中一个使用 keylistener 和 pipedoutputstream 为另一个线程(pipedinputstream)提供输入。我实现它的方式:Main 中的两个 Runnable 类,其中 main(String[] args) 使用 ExecutorService 来控制这两个线程。由于对如何使用其中一些类知之甚少,我几乎没有提出以下内容(跳过一些代码):

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());
}

问题出在f.getContentPane().add(new ListenerOutput());线上。它是递归的,没有尽头。我知道它会抛出 StackOverflow 错误。但是,我仍然很困惑该怎么做。提前致谢!

【问题讨论】:

  • f.getContentPane().add(this);

标签: java multithreading swing


【解决方案1】:

在构造函数中,这一行提供了一个提示:

addKeyListener(this);

为了避免递归:

// f.getContentPane().add(new ListenerOutput());
f.getContentPane().add(this);

所以 JFrame f 使用类似于 KeyListener 的正在构建的对象。

【讨论】:

    猜你喜欢
    • 2012-01-01
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-04
    • 2014-05-06
    • 2013-05-31
    相关资源
    最近更新 更多