Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 16 of 16

Thread: Create A Countdown In Java

  1. #1
    Junior Member
    Join Date
    Feb 2014
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Create A Countdown In Java

    Hi, I'm making a small play in java in which you have a limited time to make as many moves as possible (with the aim of achieving a maximum score), like this: http://apps4review.com/wp-content/up...ed-Blitz_2.jpg

    In the game panel I see the map on which you will perform the moves and a score indicator constantly updated. I have to add the indicator that shows me the passage of time (first 3 minutes), in digital format mm: ss. I thought I will be a useful thread called Countdown because I have to stop this counter if the user presses the pause button in the game. Then wanting to continue the game shall resume the countdown.

    What approach could I use?


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,256
    My Mood
    Hungover
    Thanks
    142
    Thanked 618 Times in 529 Posts

    Default Re: Create A Countdown In Java

    Quote Originally Posted by Nemesis89 View Post
    What approach could I use?
    What have you tried? How are you updating the score indicator?

    You might want to take a look at Swing Timers. More info here: Swing Timers - Tutorials - Static Void Games
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Junior Member
    Join Date
    Feb 2014
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Create A Countdown In Java

    Unfortunately I could not write anything yet because I do not know where to start.
    Thanks anyway for the suggestion

  4. #4
    Junior Member
    Join Date
    Feb 2014
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Create A Countdown In Java

    By studying the example in the link Swing Timers - Tutorials - Static Void Games

    I noticed that the class "MyListener" implements ActionListener. In my case I will have action on the part of MyListener in response to an event triggered by MouseListener.

    In order to better understand:
    I have a Game class (extends JPanel) where the constructor has associated this.addMouseMotionListener (new MouseMotionListener () {...} and this.addMouseListener (new MouseListener () {.....} because I need to work with both. wanting to tie the class MyListener how should I implement it to make sure it works?

  5. #5
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,737
    My Mood
    Mellow
    Thanks
    172
    Thanked 622 Times in 609 Posts

    Default Re: Create A Countdown In Java

    Your setup and subsequent question are too vague. Show some short example code that outlines the classes you've mentioned and how they should relate to each (you might figure it out putting that together) and ask a question based on that construction.

  6. #6
    Junior Member
    Join Date
    Feb 2014
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Create A Countdown In Java

    This is the class Game

    public Game(final MainFrame mainFrame,  final GameManager gameManager, ImageProvider imageProvider) {
    				this.setLayout(null);
    				dragX=0;
    				dragY=0;
    				direction=-1;
    				setPress= false;
    				drawBackground=false;
    				this.mainFrame = mainFrame;
    				this.gameManager = gameManager;
    				this.imageProvider = imageProvider;
    				this.wManager = gameManager.getWorldManager();
    				this.currentWorld= gameManager.getCurrentWorld();
    				inserts = this.getInsets();
     
    				worldHeight = gameManager.getCurrentWorld().getData().length;
    				worldWidth = gameManager.getCurrentWorld().getData().length;
     
    				width = imageProvider.getImage().getWidth(this);
    				height = imageProvider.getImage().getHeight(this);
     
    				paintPauseButton();
     
    				this.addMouseMotionListener(new MouseMotionListener() {
     
    					@Override
    					public void mouseMoved(MouseEvent e) {}
     
    					@Override
    					public void mouseDragged(MouseEvent e) 
    					{
    						if(setPress == false){
    							dragY = e.getX()/width;
    							dragX = e.getY()/height;		
    							setPress=true ;
    						}
    						else{
    							lastY = e.getX()/width;
    							lastX = e.getY()/height;
    						}
    						repaint();
    						e.consume();
    					}
     
    				});
     
    				this.addMouseListener(new MouseListener() {
    					@Override
    					public void mouseClicked(MouseEvent e) {
    					  int clickY = e.getX()/width;
    					  int clickX = e.getY()/height;
     
    			                  JOptionPane.showMessageDialog(mainFrame, "ERROR", "Message", JOptionPane.CLOSED_OPTION);
    			                  repaint();
    			                  e.consume();
    					}
     
    					@Override
    					public void mouseReleased(MouseEvent e){
    							try {
    								Thread.sleep(10);
    							} catch (InterruptedException e1) {
    								// TODO Auto-generated catch block
    								e1.printStackTrace();
    							}
    						if(lastX < pressX){ //UP
    						checkMoves();
    						direction = 0;
     				                wManager.move(Game.this.gameManager.set, direction, wManager.worldTmp, dragX, dragY);
     
    						setPress = false;
    						drawBackground=false;
     
     
    						else if(lastX > pressX){ //DOWN
    						checkMoves();
    						direction = 1;
    						wManager.move(Game.this.gameManager.set, direction, wManager.worldTmp, dragX, dragY);
    						setPress = false;
    						drawBackground=false;
    						}
     
    						else if(lastY < pressY ){ //LEFT
    						checkMoves();
    						direction = 2;
    						wManager.move(Game.this.gameManager.set, direction, wManager.worldTmp, dragX, dragY);
    						setPress = false;
    						drawBackground=false;
    						}
                                                 else{
    						checkMoves();
    						direction = 3;
    						wManager.move(Game.this.gameManager.set, direction, wManager.worldTmp, dragX, dragY);
    						setPress=false;
    						drawBackground=false;
    						}
     
    						repaint();
    						e.consume();
    					}
     
    					@Override
    					public void mouseEntered(MouseEvent e) {}
     
    					@Override
    					public void mouseExited(MouseEvent e) {}
     
    					@Override
    					public void mousePressed(MouseEvent e){
    						pressX =  e.getY()/height; 
    						pressY = e.getX()/width; 
    						drawBackground = true;
    						repaint();
    						e.consume();
    					}
    				});
    			}
     
     
    private void paintTime(Graphics g, int worldHeight2, int worldWidth2) {
    			g.drawImage(imageProvider.getTime(), worldWidth2 + 1000, worldHeight2 + 300, this);	
    			f = new Font("Cooper Black", Font.BOLD, 90);
    			g.setFont(f);
    			g.setColor(Color.RED);
                       //Here I have to draw the string that will represent the passing of time
    	}
     
    protected void paintComponent(Graphics g) {
    			super.paintComponent(g);
    			g.drawImage(imageProvider.getBackgroundGame(), 0, 0, getWidth(), getHeight(), this);
     
                            //this function draws a map of my game
    			paintMap(g, wManager.worldTmp, worldHeight, worldWidth); 
     
    			paintTime(g, worldHeight, worldWidth);
    		}

    How could I add the function MyListener present in the link above?

  7. #7
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,737
    My Mood
    Mellow
    Thanks
    172
    Thanked 622 Times in 609 Posts

    Default Re: Create A Countdown In Java

    How could I add the function MyListener present in the link above?
    I'm not sure what you mean by that. What is a 'function' in Java? And I'm not sure what 'link above' you are referring to. Why don't you try adding it just as you would any other class or interface (whatever it is), and if you have errors to resolve, come back with the code and the error.

    You're showing the Game() constructor, right? You've overused 'this.'

    What happens when you add the annotation @Override to your paintComponent() method?

    The Game class can extend one class and implement many interfaces.

  8. #8
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,256
    My Mood
    Hungover
    Thanks
    142
    Thanked 618 Times in 529 Posts

    Default Re: Create A Countdown In Java

    Quote Originally Posted by Nemesis89 View Post
    I noticed that the class "MyListener" implements ActionListener. In my case I will have action on the part of MyListener in response to an event triggered by MouseListener.
    You'll need at least 2 separate listeners: a MouseListener that triggers the event (starting the timer), and an ActionListener that gets triggered by the Timer when it fires.

    I would suggest having the Timer repeat every second (or more often if you want), and then updating the display whenever the Timer fires to keep your countdown going. Then just stop the Timer when your countdown has expired.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  9. #9
    Junior Member
    Join Date
    Feb 2014
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Create A Countdown In Java

    With regard to the ActionListener I would like to add it to the JButton "Start Game" .
        public String show="";
        JButton startGame = new JButton(new ImageIcon("start.png");
        startGame .setBorder(null);
     
        Dimension size = timeButton.getPreferredSize();
        startGame .setBounds(100 + inserts.left, 280 + inserts.bottom, size.width, size.height);
        startGame .addActionListener(listener); 
        // where MyTime listener = new MyTime (show, setTimeGame (180));
       // Pressing " StartGame " must take the following action : mainFrame.switchGamePanel (), which represents the game screen .
     
     
     
    //The class MyTime
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
     
                   public class MyTime implements ActionListener{
     
    		private int totalTime = 0;		
    		private String showTime;
     
    		public MyTime(String showTime, int totalTime){
    			this.showTime = showTime;
    			this.totalTime=totalTime;
    		}
     
    		public void actionPerformed(ActionEvent e) {
    			--totalTime;
    			setShowTime(""+totalTime);
    		}
     
    		public String getShowTime() {
    			return showTime;
    		}
     
    		public void setShowTime(String showTime) {
    			this.showTime = showTime;
    		}
    }

  10. #10
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,256
    My Mood
    Hungover
    Thanks
    142
    Thanked 618 Times in 529 Posts

    Default Re: Create A Countdown In Java

    Quote Originally Posted by Nemesis89 View Post
    With regard to the ActionListener I would like to add it to the JButton "Start Game"
    In that case, you'll need *two* ActionListeners: one for the JButton, and one for the Timer. The JButton's ActionListener starts the Timer. The Timer's ActionListener updates the display.

    You could also use a single ActionListener and check the source, but IMHO that approach is a little more convoluted.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  11. #11
    Junior Member
    Join Date
    Feb 2014
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Create A Countdown In Java

    And the switch panel who should do it?
    Could you show me an example if possible?

  12. #12
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,256
    My Mood
    Hungover
    Thanks
    142
    Thanked 618 Times in 529 Posts

    Default Re: Create A Countdown In Java

    Quote Originally Posted by Nemesis89 View Post
    And the switch panel who should do it?
    Could you show me an example if possible?
    There are several examples of using an ActionListener on a JButton as well as on a Timer in the link I gave you.

    Split your problem up into smaller pieces: Can you create a standalone program that prints out a message when you click a button? Can you create a separate standalone program that displays a countdown that starts as soon as the program is run?

    When you get each of those working individually, then you can combine them into a single program that starts a countdown after you click a button.

    This will also help you ask more specific questions when you get stuck, because you'll be able to post an SSCCE that shows what you're doing. Good luck!
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  13. #13
    Junior Member
    Join Date
    Feb 2014
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Create A Countdown In Java

    I created my countdown thread!
    The manufacturer of the thread as a parameter will have the time in seconds (eg 120) and then be shown divided into minutes and seconds. In this case, doing 120/60 I get the minutes, but in the case where there are also second to display (eg 150), how could I do?

  14. #14
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,737
    My Mood
    Mellow
    Thanks
    172
    Thanked 622 Times in 609 Posts

    Default Re: Create A Countdown In Java

    Do you mean that for 150 seconds the display should be 2:30? How do you find what's left (the remainder) after dividing by something?

  15. #15
    Junior Member
    Join Date
    Feb 2014
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Create A Countdown In Java

    I solved:
    long totalSeconds = 150;
    long minutes = totalSeconds / 60;
    long seconds = totalSeconds % 60;
    //minutes -> 2
    //seconds -> 30

  16. #16
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,737
    My Mood
    Mellow
    Thanks
    172
    Thanked 622 Times in 609 Posts

    Default Re: Create A Countdown In Java

    Excellent!

Similar Threads

  1. Countdown timer
    By AANZ in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 1st, 2013, 07:46 AM
  2. Please help me with my Java Countdown Timer
    By remagarrote in forum AWT / Java Swing
    Replies: 3
    Last Post: March 8th, 2013, 09:09 AM
  3. [SOLVED] Countdown type game help needed.
    By Acaul in forum What's Wrong With My Code?
    Replies: 20
    Last Post: December 14th, 2012, 09:55 AM
  4. Timer Countdown - Code Syntax
    By baddack in forum What's Wrong With My Code?
    Replies: 22
    Last Post: September 26th, 2012, 03:56 PM
  5. Timer class countdown
    By p0oint in forum Object Oriented Programming
    Replies: 5
    Last Post: August 26th, 2010, 03:31 AM