JPanel 未在 JFrame 中加载

发布于 2025-01-03 10:10:54 字数 3238 浏览 0 评论 0原文

在 Java 中读取文件时显示进度条时出现问题。 一切都按预期进行,用户选择一个文件,程序必须显示进度条(但它加载一个空的空白框),处理文件,然后将结果加载到另一个窗口上。

我无法让程序显示进度条对话框的内容。
如果您能在这里提供一些帮助,我们将不胜感激。

这是所涉及的3个方法的代码。

//this method reads the file
public void processFile(File arch) {       
  aFile = arch;
  Thread threadForSearch = new Thread() {
  @Override
  public void run() {
      try{
         listaProveedoresTango = controladoraConsultas.traerProveedores();  
         listaProveedoresAFIP = new LinkedList();
     BufferedReader data = new BufferedReader(new FileReader(aFile));
     String s;
      while ((s = data.readLine()) != null) {                  
     //long task                 
      }
      data.close();
    }catch (Exception e){
      System.err.println("Error: " + e.getMessage());
    }
      }
    };

    interfacesController.loadProgressBar();

    threadForSearch.start();         

   try {
      threadForSearch.join();
   } catch (InterruptedException ex) {
      Logger.getLogger(Controladora.class.getName()).log(Level.SEVERE, null, ex);
   }
   this.interfacesController.closeProgressBar();
   this.interfacesController.loadResults(someStuff);       
}

//load a progress bar
public void loadProgressBar(){           
  JProgressBar pb = new JProgressBar(0,100);
  pb.setPreferredSize(new Dimension(175,20));
  pb.setString("Processing Data");
  pb.setStringPainted(true);
  pb.setIndeterminate(true);
  JLabel infoLabel = new JLabel("Reading File: ");
  JButton cancelButton = new JButton("Cancel");
  cancelButton.addActionListener(new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent evt) {
      exitSystem();
    }
  });
  cancelButton.setVerticalAlignment(SwingConstants.CENTER);
  JPanel center_panel = new JPanel();
  center_panel.add(infoLabel);
  center_panel.add(pb);
  center_panel.add(cancelButton);
  center_panel.setLayout(new BoxLayout(center_panel,BoxLayout.Y_AXIS));
  dialog = new JDialog((JFrame)null, "Processing ...");
  dialog.getContentPane().add(center_panel, BorderLayout.CENTER);
  dialog.setSize(100, 100);
  dialog.setLocationRelativeTo(null);
  dialog.pack();
  dialog.setVisible(true);          
}

//close the open progress bar
public void closeProgressBar(){
   this.dialog.dispose();
}

使用 SwingWorker 解决了这个问题,我发布了一个汇总代码:

public void processFile(File arch) {

    aFile = arch;

    final SwingWorker searchOnFile = new SwingWorker(){  

      @Override  
      protected Object doInBackground() throws Exception {  
        try{
            BufferedReader data = new BufferedReader(new FileReader(aFile));
            String s;
            while ((s = data.readLine()) != null) {                  
                //long task                  
             }
             data.close();
        }catch (Exception e){ //Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
     interfacesController.closeProgressBar();
     interfacesController.loadResults(someStuff); 
     return null;
     }
   };  

   interfacesController.showProgressBar(); 

   searchOnFile.execute();

}

interfacesController 包含使用 GUI 的所有方法,showProgressBar() 用于显示栏,而 closeProgressBar() 则执行相反的操作。谢谢你们!

I have a problem showing my progress bar when reading a file in Java.
All works as intended, user choose a file, the program must show the progress bar (but it loads an empty blank frame), process the file and then load the results on another window.

I can't get the program to show the content of the progress bar dialog.
A little help here would be really appreciated.

Here is the code of the 3 methods involved.

//this method reads the file
public void processFile(File arch) {       
  aFile = arch;
  Thread threadForSearch = new Thread() {
  @Override
  public void run() {
      try{
         listaProveedoresTango = controladoraConsultas.traerProveedores();  
         listaProveedoresAFIP = new LinkedList();
     BufferedReader data = new BufferedReader(new FileReader(aFile));
     String s;
      while ((s = data.readLine()) != null) {                  
     //long task                 
      }
      data.close();
    }catch (Exception e){
      System.err.println("Error: " + e.getMessage());
    }
      }
    };

    interfacesController.loadProgressBar();

    threadForSearch.start();         

   try {
      threadForSearch.join();
   } catch (InterruptedException ex) {
      Logger.getLogger(Controladora.class.getName()).log(Level.SEVERE, null, ex);
   }
   this.interfacesController.closeProgressBar();
   this.interfacesController.loadResults(someStuff);       
}

//load a progress bar
public void loadProgressBar(){           
  JProgressBar pb = new JProgressBar(0,100);
  pb.setPreferredSize(new Dimension(175,20));
  pb.setString("Processing Data");
  pb.setStringPainted(true);
  pb.setIndeterminate(true);
  JLabel infoLabel = new JLabel("Reading File: ");
  JButton cancelButton = new JButton("Cancel");
  cancelButton.addActionListener(new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent evt) {
      exitSystem();
    }
  });
  cancelButton.setVerticalAlignment(SwingConstants.CENTER);
  JPanel center_panel = new JPanel();
  center_panel.add(infoLabel);
  center_panel.add(pb);
  center_panel.add(cancelButton);
  center_panel.setLayout(new BoxLayout(center_panel,BoxLayout.Y_AXIS));
  dialog = new JDialog((JFrame)null, "Processing ...");
  dialog.getContentPane().add(center_panel, BorderLayout.CENTER);
  dialog.setSize(100, 100);
  dialog.setLocationRelativeTo(null);
  dialog.pack();
  dialog.setVisible(true);          
}

//close the open progress bar
public void closeProgressBar(){
   this.dialog.dispose();
}

Solved with SwingWorker, i post a summarized code:

public void processFile(File arch) {

    aFile = arch;

    final SwingWorker searchOnFile = new SwingWorker(){  

      @Override  
      protected Object doInBackground() throws Exception {  
        try{
            BufferedReader data = new BufferedReader(new FileReader(aFile));
            String s;
            while ((s = data.readLine()) != null) {                  
                //long task                  
             }
             data.close();
        }catch (Exception e){ //Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
     interfacesController.closeProgressBar();
     interfacesController.loadResults(someStuff); 
     return null;
     }
   };  

   interfacesController.showProgressBar(); 

   searchOnFile.execute();

}

interfacesController contains all the methods to work with GUIs, showProgressBar() is used to show the bar and closeProgressBar() do the opposite. Thank you guys!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

入怼 2025-01-10 10:10:54

缺少更有用的代码,我建议使用 SwingWorker

一个抽象类,用于在后台线程中执行冗长的 GUI 交互任务。可以使用多个后台线程来执行此类任务。 ..

鉴于任务的性质,您还可以查看 ProgressMonitorInputStream

..创建一个进度监视器来监视读取输入流的进度。如果需要一段时间,将会弹出一个 ProgressDialog 来通知用户。如果用户点击取消按钮,下次读取时将抛出 InterruptedIOException。当流关闭时,所有正确的清理工作都会完成。

Short of more useful code, I suggest using a SwingWorker.

An abstract class to perform lengthy GUI-interaction tasks in a background thread. Several background threads can be used to execute such tasks. ..

Given the nature of the task, you might also look at ProgressMonitorInputStream.

..creates a progress monitor to monitor the progress of reading the input stream. If it's taking a while, a ProgressDialog will be popped up to inform the user. If the user hits the Cancel button an InterruptedIOException will be thrown on the next read. All the right cleanup is done when the stream is closed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文