Java Swingworker冻结对话框,不更新
我希望我在这里问的是正确的问题,但请随时向我询问任何其他信息。 我正试图用Java编写一个程序来处理文本区域中的一段代码。 该程序完全符合我的预期,但可能需要一些时间,因此我想在将要更新的对话框上放置一个JProgressBar。 我已经查看了进度条上的oracle示例,并尝试执行类似于中示例的操作 这使用了一个足够简单的例子,其中Java Swingworker冻结对话框,不更新,java,multithreading,dialog,swingworker,Java,Multithreading,Dialog,Swingworker,我希望我在这里问的是正确的问题,但请随时向我询问任何其他信息。 我正试图用Java编写一个程序来处理文本区域中的一段代码。 该程序完全符合我的预期,但可能需要一些时间,因此我想在将要更新的对话框上放置一个JProgressBar。 我已经查看了进度条上的oracle示例,并尝试执行类似于中示例的操作 这使用了一个足够简单的例子,其中 整个JFrame类有一个扩展的Task子类 Swingworker。Swingworker类(任务)在 使用doinBackground()方法设置背景 使用se
- 整个JFrame类有一个扩展的Task子类
Swingworker。Swingworker类(任务)在
使用
方法设置背景李>doinBackground()
- 使用
方法更新进度setProgress()
- 主JFrame任务实现
propertychangelistener
ProgressBarDemo
调用Task
时,它将自己的propertychangelistener
与Task关联,当Task
调用setprogress()
时,数据更改将广播到ProgressBarDemo
spropertyChange(evt)
方法
这是一个很好的例子
public class ProgressBarDemo extends JPanel
implements ActionListener,
PropertyChangeListener {
private JProgressBar progressBar;
private JButton startButton;
private JTextArea taskOutput;
private Task task;
class Task extends SwingWorker<Void, Void> {
/*
* Main task. Executed in background thread.
*/
@Override
public Void doInBackground() {
Random random = new Random();
int progress = 0;
//Initialize progress property.
setProgress(0);
while (progress < 100) {
//Sleep for up to one second.
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException ignore) {
}
//Make random progress.
progress += random.nextInt(10);
setProgress(Math.min(progress, 100));
}
return null;
}
/*
* Executed in event dispatching thread
*/
@Override
public void done() {
Toolkit.getDefaultToolkit().beep();
startButton.setEnabled(true);
setCursor(null); //turn off the wait cursor
taskOutput.append("Done!\n");
}
}
public ProgressBarDemo() {
super(new BorderLayout());
//Create the demo's UI.
startButton = new JButton("Start");
startButton.setActionCommand("start");
startButton.addActionListener(this);
progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
taskOutput = new JTextArea(5, 20);
taskOutput.setMargin(new Insets(5, 5, 5, 5));
taskOutput.setEditable(false);
JPanel panel = new JPanel();
panel.add(startButton);
panel.add(progressBar);
add(panel, BorderLayout.PAGE_START);
add(new JScrollPane(taskOutput), BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
/**
* Invoked when the user presses the start button.
*/
public void actionPerformed(ActionEvent evt) {
startButton.setEnabled(false);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
//Instances of javax.swing.SwingWorker are not reusuable, so
//we create new instances as needed.
task = new Task();
task.addPropertyChangeListener(this);
task.execute();
}
/**
* Invoked when task's progress property changes.
*/
public void propertyChange(PropertyChangeEvent evt) {
if ("progress" == evt.getPropertyName()) {
int progress = (Integer) evt.getNewValue();
progressBar.setValue(progress);
taskOutput.append(String.format(
"Completed %d%% of task.\n", task.getProgress()));
}
}
/**
* Create the GUI and show it. As with all GUI code, this must run on the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ProgressBarDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new ProgressBarDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
公共类ProgressBarDemo扩展了JPanel
实现ActionListener,
PropertyChangeListener{
私人JProgressBar progressBar;
私有JButton开始按钮;
专用JTextArea任务输出;
私人任务;
类任务扩展SwingWorker{
/*
*主任务。在后台线程中执行。
*/
@凌驾
公共无效doInBackground(){
随机=新随机();
int progress=0;
//初始化进度属性。
setProgress(0);
而(进度<100){
//最多睡一秒钟。
试一试{
Thread.sleep(random.nextInt(1000));
}捕获(中断异常忽略){
}
//随机取得进展。
进度+=随机。下一步(10);
setProgress(Math.min(progress,100));
}
返回null;
}
/*
*在事件调度线程中执行
*/
@凌驾
公众假期结束(){
getDefaultToolkit().beep();
startButton.setEnabled(真);
setCursor(null);//关闭等待光标
taskOutput.append(“完成!\n”);
}
}
公共进步组织(){
超级(新边框布局());
//创建演示的UI。
startButton=新的JButton(“开始”);
setActionCommand(“开始”);
addActionListener(这个);
progressBar=新的JProgressBar(01100);
progressBar.setValue(0);
progressBar.SetStringPaint(真);
taskOutput=新的JTextArea(5,20);
setMargin(新的插图(5,5,5,5));
taskOutput.setEditable(false);
JPanel面板=新的JPanel();
面板。添加(开始按钮);
面板。添加(进度条);
添加(面板、边框布局、页面开始);
添加(新的JScrollPane(taskOutput),BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyByOrder(20,20,20,20));
}
/**
*当用户按下开始按钮时调用。
*/
已执行的公共无效操作(操作事件evt){
startButton.setEnabled(错误);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_Cursor));
//javax.swing.SwingWorker的实例不可重用,因此
//我们根据需要创建新实例。
任务=新任务();
task.addPropertyChangeListener(此);
task.execute();
}
/**
*当任务的进度属性更改时调用。
*/
公共作废属性更改(属性更改事件evt){
if(“progress”==evt.getPropertyName()){
int progress=(整数)evt.getNewValue();
progressBar.setValue(进度);
taskOutput.append(String.format(
“已完成%d%%个任务。\n”,task.getProgress());
}
}
/**
*创建GUI并显示它。与所有GUI代码一样,它必须在
*事件调度线程。
*/
私有静态void createAndShowGUI(){
//创建并设置窗口。
JFrame=新JFrame(“ProgressBarDemo”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//创建并设置内容窗格。
JComponent newContentPane=newProgressBarDemo();
newContentPane.setOkable(true);//内容窗格必须是不透明的
frame.setContentPane(newContentPane);
//显示窗口。
frame.pack();
frame.setVisible(true);
}
公共静态void main(字符串[]args){
//为事件调度线程计划作业:
//创建并显示此应用程序的GUI。
javax.swing.SwingUtilities.invokeLater(新的Runnable(){
公开募捐{
createAndShowGUI();
}
});
}
}
从示例中可以看出,没有revalidate()invalidate()repaint()等实例,一切都正常运行,但是,我已尝试重新创建此方法进行更改,图形不会更新
我还在控制台上打印,这个输出完全符合预期,但无论我做什么,我都无法更新JProgressBar。
如果我包括一个按钮来增加JProgressbar,它将工作,JProgressbar将更新,但是在运行SwingWorker之后,JProgressbar不再以图形方式响应,即使我包括了revalidate()等
我还包括在方法中,在JProgressbar中的值的前后chjeck,它包含正确的值,每次。。。它只是不会更新对话框
任何帮助。。。
请
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package db_udt_searchandreplacetest;
import Model.VariableListProcessor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
*
* @author Alan Curley
*/
public class Dialog1 extends javax.swing.JFrame
implements ActionListener,
PropertyChangeListener {
/**
* Creates new form Dialog1
*/
public Dialog1() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jSeparator1 = new javax.swing.JSeparator();
jScrollPane1 = new javax.swing.JScrollPane();
SourceCode = new javax.swing.JTextArea();
goButton = new javax.swing.JButton();
jProgressBar1 = new javax.swing.JProgressBar();
updateTheFlippingProgressBar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
SourceCode.setColumns(20);
SourceCode.setFont(new java.awt.Font("Corbel", 0, 13)); // NOI18N
SourceCode.setRows(5);
SourceCode.setText("Paste Source code here.");
jScrollPane1.setViewportView(SourceCode);
goButton.setText("GO");
goButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
goButtonActionPerformed(evt);
}
});
jProgressBar1.setStringPainted(true);
updateTheFlippingProgressBar.setText("UTFPB");
updateTheFlippingProgressBar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
updateTheFlippingProgressBarActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(goButton)
.addGap(18, 18, 18)
.addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(updateTheFlippingProgressBar)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(goButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(updateTheFlippingProgressBar)
.addGap(5, 5, 5))
);
pack();
}// </editor-fold>
/**
* This is the function called when the user presses the "GO" Button.
* @param evt
*/
private void goButtonActionPerformed(java.awt.event.ActionEvent evt) {
// Update the Progressbar to include a new Maximum count.
jProgressBar1.setMaximum(SourceCode.getLineCount());
VariableListProcessor VPL = new VariableListProcessor(SourceCode);
VPL.addPropertyChangeListener(this); // Sdet this class (Dialog1) as the propertychange listener.
//java.awt.EventQueue.invokeLater(VPL);
VPL.execute();
System.out.println("GO Pressed: "+String.valueOf(jProgressBar1.getValue()));
}
private void updateTheFlippingProgressBarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jProgressBar1.setValue(jProgressBar1.getValue()+1);
if(jProgressBar1.getValue()>99)
jProgressBar1.setValue(0);
this.validate();
this.repaint();
System.out.println("UTFPB Pressed: "+String.valueOf(jProgressBar1.getValue()));
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Dialog1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Dialog1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Dialog1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Dialog1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Dialog1().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextArea SourceCode;
private javax.swing.JButton goButton;
private javax.swing.JProgressBar jProgressBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JButton updateTheFlippingProgressBar;
// End of variables declaration
// called when an action is triggered.
@Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("<<<< actionPerformed(): Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
// called when a property change being listened for is detected.
@Override
public void propertyChange(PropertyChangeEvent evt) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
if ("progress" == evt.getPropertyName()) {
int progress = (Integer) evt.getNewValue();
jProgressBar1.setValue(progress);
System.out.println("P:"+String.valueOf(jProgressBar1.getValue()));
jProgressBar1.repaint();
}
}
}
/*
*要更改此模板,请选择工具|模板
*然后在编辑器中打开模板。
*/
包db_udt_搜索和替换测试;
导入Model.VariableListProcessor;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.beans.PropertyChangeEvent;
导入java.beans.PropertyChangeListener;
/**
*
*@作者艾伦·科利
*/
公共类Dialog1扩展了javax.swing.J
package Model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.*;
/**
* This is the swingworker class that will take the string object that contains
* the source code and builds the VariableList object from the Data.
* @author Alan Curley
*/
public class VariableListProcessor extends SwingWorker<Void,Integer> {
JTextArea source;
Integer i = 0;
public VariableListProcessor(JTextArea source){
this.source = source;
i = 0;
}
public void setSource(JTextArea source){
this.source = source;
}
// This is the method that will be called in the background to allow the thread to run.
// We can update the progress property of the class to report back how it is working.
// Called when the "Execute" command is given???
@Override
protected Void doInBackground() throws InterruptedException{
// it is here we set up the Loop to go through Source, line by line and translate the variables into something
// more meaningful.
// Clear the progress settings.
Integer percProgress;
i = 0;
//setProgress(0);
// build an Arraylist of Strings that represent each line in the source code.
ArrayList<String> sourceCodeList;
sourceCodeList = new ArrayList();
sourceCodeList.addAll(Arrays.asList(source.getText().split("\\n")));
for (String S:sourceCodeList){
if(S.matches("TYPE\\W*UDT\\W+\\d+.*"))
System.out.println(S);
percProgress = ((++i)*100/source.getLineCount());
publish(percProgress);
/*if(!(oldPercProgress.equals(percProgress)))
{
try{ ///
Thread.sleep(100);
/*
}catch(InterruptedException ignore){}
oldPercProgress = percProgress;
} */
// if(i.equals(269))
// System.out.println(String.valueOf(i)+"\t"+S);
}
return null;
//throw new UnsupportedOperationException("<<<< VPL-doInBackground(): Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
protected void done(){
System.out.println("Complete. :-)");
JOptionPane.showMessageDialog(null, "Complete", "Complete", JOptionPane.INFORMATION_MESSAGE);
//throw new UnsupportedOperationException("<<<< VPL-done(): Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
// Can safely update the GUI from this method.
protected void process(List<Integer> chunks) {
// Here we receive the values that we publish().
// They may come grouped in chunks.
int mostRecentValue = chunks.get(chunks.size()-1);
setProgress(mostRecentValue);
}
}