62,614
社区成员
发帖
与我相关
我的任务
分享
package swingproblem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Entrance extends JFrame implements ActionListener{
public static Entrance entrance;
public WaitThread storywait=new WaitThread();
JButton abc=new JButton("abcde");
public static void main(String args[]){
entrance=new Entrance();
entrance.setBounds(0,0,1024,768);
entrance.setLayout(null);
entrance.drawsomething();
entrance.waiting();
entrance.setVisible(true);
}
public void drawsomething(){
abc.setBounds(0,0,100,30);
this.add(abc);
}
public void waiting(){
storywait.start();
//if (false)//这里如果让它wait,那么整个项目就卡死
while (storywait.wakeup==false) {
synchronized (storywait){
try {
entrance.revalidate();
storywait.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("success");
}
@Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource()==abc){
synchronized (storywait){
storywait.wakeup();
}
}
}
}
class WaitThread extends Thread{
public boolean wakeup=false;
public void wakeup(){
wakeup=true;
synchronized(this) {
notify();
}
}
public void run(){
}
}
//package swingproblem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class Entrance extends JFrame implements ActionListener{
public static Entrance entrance;
public WaitThread storywait=new WaitThread();
JButton abc=new JButton("abcde");
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable(){//创建窗口的代码最好是单独放到一个线程中.
@Override
public void run(){
entrance=new Entrance();
entrance.setBounds(0,0,1024,768);
entrance.setLayout(null);
entrance.drawsomething();
entrance.setDefaultCloseOperation(EXIT_ON_CLOSE);
entrance.setVisible(true);
}
});
try{
Thread.sleep(1000);//这里休眠为了确保上面窗口线程已经执行.
}catch(InterruptedException e){
e.printStackTrace();
}
entrance.waiting();
}
public void drawsomething(){
abc.setBounds(0,0,100,30);
this.add(abc);
abc.addActionListener(this);//按钮需要添加监听器.否则点按钮也无效.
}
public void waiting(){
while (storywait.wakeup==false) {
synchronized (storywait){
try {
entrance.revalidate();
System.out.println("before");//增加这里为了测试
storywait.wait();
System.out.println("after");//增加这里为了测试
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("success");
}
@Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource()==abc){
synchronized (storywait){
storywait.wakeup();
}
}
}
}
class WaitThread{//这里没必要继承线程.因为本身只是作为一个同步的对象而已.
public boolean wakeup=false;
public void wakeup(){
wakeup=true;
synchronized(this) {
notify();//这里最好用notifyAll().虽然本题用notify也可以.
}
}
}