Results 1 to 16 of 16

Thread: Timer help

  1. #1
    Kinyo is offline Member
    Join Date
    Mar 2009
    Posts
    10
    Rep Power
    0

    Angry Timer help

    I have this program that as soon as you click on a grid of 10 by 10 buttons. Like a checkers game. And as soon as you click on it I have a timer that keeps track of the time for how long you play. I also have a button called "New Game" once I click it I want it to reload the window with everything set back to default. For some reason I simply cannot get it. Anyone know how to do it?

    I was told to go to the action listener when the button is clicked, set everything there back to default. I got all of that working, but when the new window loads, the timer is set back to "0:00" but it keeps going. The timer doesn't stop and waits for someone to click on the grid again.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    without code, it's hard to say what is wrong. I would make sure that you call stop() on the Swing Timer (it is a Swing Timer, right?) when you reset everything else. I would then call start() on the timer from within the grid-button's actionlistener after first checking to see if the timer is running or not.

  3. #3
    Kinyo is offline Member
    Join Date
    Mar 2009
    Posts
    10
    Rep Power
    0

    Default

    Here is the code that I have. I hope this is all that is needed.

    Java Code:
    package battleshipGUI;
    
    
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.*;
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.LineBorder;
    
    /**
     * Purpose:
     * 
     * @author cst132
     */
    public class BattleshipWindow extends JFrame implements ActionListener
    {
        /**
         * Define default board height
         */
        public static final int HEIGHT = 10;
        /**
         * Define default board width
         */
        public static final int WIDTH = 10;
        /**
         * Define default number of ships in the game
         */
        public static final int NUMBER_OF_SHIPS = 5;
        /**
         * Define starting column heading letter
         */
    
        private int timerMinute;
        private int timerSecond;
        private int guessCounter;
    
        private Timer timer;
        // private BattleshipGrid grid;
        private DisplayableCell[][] cells;
        private Ship[] ships;
    
        private JButton newGameButton = new JButton("New Game");
        private JButton closeButton = new JButton("Close");
        private JButton[][] cellButtons;
    
        // temp button for stopping the temp timer
        // JButton stopMe = new JButton("Stop Me");
    
        private JLabel welcome = new JLabel(
                "Welcome to CST Single Player BattleShip");
        private JLabel elapsedTime = new JLabel("Elapsed Game Time:");
        private JLabel cellGuessed = new JLabel("Cells Guessed:");
        private JLabel timeCounter = new JLabel("0:00");
        private JLabel guessCounterLabel = new JLabel();
    
        private JPanel gridPanel;
        private JPanel rightPanel;
        private JPanel timePanel;
        private JPanel guessPanel;
    
        public BattleshipWindow()
        {
            setTitle("CST Battleship");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            setSize(530, 500);
            initializeWindow();
            createMenu();
            setVisible(true);
    
            timerSecond = 1;
            timerMinute = 0;
            timer = new Timer(1000, this);
    
            guessCounter = 0;
        }
    
        private void initializeWindow()
        {
    
            JPanel topPanel = new JPanel();
            topPanel.add(welcome);
            add(topPanel, BorderLayout.NORTH);
    
            JPanel bottomPanel = new JPanel();
            bottomPanel.add(newGameButton);
            bottomPanel.add(closeButton);
            add(bottomPanel, BorderLayout.SOUTH);
    
            initRightPanel();
            add(rightPanel, BorderLayout.EAST);
    
            initGridPanel();
            add(gridPanel, BorderLayout.CENTER);
    
            closeButton.addActionListener(new MyListener());
            newGameButton.addActionListener(new MyListener());
        }
    
        private void initRightPanel()
        {
            rightPanel = new JPanel();
    
            timePanel = new JPanel();
            timePanel.setBorder(new LineBorder(Color.BLACK, 1));
            timePanel.add(timeCounter);
    
            guessPanel = new JPanel();
            guessPanel.setBorder(new LineBorder(Color.BLACK, 1));
            guessCounterLabel.setText(guessCounter + "");
            guessPanel.add(guessCounterLabel);
            
            rightPanel.setLayout(new GridLayout(4, 1));
            rightPanel.add(elapsedTime);
            rightPanel.add(timePanel);
            rightPanel.add(cellGuessed);
            rightPanel.add(guessPanel);
            rightPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
    
        }
    
        public void initGridPanel()
        {
            gridPanel = new JPanel();
            gridPanel.setSize(320, 320);
            gridPanel.setLayout(new GridLayout(HEIGHT, WIDTH));
            cells = new DisplayableCell[HEIGHT][WIDTH];
            cellButtons = new JButton[HEIGHT][WIDTH];
    
            for (int i = 0; i < cellButtons.length; i++)
            {
                for (int j = 0; j < cells.length; j++)
                {
                    cellButtons[i][j] = new JButton();
                    cells[i][j] = new EmptyCell();
                    cellButtons[i][j].setIcon(cells[i][j].displayCell(0));
                    gridPanel.add(cellButtons[i][j]);
    
                    cellButtons[i][j].addActionListener(new MyListener());
                }
            }
    
            createShips();
        }
    
        public void createMenu()
        {
            JMenuBar menuBar = new JMenuBar();
            setJMenuBar(menuBar);
    
            JMenu controlMenu = new JMenu("Game");
            menuBar.add(controlMenu);
    
            JMenuItem newGame = new JMenuItem("New Game");
            controlMenu.add(newGame);
            JMenuItem close = new JMenuItem("Close");
            controlMenu.add(close);
    
            newGame.addActionListener(new MyListener());
    
        }
    
        public void createShips()
        {
            ships = new Ship[NUMBER_OF_SHIPS];
    
            for (int i = 0; i < NUMBER_OF_SHIPS; i++)
            {
                ships[i] = randomlyPickShip();
    
                int randWidth = 0;
                int randHeight = 0;
                boolean validLocation = false;
                while (!validLocation)
                {
                    // Ships will always be horizontal to make it easier
                    // Randomly pick location - need to have room for whole ship
                    randWidth = (int) (Math.random() * (WIDTH - ships[i].getSize()));
                    randHeight = (int) (Math.random() * HEIGHT);
    
                    boolean shipInWay = false;
                    // make sure ship doesn't already exist
                    for (int k = randWidth; k < randWidth + ships[i].getSize()
                            && !shipInWay; k++)
                    {
                        if (cells[randHeight][k] instanceof Ship)
                        {
                            shipInWay = true;
                        }
                    }
                    if (!shipInWay)
                    {
                        validLocation = true;
                    }
                }
                ships[i].setStartLocation(randHeight, randWidth);
    
                for (int j = randWidth; j < randWidth + ships[i].getSize(); j++)
                {
                    cells[randHeight][j] = ships[i];
                    cellButtons[randHeight][j].setIcon(ships[i].displayCell(j));
                }
            }
        }
    
        public Ship randomlyPickShip()
        {
            // Randomly pick a number between 0 and 2 to chose type of ship
            int shipType = (int) (Math.random() * 3);
            Ship ship;
            switch (shipType)
            {
                case 0:
                    ship = new TugBoatGUI();
                    break;
                case 1:
                    ship = new SubmarineGUI();
                    break;
                default:
                    ship = new AirCraftCarrierGUI();
                    break;
            }
            return ship;
        }
    
        private class MyListener implements ActionListener
        {
                    
            public void actionPerformed(ActionEvent ae)
            {
                
                if (ae.getSource() == closeButton
                        || (ae.getSource() instanceof JMenuItem && ae
                                .getActionCommand().equalsIgnoreCase("Close")))
                {
                    System.exit(0);
                }
                else if (ae.getSource() == newGameButton
                        || (ae.getSource() instanceof JMenuItem && ae
                                .getActionCommand().equalsIgnoreCase("New Game")))
                {
                    resetBoard();
                }
                // else if (ae.getSource() == stopMe)
                // {
                // timer.stop();
                // }
                else
                {
                    boolean found = false;
                    for (int i = 0; i < cellButtons.length && !found; i++)
                    {
                        for (int j = 0; j < cells.length && !found; j++)
                        {
                            if (ae.getSource() == cellButtons[i][j])
                            {
                                if (!timer.isRunning())
                                {
                                    timer.start();
                                    
                                }
                                found = true;
                                cells[i][j].locationSelected(i, j);
                                cellButtons[i][j].setIcon(cells[i][j]
                                        .displayCell(j));
                                cellButtons[i][j].removeActionListener(this);
                                guessCounter++;
                                guessCounterLabel.setText(guessCounter + "");
                                checkAllShipsComplete(guessCounter);
                            }
                        }
                    }
                }
            }
    
        }
    
        private void resetBoard()
        {
            timer = new Timer(1000, this);
            
            timerSecond = 0;
            timerMinute = 0;
            guessCounter = 0;
    
            timeCounter = new JLabel("0:00");
            guessCounterLabel = new JLabel();
            //timer.stop();
    
            remove(rightPanel);
            remove(gridPanel);
    
            initRightPanel();
            initGridPanel();
    
            add(rightPanel, BorderLayout.EAST);
            add(gridPanel, BorderLayout.CENTER);
        }
    
        public boolean checkAllShipsComplete(int numberOfGuesses)
        {
            boolean allShipsComplete = true;
    
            for (int i = 0; i < NUMBER_OF_SHIPS && allShipsComplete; i++)
            {
                if (!ships[i].isComplete())
                {
                    allShipsComplete = false;
                }
            }
            if (allShipsComplete)
            {
    //            timer.stop();
                JOptionPane.showMessageDialog(null,
                        "Congratulations - you got them all! "
                                + "You needed to select " + numberOfGuesses
                                + " spaces to find all ships");
                
            }
    
            return allShipsComplete;
        }
    
        @Override
        public void actionPerformed(ActionEvent e)
        {
            String underTen = "";
            if (timerSecond < 10)
            {
                underTen = "0";
            }
            timeCounter.setText(timerMinute + ":" + underTen + timerSecond);
    
            timerSecond++;
            if (timerSecond != 0 && timerSecond % 60 == 0)
            {
                timerMinute++;
                timerSecond = 0;
            }
    
        }
    
    }

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    As I thought.... where do you call timer.stop()?

  5. #5
    Kinyo is offline Member
    Join Date
    Mar 2009
    Posts
    10
    Rep Power
    0

    Default

    I had it called in a few places but they either don't work or when the timer stops nothing else works because it stops the action listener

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Alright "TheSunshine", now you're confusing the heck out of me. How many fora are you posting these questions in??
    Last edited by Fubarable; 03-15-2009 at 12:39 AM.

  7. #7
    Kinyo is offline Member
    Join Date
    Mar 2009
    Posts
    10
    Rep Power
    0

    Default

    I have one in Eclipse, but thats all my problems. This Timer one is my biggest one so I tried posting it in here

    EDIT: I just clicked on the Sunshine link. I don't know who that is.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Sorry, but the posts just seemed very similar on superficial glance (including a Timer issue and panel names). Anyway, have you tried to change the reset method like so?
    Java Code:
      private void resetBoard() {
        if (timer.isRunning()) {
          timer.stop();
        }
        timer = new Timer(1000, this);
    The reason that this important is that creating a new Timer instance does not dispose or stop the old one. You have to do that yourself.

  9. #9
    Kinyo is offline Member
    Join Date
    Mar 2009
    Posts
    10
    Rep Power
    0

    Default

    I have tried to implement that in the resetBoard() but it either just freezes the program or it just don't work. Could you show me where to put it in?

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    I thought I just did. Anyway, I can't test it out in your code as there are too many classes that it depends on that I have no access to.

  11. #11
    Kinyo is offline Member
    Join Date
    Mar 2009
    Posts
    10
    Rep Power
    0

    Default

    That if statement does not fix it. If you want I can show the code for all the classes

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    I'd prefer that you make the effort to create an SSCCE (check out the link!). While this is a bit of work, creating one will often show you the error of your ways, and if it doesn't, it will at least allow you to post code that is of reasonable length for us to look at and debug.

  13. #13
    Kinyo is offline Member
    Join Date
    Mar 2009
    Posts
    10
    Rep Power
    0

    Default

    Never done a SSCCE and I dont have the time to make one either.

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Never done a SSCCE and I dont have the time to make one either.
    perhaps, but if you post all of your code and ask us to go through it, it's asking a lot of us to invest a lot of our time and effort go through a large amount of code. Is your time more valuable than ours? Please ask yourself this question: who should be putting in more effort to solve this problem, you, who are asking volunteers to help you for free, or us, the volunteers?

    My vote is that if you still require help, an SSCCE would be highly appreciated, would be a sign of respect and appreciation for those who might help you, and would likely get you help sooner than if you don't make one.

    Your choice.

  15. #15
    Kinyo is offline Member
    Join Date
    Mar 2009
    Posts
    10
    Rep Power
    0

    Default

    Well I am thankful for all the volunteers, but I dont know how to do a SSCCE and at the moment I have other things to worry about that that SSCCE, and if you or anyone else on this forum don't want to help. That is fine, I will just go else where.

  16. #16
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

Similar Threads

  1. Thread vs Timer
    By dawiz001 in forum Threads and Synchronization
    Replies: 5
    Last Post: 03-07-2009, 08:25 PM
  2. Running Timer
    By Doctor Cactus in forum New To Java
    Replies: 2
    Last Post: 12-26-2008, 09:24 AM
  3. EJB Timer
    By mrjunsy in forum Advanced Java
    Replies: 0
    Last Post: 08-22-2008, 04:09 PM
  4. EJB Timer
    By mrjunsy in forum New To Java
    Replies: 0
    Last Post: 08-04-2008, 06:47 PM
  5. Replies: 0
    Last Post: 04-04-2008, 02:46 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •