【发布时间】:2023-04-09 21:36:01
【问题描述】:
好吧,我开发了一个带有JDialog 的等待屏幕,但它只在隔离时才有效。
这是我的代码:
/**
*
* @author krisnamourtscf
*/
public class TelaDeProcessamento extends Thread {
private String titulo;
private String mensagem;
private JDialog dialog;
public TelaDeProcessamento(String titulo, String mensagem) {
this.titulo = titulo;
this.mensagem = mensagem;
dialog = new JDialog(new JFrame(), true);
}
public static TelaDeProcessamento iniciaTela(String titulo, String mensagem) {
TelaDeProcessamento tela = new TelaDeProcessamento(titulo, mensagem);
tela.start();
return tela;
}
@Override
public void run() {
try {
dialog.setTitle(titulo);
dialog.getContentPane().setBackground(Color.WHITE);
dialog.setSize(new Dimension(300, 150));
dialog.getContentPane().setLayout(new BorderLayout());
ImageIcon ii = new ImageIcon(getClass().getResource("/imagens/4.gif"));
JLabel imageLabel = new JLabel();
imageLabel.setLocation(70, 0);
imageLabel.setText(" " + mensagem);
imageLabel.setIcon(ii);
dialog.getContentPane().add(imageLabel, java.awt.BorderLayout.CENTER);
dialog.setLocationRelativeTo(null);
dialog.validate();
dialog.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void paraTela() {
dialog.dispose();
}
public static void main(String[] args) {
TelaDeProcessamento tela=TelaDeProcessamento.iniciaTela("Aguarde....", "isso é um teste");
try {
Thread.sleep(5000);
} catch (Exception ex) {
}
tela.paraTela();
}
}
结果如下:
虽然,当我从另一个类调用它时,GIF 没有出现
从另一个 JDialog 类示例调用
this.setTitle(title);
this.setModal(true);
this.setLocationRelativeTo(null);
TelaDeProcessamento tela = TelaDeProcessamento.iniciaTela("Aguarde", "carregando dados");
this.initiateScreenComponets();
tela.paraTela();
JTableUtil.addEventosSelecaoBusca(this);
this.setVisible(true);
结果:
我做错了什么?
【问题讨论】:
-
我怀疑这是因为您在 AWT 事件调度线程之外执行您的操作。几乎所有的 Swing 和 AWT 方法都必须只在该线程中运行,而不能在其他线程中运行。违反此规则将导致奇怪和不可预测的行为。见docs.oracle.com/javase/tutorial/uiswing/concurrency。
-
感谢@VGR 我用 SwingWorker 解决了问题
标签: java image swing gif event-dispatch-thread