java中如何实现:主线程等待UI输入,然后继续运行?

import java.awt.Container;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Test extends JFrame{

public Test(){
Container container = getContentPane();
container.add(new JButton("主线程继续"));
}

public static void main(String[] args) {

Test frame = new Test();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(100,100);
frame.setVisible(true);

System.out.println("1");
//这里时要求的代码,要求主线程在这里悬停,直到我按下“主线程继续”按钮,然后才输出“2”
System.out.println("2");
}
}

在你的代码基础上改进了。

package com.sacswing.resource;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Test extends JFrame {
//同步变量
private static Boolean continueThread = false;

public Test() {
Container container = getContentPane();
JButton btn = new JButton("主线程继续");

//按钮要添加监听,来控制共享数据continueThread
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
continueThread = !continueThread;
}
});
container.add(btn);
}

public static void main(String[] args) {

Test frame = new Test();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(100, 100);
frame.setVisible(true);

System.out.println("1");

// 这里时要求的代码,要求主线程在这里悬停,直到我按下“主线程继续”按钮,然后才输出“2”
synchronized (continueThread) {
//如果继续线程为false,则执行循环
while (continueThread == false) {
}
}
System.out.println("2");
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-02-28
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test extends JFrame implements ActionListener {
static JFrame frame = null;
static JPanel panel = null;
static JButton button = null;

public Test() {
frame = new JFrame();
panel = new JPanel();
button = new JButton("主线程继续");

frame.add(panel);
panel.add(button);
button.addActionListener(this);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(100, 100);
frame.setVisible(true);
}

public static void main(String[] args) {
System.out.println("1");
new Test();
}

public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource() == button) {
System.out.println("2");
}
}

}

这个格式比较标准,实现了你的功能。
记住:一般我们都把构造窗口和对窗口的设置放到构造方法中哦^_^
第2个回答  2011-02-28
先wait 当点击事件返回值真的时候 唤醒
第3个回答  2011-02-28
最好用两个线程,一个就是主线程,还有一个线程执行窗口,然后再输出“1”后加入this.wait(),使主线程暂停直至两一个线程唤醒他,然后就可以在窗口线程中调用this.notify()或者this.notifyAll()来唤醒主线程

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网