Swing Progressbar benutzen um Fortschritt einer Methode anzuzeigen

1er1

Mitglied
Hey,
ich bin leider noch blutger neuling in Java. Vor alem was die Oberfläche angeht :/

Ich habe hier ein Programm, das alle Dateien in einem Ordner auswählen soll die vom Typ grp oder lst sind und diese bearbeitet.
Wie gesagt ich kenne mich leider nicht besonders mit der Oberfläche aus, aber ich hätte gerne das die JProgressbar läuft während die Dateien bearbeitet werden und endet wenn die letzte Datei bearbeitet wurde.
Code:
public class GUI
{
  
    private  JButton button1;
    private JButton button2;
    private JButton button3;
    private static int l;
    private JProgressBar progressBar;
    private JPanel panel1;
    static JProgressBar pb;
    private JFrame frame1;
    static String X;

    
    public GUI()
    {
        frame1 = new JFrame();
        frame1.setTitle("Eins Elf Einself");
        panel1 = new JPanel();
        panel1.setLayout(null);
        frame1.add(panel1);

        button1 = new JButton("1");
        button1.setFont(new Font("Arial",Font.BOLD,14));
        button1.setBackground(Color.WHITE);
        button1.setBounds(10,10,100,25);
        button1.addActionListener(new ButtonLauscher());
        panel1.add(button1);
        button1.setVisible(true);

        button2 = new JButton("11");
        button2.setFont(new Font("Arial",Font.BOLD,14));
        button2.setBackground(Color.WHITE);
        button2.setBounds(10,70,100,25);
        button2.addActionListener(new ButtonLauscher());
        panel1.add(button2);
        button2.setVisible(true);

        button3 = new JButton("1&11");
        button3.setFont(new Font("Arial",Font.BOLD,14));
        button3.setBackground(Color.WHITE);
        button3.setBounds(10,130,100,25);
        button3.addActionListener(new ButtonLauscher());
        panel1.add(button3);
        pb = new JProgressBar();
        pb.setBounds(150, 50, 250, 50);
        pb.setValue(0);
        pb.setStringPainted(true);
        panel1.add(pb);
        frame1.setSize(500,200);

        frame1.setResizable(false);
        frame1.setLocationRelativeTo(null);
        frame1.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        frame1.setVisible(true);

    }

    public static void update1(String Dateipfad) throws IOException
    {
        File dir = new File(Dateipfad);
        File [] s= dir.listFiles();
        pb.setMaximum(s.length);

        for (int i5 = 0; i5<s.length; i5++)
        {
            pb.setValue( i5 );  //
            try
            {Thread.sleep(50);}
            catch(Exception e)
            {}

            if (s[i5].getPath().contains(".lst") || s[i5].getPath().contains(".grp") ||  s[i5].getPath().contains(".GRP" )|| s[i5].getPath().contains(".LST" ))
            {
                FileReader f = new FileReader(s[i5].getPath());
                BufferedReader b = new BufferedReader(f);
                int n = 0;
                String zeilen = b.readLine();
                while(zeilen != null)
                {
                    n++;
                    zeilen = b.readLine();
                }

                f.close();
                String[] s4 = new String[n];
                String [] inhalte1 = new String[n];
                f = new FileReader(s[i5].getPath());
                b = new BufferedReader(f);

                for(int i = 0; i<n; i++)
                {
                    inhalte1[i] = b.readLine();

                }
                for(int i = 0; i<n; i++)
                {
                    String[]s3 = inhalte1[i].split("(?<=\\|)", 30);
                    if (s3.length == 30)
                    {
                        for(int i1 = 0; i1<s3.length; i1++)
                        {
                            if(s4[i] == null)
                            {s4[i] = "";}
                            if(s3[25].equals("1|"))
                            {s3[25] = "0|";
                            }
                            s4[i] = s4[i] + s3[i1];
                        }
                    }

                    else
                    {
                        for(int i1 = 0; i1<s3.length; i1++)
                        {
                            if(s4[i] == null)
                            {s4[i] = "";}
                            s4[i] = s4[i] + s3[i1];
                        }
                    }
                    String separator = System.getProperty( "line.separator" );
                    s4[i] = s4[i] + separator;

                }     
                try
                {

                    BufferedWriter writer = new BufferedWriter(new FileWriter(s[i5].getPath()));
                    writer.write("");
                    for(int i = 0; i<n; i++)
                    {
                        writer.write(s4[i]);
                    }
                    writer.close();

                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }

            }

            if( i5 == s.length)
            {pb.setValue(pb.getMaximum());}
        }   
    }
    class ButtonLauscher implements ActionListener
    {
        
