如何停止执行Java代码并等待ActionEvent?

时间:2013-10-14 11:10:30

标签: java swing actionlistener wait notify

如果我想等待用户互动(等待用户按某个按钮时),请确保此方法是否正确:

SomeDialog someDialog = new SomeDialog(frame);

someDialog.setVisible(true);

try {

       synchronized (someDialog) {
          someDialog.wait();
       }

     } catch (InterruptedException ex) {
       Logger.getLogger(SomeDialog.class.getName()).log(Level.SEVERE, null, ex);
     }

int a = 0; a++; // <---- this line should not be processed before user clicks a button

然后:

someDialogButton.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {

    synchronized (SomeDialog.this) {
       SomeDialog.this.notify();
    }

  }
});

1 个答案:

答案 0 :(得分:0)

如果您需要等待用户处理对话,请先使用someDialog.setModal(true)