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

[复制链接]
查看11 | 回复1 | 2011-3-6 08:18:09 | 显示全部楼层 |阅读模式
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\");
}
}
回复

使用道具 举报

千问 | 2011-3-6 08:18:09 | 显示全部楼层
<pre id=\"best-answer-content\" class=\"reply-text mb10\">在你的代码基础上改进了。


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\");
}
}
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行