Java如何为GUI线程
所以我有一个按钮,打开一个while循环,然后我的整个GUI冻结,直到while循环结束,也就是说,我该如何让GUI每秒钟更新一次Java如何为GUI线程,java,multithreading,swing,event-dispatch-thread,Java,Multithreading,Swing,Event Dispatch Thread,所以我有一个按钮,打开一个while循环,然后我的整个GUI冻结,直到while循环结束,也就是说,我该如何让GUI每秒钟更新一次 JButton Test= new JButton(); Test.setText("Test"); Test.setSize(230, 40); Test.setVisible(true); Test.setLocation(15, 290); Test.addActionListener(new ActionListener() { @
JButton Test= new JButton();
Test.setText("Test");
Test.setSize(230, 40);
Test.setVisible(true);
Test.setLocation(15, 290);
Test.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e){
int x = 0;
while(x<500){
x++
});
JButton Test=newjbutton();
Test.setText(“测试”);
测试设置尺寸(230,40);
Test.setVisible(真);
测试设置位置(15290);
Test.addActionListener(新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
int x=0;
而(x这一点很明显,因为Swing对象不是线程安全的,因此提供了SwingUtilities.invokeLater()
,它允许在稍后的某个时间点执行任务
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
int x = 0;
while(x<500){
x++
}
}
});
javax.swing.SwingUtilities.invokeLater(new Runnable()){
公开募捐{
int x=0;
而(x这一点很明显,因为Swing对象不是线程安全的,因此提供了SwingUtilities.invokeLater()
,它允许在稍后的某个时间点执行任务
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
int x = 0;
while(x<500){
x++
}
}
});
javax.swing.SwingUtilities.invokeLater(new Runnable()){
公开募捐{
int x=0;
而(x使用ExecutorService
类
Test.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ExecutorService es = Executors.newCachedThreadPool();
es.submit(new Runnable() {
@Override
public void run() {
int x = 0;
while (x < 500) {
x++;
}
}
});
}
});
Test.addActionListener(新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
ExecutorService es=Executors.newCachedThreadPool();
es.submit(新的Runnable(){
@凌驾
公开募捐{
int x=0;
而(x<500){
x++;
}
}
});
}
});
使用执行器服务
类
Test.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ExecutorService es = Executors.newCachedThreadPool();
es.submit(new Runnable() {
@Override
public void run() {
int x = 0;
while (x < 500) {
x++;
}
}
});
}
});
Test.addActionListener(新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
ExecutorService es=Executors.newCachedThreadPool();
es.submit(新的Runnable(){
@凌驾
公开募捐{
int x=0;
而(x<500){
x++;
}
}
});
}
});
最重要的想法是,您的GUI冻结是因为您在负责绘制GUI的线程中进行了大量处理;解决方案是将计算或任何可能需要花费时间的处理委托给将在后台执行的线程。最重要的想法是,您的GUI冻结是因为您正在执行h在负责绘制GUI的线程中进行了大量处理;解决方案是将计算或任何可能需要时间的处理委托给将在后台执行的线程。请学习常见的Java命名法(命名约定-例如,EachWordUpperCaseClass
,firstWordLowerCaseMethod()
,firstWordLowerCaseAttribute
,除非它是一个大写常量
)并一致使用。请学习常见的Java命名法(命名约定-例如EachWordUpperCaseClass
,firstWordLowerCaseMethod()
,firstWordLowerCaseAttribute
,除非它是一个大写常量
),并一致地使用它。“…我该如何让我的GUI每秒更新一次?”提问者提供的示例代码非常糟糕,因为在“重载”循环中,它甚至没有尝试更新GUI!要做到“更新GUI”,它应该在EDT上完成,而重载本身应该在EDT上完成。因此,最好的答案是建议使用SwingWworker
。worker同时负责和和关闭EDT代码。“…我如何使GUI每秒更新一次?”提问者提供的示例代码非常糟糕,因为在“重载”循环中,它甚至没有尝试更新GUI!要做到“更新GUI”,它应该在EDT上完成,而重载本身应该在EDT上完成。因此,最好的答案是建议使用SwingW工人
。工人同时考虑和关闭EDT代码。