        @Override
        public void actionPerformed (ActionEvent ae) {

            if(ae.getSource() == button1){
                try
                {update1(X);
                }
                catch(Exception e)
                {e.printStackTrace();}
            }

        }

    }

    public static void main(String[] args)
    {
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fc.showOpenDialog(null);
        File f1;

        if (returnVal == JFileChooser.APPROVE_OPTION)
        {
            f1 = fc.getSelectedFile();
            X = f1.getPath();

        }   
        GUI programm = new GUI();

    }
}

Leider funktioniert es nicht so wie ich mir das ganze vorstelle. Hat mir da jemand einen Tipp wie das ganze funtionieren könnte?

Vielen Dank schonmal im Voraus.
 
Habe mir das ganze mal angeschaut, aber irgendwie klappts nich so wie ich mir das vorstelle....
Verstehen tu ichs auch noch nich so ganz...

Code:
public class ProgressBarDemo extends JPanel implements ActionListener,
    PropertyChangeListener {
    private static String X;
  private JProgressBar progressBar;
  private JButton startButton;
  private JTextArea taskOutput;
  private Task task;
private int l;
  class Task extends SwingWorker<Void, Void> {


    @Override
    public Void doInBackground() throws IOException {
    
      int progress = 0;
  
      setProgress(0);
      while (progress < 100) {
      
        try {
          Thread.sleep(50);
        } catch (InterruptedException ignore) {
        }
   
      t
        File dir = new File(X);
        File [] s= dir.listFiles();
     
        for (int i5 = 0; i5<s.length; i5++)
        {    l = 100/s.length;
      
          
            if (s[i5].getPath().contains(".lst") || s[i5].getPath().contains(".grp") ||  s[i5].getPath().contains(".GRP" )|| s[i5].getPath().contains(".LST" ))
            {
               
               
                FileReader f = new FileReader(s[i5].getPath());
                BufferedReader b = new BufferedReader(f);
                int n = 0;
              
                String zeilen = b.readLine();
                while(zeilen != null)
                {
                    n++;
                    zeilen = b.readLine();
                }

                f.close();
          
                String[] s4 = new String[n];
                String [] inhalte1 = new String[n];
                f = new FileReader(s[i5].getPath());
                b = new BufferedReader(f);

                for(int i = 0; i<n; i++)
                {
                    inhalte1[i] = b.readLine();

                }
                       
             
                for(int i = 0; i<n; i++)
                {
                   
                      String[]s3 = inhalte1[i].split("(?<=\\|)", 30);
                   
                    
                    if (s3.length == 30)
                    {
                       
                        for(int i1 = 0; i1<s3.length; i1++)
                        {
                            if(s4[i] == null)
                            {s4[i] = "";}
                            if(s3[25].equals("1|"))
                            {s3[25] = "0|";
                            }
                             if(s3[22].equals("11|"))
                            {s3[22] = "10|";
                            }
                            s4[i] = s4[i] + s3[i1];
                        }
                    }
                   
                    else
                    {
                        for(int i1 = 0; i1<s3.length; i1++)
                        {
                            if(s4[i] == null)
                            {s4[i] = "";}
                            s4[i] = s4[i] + s3[i1];
                        }
                    }
                    String separator = System.getProperty( "line.separator" );
                    s4[i] = s4[i] + separator;
                  
                }     
                
               
                try
                {

                    BufferedWriter writer = new BufferedWriter(new FileWriter(s[i5].getPath()));
                    writer.write("");
                    for(int i = 0; i<n; i++)
                    {
                    writer.write(s4[i]);
                   }
                    writer.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
          progress = l*i5;
setProgress(Math.min(progress, 100));
            }}
       
       
       
      }
      return null;
    }

    @Override
    public void done() {
      Toolkit.getDefaultToolkit().beep();
      startButton.setEnabled(true);
      setCursor(null);
      taskOutput.append("Done!\n");
    }
  }

  public ProgressBarDemo() {
    super(new BorderLayout());


    startButton = new JButton("Start");
    startButton.setActionCommand("start");
    startButton.addActionListener(this);

    progressBar = new JProgressBar(0, 100);
    progressBar.setValue(0);
    progressBar.setStringPainted(true);

    taskOutput = new JTextArea(5, 20);
    taskOutput.setMargin(new Insets(5, 5, 5, 5));
    taskOutput.setEditable(false);

    JPanel panel = new JPanel();
    panel.add(startButton);
    panel.add(progressBar);

    add(panel, BorderLayout.PAGE_START);
    add(new JScrollPane(taskOutput), BorderLayout.CENTER);
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

  }

  public void actionPerformed(ActionEvent evt) {
    startButton.setEnabled(false);
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
 
    task = new Task();
    task.addPropertyChangeListener(this);
    task.execute();
  }

  public void propertyChange(PropertyChangeEvent evt) {
    if ("progress" == evt.getPropertyName()) {
      int progress = (Integer) evt.getNewValue();
      progressBar.setValue(progress);
      taskOutput.append(String.format("Completed %d%% of task.\n", task
          .getProgress()));
    }
  }

  private static void createAndShowGUI() {
   
    JFrame frame = new JFrame("ProgressBarDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  
    JComponent newContentPane = new ProgressBarDemo();
    newContentPane.setOpaque(true);
    frame.setContentPane(newContentPane);

    frame.pack();
    frame.setVisible(true);
  }

  public static void main(String[] args) {
     JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fc.showOpenDialog(null);
        File f1;

        if (returnVal == JFileChooser.APPROVE_OPTION)
        {
            f1 = fc.getSelectedFile();
            X = f1.getPath();
        } 
   
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}
 
Schau mal hier. Ein kleines Beispiel
Java:
class FileRunnerBackgroundTask extends SwingWorker<Void, Integer> {

    private final JProgressBar progressBar;
    private final JLabel lblStatus;
    private int maximum;

    public FileRunnerBackgroundTask( JProgressBar progressBar, JLabel lblStatus) {
        this.progressBar = progressBar;
        this.lblStatus = lblStatus;
    }

    @Override
    protected void process( List<Integer> chunks ) {
        int i = chunks.get(chunks.size() - 1);
        progressBar.setValue(i);
        lblStatus.setText(String.format("Loading (%d/%d)", i, maximum));
    }


    @Override
    protected Void doInBackground() throws Exception {
        File directory = new File("dir_path");
        File[] files = directory.listFiles();

        Objects.requireNonNull(files);

        this.maximum = files.length;
        progressBar.setMaximum(maximum);

        for(int i = 0; i < files.length; i++) {

            File currentFile = files[i];
           
           // simuliert deine lange Operation, die du mit dem File machst
            Thread.sleep(30);

            publish(i+1);
        }
        return null;
    }

    @Override
    protected void done() {
        try {
            get();
            lblStatus.setText(String.format("Done (%d/%d)", maximum,maximum));
        } catch ( InterruptedException | ExecutionException e ) {
            e.printStackTrace();
        }
    }
}

Zum verstehen der einzelnen Methoden des SwingWorkers und wann welche Methode wie aufgerufen wird empfehle ich die JavaDoc zum SwingWorker
 

Zurück
Oben