MAke a quiz in gui which shows the player the time left for a particular question and automatically proceeds to the next question when time limit exceeds. time left to be shown in a jlabel

I ve tried this code in non - gui window I.e in java class but i m not able to implement it in jframe form using jlabel . please help me display time left for a particular question of my quiz in a jlabel and automatically proceed to next question when the time limit exceeds . also tell me where to write the code while creating jFrame .
here's my code :-

public class myclass{
public static void main(String[] args){
Thread thread = new Thread();
for(int i = 60;i>=0;i--)
{ System.out.println(i);
thread.sleep(1000);
}
}
}

Thanks for the code ,, And i tried the latter site www.javacoderanch.com and I wrote the exact code but I Am getting an error in that says "**Class , Interface or Enum expected" and the "Whole public static main method is underlined red" **
please tell me how to remove the error
.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package newpackage;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

/**
 *
 * @author win 7
 */
public class NewJFrame extends javax.swing.JFrame {
  public static final DateFormat df = new SimpleDateFormat("hh:mm:ss");
    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() throws HeadlessException {
        initUI();
    }
 private void initUI() {
 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 setSize(200,200);
 Container container = getContentPane();
 container.setLayout( new FlowLayout(FlowLayout.CENTER));
 final JLabel label = new JLabel();
 container.add(label);
 Timer timer = new Timer(1000, new ActionListener(){ 
     public void actionPerformed(ActionEvent e ){
         Calendar  now = Calendar.getInstance();
         String  timeText = df.format(now.getTime());
         label.setText(timeText);
     }
 });
 timer.start();
     }



 }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
       SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }a

    // Variables declaration - do not modify                     
    // End of variables declaration                   

    private void initUI() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.

}

Its a mistake to try to learn basic principles from a sample as complicated as that.
Because the weather here is horrible and I have nothing better to de I'll take a moment to show you a very very simple program that updates a JLabel with a one-second counter.

This will only be useful if you take the time to understand every single line, using the API reference documentation for anything unfamiliar. Once you understand it all you will know how to write your own program.

import javax.swing.*;

public class SimplestTimer {

    public static void main(String[] args) {
        new SimplestTimer();
    }

    JFrame frame = new JFrame("Timer");
    JLabel timeLabel = new JLabel("Time shown here");
    int timeCounter = 0;

    SimplestTimer() {
        frame.add(timeLabel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        new Timer(1000, this::updateGUI).start();
    }

    void updateGUI(java.awt.event.ActionEvent e) {
        timeLabel.setText("" + (++timeCounter));
    }
}

If you get stuck you can ask questions here, but only after trying yourself.

OK I ll try and understand first by myself. BTW thank you so much JamesCherrill.
:-):-):-):-)

Can u explain me d working of updateGUI() and why it is void ,, and how we can start and stop the timer using a button

Starting at the top...
You create a Timer by giving it a time interval (1000 mSec in this case) and an ActionListener (the same as an ActionListener for a JButton etc). The Timer then calls the ActionListener every 1000 mSec. The code above uses a Java 8 lambda, which maybe you haven't covered yet, so here's the long verersion that you would have used before Java 8...

timer = new Timer(1000, new ActionListener(){ 
     public void actionPerformed(ActionEvent e ){
         updateGUI(e);
     }
 });

so via that the updateGUI method gets called every 1000 mSec. It's void because it doesn't return anything. It just adds one to the timeCounter, converts that to a String and uses it to set the JLabel's text.

Once you have created a Timer you can start and stop it by calling its start() and stop() methods (cunning, eh?). Eg if you have a startTimer JButton you would use

startTimer.addActionListener(new ActionListener(){ 
    public void actionPerformed(ActionEvent e ){
        timer.start();
    }
});

Edited 9 Months Ago by JamesCherrill

Thanks James ,, the code's working but when I added the button startTimer the Jlabel disappeared and when I added another button stop the start button disappeared .
Please help me with it . Also I designed a Jframe form Using a Label , stop and start button but the code is not working with jframe components. Plzz help me .

Sounds like you are having layout manger problems, for example, the default LM for a JFrame is a BorderLayout, in which if you just add a component without saying where to add it it goes in the center position, replacing whatever was there before.

This tutorial will teach you how to chose and use a Layout Manager
https://docs.oracle.com/javase/tutorial/uiswing/layout/index.html

Apart from that I can't say anything sensible about code I have never seen!

This is the code which I used in my Jframe form but nothing happens when I click the start and stop buttons .

package newpackage;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

/**
 *
 * @author win 7
 */
