javaswingjframeactionlistenerjprogressbar

How to add a JProgressBar which works with a Timer in my code?


I want to add a JProgressBar in my code, which counts till 5 (in seconds). After that, it shall make new values, but my current problem is, that I can't even make the ProgressBar with my ActionListener, so I doesn't repeat. Can someone show me how to add the ProgressBar with the Timer?

I tried to add it in the Haupt class, but it didn't repeat after pressing the restart button (Neustart), so I tried many other things, but nothing worked.

/**
 * @author (Noah Steinle) 
 * @version (2.2.1)
 */

//Importe
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import javax.swing.JProgressBar;
import javax.swing.Timer;

//Klasse mit JFrame erweitert und hat einen ActionListener implementiert
public class Haupt extends JFrame implements ActionListener 
{
    private int x = (int) (Math.random() * 20 + 1);
    private int y = (int) (Math.random() * 20 + 1);
    private int z = x * y;  

    private JTextField benutzerWert;   

    private JLabel aufgabe;
    private JLabel eingabeTipp;    
    private JButton neustartButton;

    private static int richtig;
    private JLabel richtigLabel;

    private static int falsch;
    private JLabel falschLabel;

    private Timer timer;

    private JProgressBar progressBar;


    public Haupt() 
    {
        super("Multi-Game");

        //nutzt FlowLayout ein
        setLayout(new FlowLayout());

        //Label zur Anzeige des Aufgabeterms
        aufgabe = new JLabel(x + "\u2219" + y + "= ");  
        add(aufgabe);

        //Eingabefeld für Benutzer und wird gecheckt
        benutzerWert = new JTextField(5); 
        benutzerWert.addActionListener(this);
        add(benutzerWert);

        //gibt einen Tipp aus, wie der Wert im Vergleich zum Ergebnis ist
        eingabeTipp = new JLabel("");
        add(eingabeTipp); 

        //Neustart
        neustartButton = new JButton("Nächste Aufgabe");
        add(neustartButton);
        neustartButton.addActionListener(this);

        //Anzahl der Richtigen        
        richtig = 0;
        richtigLabel = new JLabel();
        richtigLabel.setText("Anzahl der Richtigen: " + richtig);
        add(richtigLabel);

        //Anzahl der Falschen
        falsch = 0;
        falschLabel = new JLabel();
        falschLabel.setText("Anzahl der Falschen: " + falsch);
        add(falschLabel);

        //ProgressBar erstellen
        progressBar =new JProgressBar(0,5); //min = 0 , max = 5
        add(progressBar);
    }  

    //Methode zum Generieren von Zufallswerten im Bereich von 1 bis 20
    private int zufallWert()
    {
        int x = (int) (Math.random() * 20 +1);
        return x;
    }




