我有一个SwingWorker
类,它加载文本文件并将其切片以进行进一步处理。
以下是SwingWorker
类:
public class ConverterWorker extends SwingWorker<String, String>
{
private final File f;
private final JLabel label;
public ConverterWorker(File f, JLabel label)
{
this.f = f;
this.label = label;
}
@Override
protected String doInBackground() throws Exception
{
NMTMain.convertableData = getDataSets(f);
if(!NMTMain.convertableData.isEmpty())
{
return "Done";
}
else
{
publish("Failed to load the file!");
return "Failed";
}
}
@Override
public void done()
{
try
{
label.setText(get());
}
catch (Exception e)
{
e.printStackTrace(System.err);
System.out.println("error");
}
}
@Override
protected void process(List<String> chunks)
{
label.setText(chunks.get(chunks.size() - 1));
}
public ArrayList<ArrayList<Convertable>> getDataSets(File f)
{
ArrayList<ArrayList<Convertable>> dataSets = new ArrayList<ArrayList<Convertable>>();
publish("Loading file...");
setProgress(0);
String[] data = loadFile(f);
for(int i = 0; i< NMTMain.nodes.size(); i++)
{
dataSets.add(splitByNode(data, NMTMain.nodes.get(i).getName()));
}
setProgress(100);
return dataSets;
}
private ArrayList<Convertable> splitByNode(String[] data, String name)
{
ArrayList<Convertable> temp = new ArrayList<Convertable>();
for(int i = 0; i < data.length; i++)
{
if(data[i].contains(name))
{
temp.add(new Convertable(data[i]));
}
}
Collections.sort(temp);
return temp;
}
private String[] loadFile(File f)
{
String data = "";
String[] nodes;
long fileLength = f.length();
int bytesRead = -1;
int totalBytesRead = 0;
try
{
if(f.exists())
{
Scanner scan = new Scanner(f);
while(scan.hasNextLine())
{
String line = scan.nextLine();
data = data + line + "\n";
bytesRead = line.getBytes().length;
totalBytesRead += bytesRead;
int progress = (int) Math.round(((double) totalBytesRead / (double) fileLength) * 100d);
/* try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//publish("loading... " + String.valueOf(progress));
setProgress(progress);
}
scan.close();
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
nodes = data.split("\n\"\n");
return nodes;
}
当取消注释Thread.sleep(1);
时,它可以很好地工作。但是,当我注释掉Thread.sleep(1);
时,该类不会更新进度条。
我通过一个按钮调用我的类,这里是ActionListener
:
loadInput.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
int returnval=NMTMain.fileChooser.showOpenDialog(NMTMain.MainFrame);
if(returnval == 0)
{
File f=NMTMain.fileChooser.getSelectedFile();
final ConverterWorker worker = new ConverterWorker(f, dialogPanel.getLabel());
worker.addPropertyChangeListener(new PropertyChangeListener()
{
@Override
public void propertyChange(final PropertyChangeEvent evt)
{
if("progress".equalsIgnoreCase(evt.getPropertyName()))
{
dialogPanel.showProgressDialog("Conversion");
dialogPanel.setProgressBarValue((int) evt.getNewValue());
}
if(worker.isDone())
{
dialogPanel.showConfirmDialog("Conversion", "OK");
}
}
});
worker.execute();
}
}
});
没有sleep也应该正常工作,那么我在这里做错了什么?
更新:
事实证明我的DialogPanel
不是最好的,会导致这种行为。
这是DialogPanel
类:
public class DialogPanel extends JDialog
{
private JLabel label;
private JPanel panel;
private JButton button;
private JProgressBar progressBar;
public DialogPanel()
{
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5,10,5,10);
panel = new JPanel();
panel.setLayout(new GridBagLayout());
progressBar = new JProgressBar(0,100);
progressBar.setVisible(false);
progressBar.setStringPainted(true);
setLabel(new JLabel("def text", SwingConstants.CENTER));
button = new JButton("OK");
button.setVisible(false);
button.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
// TODO Auto-generated method stub
dispose();
}
});
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(getLabel(), gbc);
gbc.gridy = 1;
panel.add(progressBar, gbc);
panel.add(button, gbc);
this.setContentPane(panel);
this.setLocationRelativeTo(null);
this.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
this.setResizable(false);
}
public void setProgressBarValue(int value)
{
progressBar.setValue(value);
}
public void setProgressBarVisibility(boolean value)
{
progressBar.setVisible(value);
}
public void setText(String text)
{
getLabel().setText(text);
}
public void showProgressDialog(String title)
{
progressBar.setVisible(true);
button.setVisible(false);
this.setTitle(title);
this.pack();
if(!this.isVisible())
{
this.setVisible(true);
}
}
public void showConfirmDialog(String title, String buttontext)
{
progressBar.setVisible(false);
button.setVisible(true);
this.setTitle(title);
button.setText(buttontext);
this.pack();
if(!this.isVisible())
{
this.setVisible(true);
}
}
public JLabel getLabel()
{
return label;
}
public void setLabel(JLabel label)
{
this.label = label;
}
public JProgressBar getProgressBar()
{
return progressBar;
}
@Override
public Dimension getPreferredSize()
{
return new Dimension(200, 100);
}
}
对于专业人士来说,这可能是一团糟的。我如何在对话框中显示进度条,并在进程完成时有一个确认按钮以处理对话框?
解决方案:
我已经从我的DialogPanel
类改为ProgressMonitor,现在一切都很好。
感谢您的时间和建议。