我正在使用swing计时器在swing应用程序中加载不同的pdf文件 但是我遇到一个问题,当我执行一个程序屏幕保持空白几秒钟,如4到5秒然后pdf文件被渲染,所以在这段时间我想显示一条消息,请等待。这是我的示例代码
if (type[i].equalsIgnoreCase("PDF")) {
int k = i;
pdfTimer = new Timer(0, (ActionEvent e) -> {
renderPDF(k);
});
pdfTimer.setDelay(1000*2);
pdfTimer.start();
答案 0 :(得分:2)
在SwingWorker's后台线程(doInBackground
)方法上运行渲染。这样,您的GUI将保持响应。从done
方法,您可以通知用户渲染已完成。请注意,不要从GUI
方法更新任何Swing doInBackground
,因为它在EDT之外运行。
P.S。 Swing Timer用于重复性任务。
答案 1 :(得分:0)
您可以显示进度条并在第二个线程上计算渲染。
JLabel lblWait = new JLabel("Please wait...");
lblWait .setBounds(116, 26, 113, 14);
contentPanel.add(lblWait );
final JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
progressBar.setBounds(72, 66, 187, 16);
contentPanel.add(progressBar);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
final JButton btFin = new JButton("Cancel");
btFin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
buttonPane.add(btFin);
}
}
Thread t = new Thread() {
public void run() {
//You launch the thread with your progress bar as an argument
maStructure.setaAfficher(new MgtSimulation(aAfficher, nombreSimulations).jouerSimulations(progressBar));
maStructure.actualiserAffichage();
dispose();
}
};
t.start();
}
您可以在方法中更改进度条值
public BeanAffichage jouerSimulations(JProgressBar progressBar){
//Variables
for (int i = 0; i < nombreSimulations; i++) {
//Computing
progressBar.setValue(Whatever you want);
}
return aAfficher;
}
答案 2 :(得分:0)
只是 SwingWorker
默认显示一些消息,例如正在加载... 并创建一个Thread
以在后台运行,加载PDF并更新窗口
class BackgroundThread implements Runnable {
@Override
public void run() {
// the Swing call below must be queued onto the Swing event thread
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
// OK To make Swing method calls here
loadFile(args..);
repaint();//Or something similar that fits your purpose
}
});
}
}