     public void actionPerformed(ActionEvent e) 
     {
           //Reaktion auf Benutzereingabe
           if(e.getSource()==benutzerWert) {

             int versuch;

             //String (benutzerWert) in Integer umwandeln + in Versuch einf.
             versuch = Integer.parseInt(benutzerWert.getText());


             if (versuch > z) 
             {
                  eingabeTipp.setText("Zu groß!");
                  SwingUtilities.updateComponentTreeUI(eingabeTipp);
                  getContentPane().setBackground(Color.RED);
                  eingabeTipp.setForeground(Color.BLACK);
                  aufgabe.setForeground(Color.BLACK);
                  falsch++;
                  falschLabel.setText("Falsche: " + falsch);
             }

             if (versuch < z) 
              {
                  eingabeTipp.setText("Zu klein!");
                  SwingUtilities.updateComponentTreeUI(eingabeTipp);
                  getContentPane().setBackground(Color.BLUE);
                  eingabeTipp.setForeground(Color.WHITE);
                  aufgabe.setForeground(Color.WHITE);
                  falsch++;
                  falschLabel.setText("Falsche: " + falsch);
              }             

             if (versuch == z) 
              {
                  eingabeTipp.setText("Richtig!!!");
                  //SwingUtilities.updateComponentTreeUI(eingabeTipp);
                  benutzerWert.setEditable(true);
                  getContentPane().setBackground(Color.GREEN);
                  eingabeTipp.setForeground(Color.BLACK);
                  aufgabe.setForeground(Color.BLACK);
                  richtig++;
                  richtigLabel.setText("Richtige : " + richtig);
                  x = zufallWert();
                  y =zufallWert();
                  z = x * y;
                  aufgabe.setText(x + "\u2219" + y);
                  getContentPane().setBackground(Color.WHITE);
                  eingabeTipp.setForeground(Color.BLACK);
                  aufgabe.setForeground(Color.BLACK);
                  benutzerWert.setText("");
                  eingabeTipp.setText("");
              }      
           }

           //Button setzt neue Werte
           else
           {
               x = zufallWert();
               y =zufallWert();
               z = x * y;
               aufgabe.setText(x + "\u2219" + y);
               getContentPane().setBackground(Color.WHITE);
               eingabeTipp.setForeground(Color.BLACK);
               aufgabe.setForeground(Color.BLACK);
               benutzerWert.setText("");
           }
     } 

    //Anzeigen des JFrames
    public static void main(String args[]) 
    {
        Haupt ausgabeFrame = new Haupt();
        ausgabeFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ausgabeFrame.setSize(550, 150);
        ausgabeFrame.setVisible(true);
    }
}

If the answer is right, it should add 1 to "Richtige" else to "Falsche", if the timer is at 5, while trying to answer the question, it should skip to the next question (so new values).


