jframe如何实现多线程
我正在使用这段代码来实现多线程:
class Progress extends JFrame implements Runnable {
Thread t;
JProgressBar current;
JTextArea out;
JButton find;
Thread runner;
JFrame tframe;
int num = 0;
public Progress() {
t=new Thread(this,"Thread1");
t.start();
}
public void run()
{
tframe=new JFrame("Please wait");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
pane.setLayout(new FlowLayout());
current = new JProgressBar();
//current.setValue(0);
current.setStringPainted(true);
current.setIndeterminate(true);
pane.add(current);
setContentPane(pane);
tframe.add(pane);
tframe.pack();
tframe.setSize(300,100);
tframe.setResizable(false);
tframe.setAlwaysOnTop(true);
tframe.setLocation(300,300);
tframe.setVisible(true);
}
public void stop()
{
tframe.dispose();
}
当我需要启动线程时,我使用
Progress t=new Progress(); .
This 显示帧,并停止我使用 t.stop();但是,我没有获得所需的多线程效果。仅显示框架,不显示无生命的进度条。需要注意的是,作为单线程使用时会显示进度条;
这里必须做什么?请帮忙,提前致谢
I am using this code for implementing multithreading :
class Progress extends JFrame implements Runnable {
Thread t;
JProgressBar current;
JTextArea out;
JButton find;
Thread runner;
JFrame tframe;
int num = 0;
public Progress() {
t=new Thread(this,"Thread1");
t.start();
}
public void run()
{
tframe=new JFrame("Please wait");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
pane.setLayout(new FlowLayout());
current = new JProgressBar();
//current.setValue(0);
current.setStringPainted(true);
current.setIndeterminate(true);
pane.add(current);
setContentPane(pane);
tframe.add(pane);
tframe.pack();
tframe.setSize(300,100);
tframe.setResizable(false);
tframe.setAlwaysOnTop(true);
tframe.setLocation(300,300);
tframe.setVisible(true);
}
public void stop()
{
tframe.dispose();
}
When i need to start the thread, i use
Progress t=new Progress(); .
This displays the frame , and to stop i use t.stop(); However, i am not getting the desired multithreading effect. Only the frame is displayed, not the inanimate progress bar . Note that, progress bar is displayed when used as a single thread;
What must be done here? Please help, Thanks in Advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是完全错误的。 Swing 是单线程的。与 swing 组件的每次交互都必须在单个事件调度线程中完成。仔细阅读本教程。它解释了在使用多线程时必须如何完成工作。另请阅读本关于进度条和进度监视器的教程。
This is completely wrong. Swing is single-threaded. Every interaction with swing components must be done in the single, event dispatch, thread. Read this tutorial carefully. It explains how things must be done when working with multiple threads. Also read this tutorial on progress bars and progress monitors.