public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();


    }

     public  int timeCounter = 0;
      void  SimplestTimer(){
          Timer   timer = new Timer(1000, new ActionListener(){ 
      public void actionPerformed(ActionEvent e ){
         updateGUI(e);
     }
   });
btnstart.addActionListener(new ActionListener(){ 
    public  void actionPerformed(ActionEvent e ){
       timer.start();
    }
}); 

btnstop.addActionListener(new ActionListener(){ 
    public void actionPerformed(ActionEvent e ){
       timer.stop();
    }
});
    }


    void updateGUI(java.awt.event.ActionEvent e) {

       lbld.setText("" + (++timeCounter));

    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        lbld = new javax.swing.JLabel();
        btnstart = new javax.swing.JButton();
        btnstop = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lbld.setText("time");
        lbld.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(153, 153, 0), null));

        btnstart.setText("start");
        btnstart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnstartActionPerformed(evt);
            }
        });

        btnstop.setText("stop");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(147, 147, 147)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnstart)
                    .addComponent(lbld, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnstop)
                .addContainerGap(94, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(44, 44, 44)
                .addComponent(lbld, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(54, 54, 54)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnstart)
                    .addComponent(btnstop))
                .addContainerGap(121, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void btnstartActionPerformed(java.awt.event.ActionEvent evt) {                                         

    // TODO add your handling code here:
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
                 new SimplestTimer();
            }
        });
    }




    // Variables declaration - do not modify                     
    private javax.swing.JButton btnstart;
    private javax.swing.JButton btnstop;
    private javax.swing.JLabel lbld;

You seem to have tried to incorporate the SimplestTimer code and got that wrong.
Line 142 will create a new instance of the SimplestTimer class, but that has no relevance to this application. You have a method called SimplestTimer, but you don't call it.

Forget/delete SImplestTimer now - it was just a teaching aid.
Take the code that starts the timer and adds the button listeners, and put that in your constructor after the call to initComponents.

Can you please explain me what is contructor and how should I call initComponents();

Please can You help me get answers to my questions related to the code below

public class NewJFrame extends javax.swing.JFrame {
    public  int timeCounter = 0;
    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();

          Timer   timer = new Timer(1000, new ActionListener(){ 
      public void actionPerformed(ActionEvent e ){
         updateGUI(e);
     }
   });
btnstart.addActionListener(new ActionListener(){ 
    public  void actionPerformed(ActionEvent e ){
       timer.start();
    }
}); 

btnstop.addActionListener(new ActionListener(){ 
    public void actionPerformed(ActionEvent e ){
       timer.stop();
    }
});



    }





    void updateGUI(java.awt.event.ActionEvent e) {

       lbld.setText("" + (++timeCounter));

    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        lbld = new javax.swing.JLabel();
        btnstart = new javax.swing.JButton();
        btnstop = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lbld.setText("time");
        lbld.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(153, 153, 0), null));

        btnstart.setText("start");
        btnstart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnstartActionPerformed(evt);
            }
        });

        btnstop.setText("stop");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(147, 147, 147)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)

     .addComponent(btnstart)
                    .addComponent(lbld, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnstop)
                .addContainerGap(94, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(44, 44, 44)
                .addComponent(lbld, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(54, 54, 54)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnstart)
                    .addComponent(btnstop))
                .addContainerGap(121, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void btnstartActionPerformed(java.awt.event.ActionEvent evt) {                                         

    // TODO add your handling code here:
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);

            }
        });
    }

Q1. why void updateGui is out of the scope of class NewJFrame?(lines 52-56)
Q2. IN line 29 y u have written "e" in the bracket of updateGUI(e)?

Q1 - don't understand the question. It is in the scope, and lines 52-56 have nothing to do with it
Q2 - updateGui takes an instance of ActionEvent as a parameter. Where it is called there is a suitable instance in the variable e (it was passed in as a parameter to the actionPerformed method).

ps: I;m going out now, so no more answers until tomorrow.
J

pps: Back now.
When you post code you can omit all the standard stuff that Netbeans generates (initComponents and main) - just leave the method header and the closing bracket.

Edited 9 Months Ago by JamesCherrill

Now I am making a quiz using a jframe form . I have 1 question in each panel including a panel for front and end page . Can you suggest me a way how to easily switch between these panels and create them. like there will be almost 20 panels and have very little space to design them . Also if there is a better alternate to panels .. please suggest me .

Can you tell me how can overlap Multiple JPanels over each other in a JFrame Form.

OH But i DIdnt liked the appearence of tabbed pane therefore i didnot read it.

OK.
If you don't want the tabs then you can place a whole lot of JPanels at the same place and make all except one invisible setVisible(false) When you want to change panels make the current one invisible and the next one visible.

Ok , But the problem I am encountering is that I cannot Design like say 20 panels in my Jframe form ... I dont have space on my window ... unless I am Able to overlap them over Each other while designing ... I read about Overlay Layout and CardLayout but I am not able to use them ... like when I try them .. the whole thing merges into One .. please help me get a way out of this Situation .... I hope You understood my problem Cherrill.._Plzz help

And The thing is while switching between the JPanels .. the first one should exactly take the place of the second .. to ensure smooth Switching between the Panels .. plzz help

Can you please tell how can I change the background propertyi.e. I want to insert its predefined background graphic which I did using one of its properties but I cannot recall it now . I googled it but I could get results related to only changing its background Image using some code ...but as far as I remember I changed its Background with some Texture without using any code.. help Plzz!!!

This question has already been answered. Start a new discussion instead.