Solution

  • I just figured it out and wanted to share my solution:

    /**
     * @author (Noah Steinle) 
     * @version (2.3.1)
     */
    
    //Importe
    import java.awt.Color;
    import java.awt.FlowLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.util.Random;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.JLabel;
    import javax.swing.JButton;
    import javax.swing.SwingUtilities;
    import javax.swing.JProgressBar;
    import javax.swing.Timer;
    
    //Klasse mit JFrame erweitert und hat einen ActionListener implementiert
    public class Haupt extends JFrame implements ActionListener
    {
        private int x = (int) (Math.random() * 20 + 1);
        private int y = (int) (Math.random() * 20 + 1);
        private int z = x * y;  
    
        private JTextField benutzerWert;   
    
        private JLabel aufgabe;
        private JLabel eingabeTipp;    
        private JButton neustartButton;
    
        private static int richtig;
        private JLabel richtigLabel;
    
        private static int falsch;
        private JLabel falschLabel;
    
        private Timer timer;
    
        private int counter;
    
        private JProgressBar progressBar;
    
    
        public Haupt()
        {
            super("Multi-Game");
    
            //nutzt FlowLayout ein
            setLayout(new FlowLayout());
    
            //Label zur Anzeige des Aufgabeterms
            aufgabe = new JLabel(x + "\u2219" + y + "= ");
            add(aufgabe);
    
            //Eingabefeld für Benutzer und wird gecheckt
            benutzerWert = new JTextField(5);
            benutzerWert.addActionListener(this);
            add(benutzerWert);
    
            //gibt einen Tipp aus, wie der Wert im Vergleich zum Ergebnis ist
            eingabeTipp = new JLabel("");
            add(eingabeTipp);
    
            //Neustart
            neustartButton = new JButton("Naechste Aufgabe");
            add(neustartButton);
            neustartButton.addActionListener(this);
    
            //Anzahl der Richtigen
            richtig = 0;
            richtigLabel = new JLabel();
            richtigLabel.setText("Anzahl der Richtigen: " + richtig);
            add(richtigLabel);
    
            //Anzahl der Falschen
            falsch = 0;
            falschLabel = new JLabel();
            falschLabel.setText("Anzahl der Falschen: " + falsch);
            add(falschLabel);
    
            //ProgressBar wird erstellt
            progressBar = new JProgressBar(0,5); //min = 0 , max = 5
            progressBar.setValue(0);
            add(progressBar);
            
            //Timer wird erstellt
            timer = new Timer(5000, this); //Timer mit 5 Sekunden
              
               timer.start();
               new Timer(1000, updateProBar).start();
        }  
    
        ActionListener updateProBar = new ActionListener() 
        {
           public void actionPerformed(ActionEvent actionEvent) 
           {
              //ProgressBar wird veraendert
              progressBar.setValue(++counter);
              if(progressBar.getValue() == 5) 
              {
                 counter = 0;
              }
           }
        };
        
        
        //Methode zum Generieren von Zufallswerten im Bereich von 1 bis 20
        private int zufallWert()
        {
           int x = (int) (Math.random() * 20 +1);
           return x;
        }
    
         public void actionPerformed(ActionEvent e)
         {
               //Reaktion auf Benutzereingabe
               if(e.getSource()==benutzerWert) {
    
                 int versuch;
    
                 //String (benutzerWert) in Integer umwandeln + in Versuch einf.
                 versuch = Integer.parseInt(benutzerWert.getText());
    
                 //wenn Eingabe groesser als Ergebnis
                 if (versuch > z)
                 {
                      eingabeTipp.setText("Zu gross!");
                      SwingUtilities.updateComponentTreeUI(eingabeTipp);
                      getContentPane().setBackground(Color.RED);
                      eingabeTipp.setForeground(Color.BLACK);
                      aufgabe.setForeground(Color.BLACK);
                      falsch++;
                      falschLabel.setText("Falsche: " + falsch);
                 }
                 //wenn Eingabe geringer als Ergebnis
                 if (versuch < z)
                  {
                      eingabeTipp.setText("Zu klein!");
                      SwingUtilities.updateComponentTreeUI(eingabeTipp);
                      getContentPane().setBackground(Color.BLUE);
                      eingabeTipp.setForeground(Color.WHITE);
                      aufgabe.setForeground(Color.WHITE);
                      falsch++;
                      falschLabel.setText("Falsche: " + falsch);
                  }
                 //wenn Ergebnis erraten
                 if (versuch == z)
                  {
                      eingabeTipp.setText("Richtig!!!");
                      //SwingUtilities.updateComponentTreeUI(eingabeTipp);
                      benutzerWert.setEditable(true);
                      getContentPane().setBackground(Color.GREEN);
                      eingabeTipp.setForeground(Color.BLACK);
                      aufgabe.setForeground(Color.BLACK);
                      richtig++;
                      richtigLabel.setText("Richtige : " + richtig);
                      x = zufallWert();
                      y =zufallWert();
                      z = x * y;
                      aufgabe.setText(x + "\u2219" + y);
                      getContentPane().setBackground(Color.WHITE);
                      eingabeTipp.setForeground(Color.BLACK);
                      aufgabe.setForeground(Color.BLACK);
                      benutzerWert.setText("");
                      eingabeTipp.setText("");
                      counter = 0;
                      progressBar.setValue(0);
                      timer.restart();
                  }
               }
    
               //Button setzt neue Werte und Timer bzw. ProgressBar auch
               else
               {
                   x = zufallWert();
                   y =zufallWert();
                   z = x * y;
                   aufgabe.setText(x + "\u2219" + y);
                   getContentPane().setBackground(Color.WHITE);
                   eingabeTipp.setForeground(Color.BLACK);
                   aufgabe.setForeground(Color.BLACK);
                   benutzerWert.setText("");
                   counter = 0;
                   progressBar.setValue(0);
                   timer.restart();
               }
         } 
         
        //Anzeigen des JFrames
        public static void main(String args[])
        {
            Haupt ausgabeFrame = new Haupt();
            ausgabeFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            ausgabeFrame.setSize(550, 150);
            ausgabeFrame.setVisible(true);
        }
    }