我正在开发加密解密文件的应用程序,我想根据进程的实时时间使用 jProgressBar。
1 回答
要jProgressBar
根据任务花费的时间进行工作,您应该使用SwingWorker在单独的线程中执行任务。
SwingWorker是如何工作的?
SwingWorker
专为需要在后台线程中运行长时间运行的任务并在完成时或在处理时向 UI 提供更新的情况而设计。的子类SwingWorker
必须实现doInBackground()
执行后台计算的方法。工作流程
SwingWorker 的生命周期涉及三个线程:
当前线程:在该线程上调用了 execute() 方法。它安排
SwingWorker
在工作线程上执行并立即返回。SwingWorker
可以使用 get 方法 等待完成。工作线程:
doInBackground()
在该线程上调用该方法。这是所有后台活动都应该发生的地方。要通知PropertyChangeListeners
绑定属性的更改,请使用firePropertyChange
和getPropertyChangeSupport()
方法。默认情况下,有两个可用的绑定属性:状态和进度。事件调度线程:所有与 Swing 相关的活动都发生在该线程上。SwingWorker 调用 process 和 done() 方法并通知此线程上的任何 PropertyChangeListener。
通常,当前线程是事件调度线程。
因此,要开发一个加密和解密文件的应用程序,您可以使用 SwingWorker 来执行加密/解密和 jProgressBar 根据进程所花费的实时时间。
样本输出:
代码:
public class Test extends JPanel implements ActionListener,
PropertyChangeListener {
private JProgressBar progressBar;
private JButton startButton;
private JTextArea encryptedOutput;
private JTextArea decryptedOutput;
private Task task;
Key aesKey;
Cipher cipher;
String key = "Code1234Code1234"; // 128 bit key
class Task extends SwingWorker<Void, Void> {
@Override
public Void doInBackground() {
int progress = 0;
// Initialize progress property.
setProgress(0);
try {
JFileChooser fileopen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("txt files",
"txt");
fileopen.addChoosableFileFilter(filter);
File file = null;
String fileName = "";
int ret = fileopen.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
file = fileopen.getSelectedFile();
fileName = file.getName();
encryptedOutput.setText(String.format(
"Encrypted Output : %s\t\n\n", fileName));
decryptedOutput.setText(String.format(
"Decrypted Output : %s\t\n\n", fileName));
BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
long readLength = 0;
long totalLength = file.length();
double lengthPerPercent = 100.0 / totalLength;
// added dummy delay because encryption takes very less time
// in MVCE
Thread.sleep(1000);
while (line != null) {
try {
Thread.sleep(100);
// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(line.getBytes());
encryptedOutput.append(String.format("%s\n",
new String(encrypted)));
// decrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(
cipher.doFinal(encrypted));
decryptedOutput.append(String.format("%s\n",
decrypted));
// calculate progress.
readLength += line.length();
progress = (int) (lengthPerPercent * readLength);
setProgress(Math.min(progress, 100));
line = in.readLine();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/*
* Executed in event dispatching thread
*/
@Override
public void done() {
setProgress(100);
Toolkit.getDefaultToolkit().beep();
startButton.setEnabled(true);
// turn off the wait cursor
setCursor(null);
}
}
public Test() {
super(new BorderLayout());
// Create key and cipher
aesKey = new SecretKeySpec(key.getBytes(), "AES");
try {
cipher = Cipher.getInstance("AES");
} catch (Exception e) {
e.printStackTrace();
}
progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
encryptedOutput = new JTextArea(20, 50);
encryptedOutput.setMargin(new Insets(5, 5, 5, 5));
encryptedOutput.setEditable(false);
encryptedOutput.setLineWrap(true);
decryptedOutput = new JTextArea(20, 50);
decryptedOutput.setMargin(new Insets(5, 5, 5, 5));
decryptedOutput.setEditable(false);
decryptedOutput.setLineWrap(true);
startButton = new JButton("Start Encoding");
startButton.setActionCommand("start");
startButton.addActionListener(this);
JPanel panel = new JPanel();
add(panel, BorderLayout.PAGE_START);
panel.add(progressBar, BorderLayout.LINE_START);
add(new JScrollPane(encryptedOutput), BorderLayout.LINE_START);
add(new JScrollPane(decryptedOutput), BorderLayout.LINE_END);
panel.add(startButton, BorderLayout.PAGE_END);
setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50));
}
public void actionPerformed(ActionEvent evt) {
startButton.setEnabled(false);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
task = new Task();
task.addPropertyChangeListener(this);
task.execute();
}
/**
* Invoked when task's progress property changes.
*/
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("progress")) {
int progress = (Integer) evt.getNewValue();
progressBar.setValue(progress);
encryptedOutput.append("\n\n");
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new Test();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}