Results 1 to 14 of 14
  1. #1
    Addez is offline Senior Member
    Join Date
    Aug 2009
    Posts
    294
    Rep Power
    0

    Default Timer stops working :P

    Hello!

    I got a JFrame with a jpanel on.
    On that JPanel I got a JButton.
    Click that button and the jpanel should get removed then
    a "startGame" method would be executed so that
    another JPanel comes up and then a timer starts that controls the game.

    Now everything works, except the timer.

    The code execute and is finished beyon the last time which is
    timer.start()

    Yet, the actionPreformed method is never executed..
    Any idea why?

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

    Default

    Quote Originally Posted by Addez View Post
    Hello!

    I got a JFrame with a jpanel on.
    On that JPanel I got a JButton.
    Click that button and the jpanel should get removed then
    a "startGame" method would be executed so that
    another JPanel comes up and then a timer starts that controls the game.

    Now everything works, except the timer.

    The code execute and is finished beyon the last time which is
    timer.start()

    Yet, the actionPreformed method is never executed..
    Any idea why?
    You've got a bug in your code, but what this bug is is anybody's guess.

    edit: Looks like JosAH found it. Nice catch -- and I thought we'd need to see code to solve this. Here's where @Override can make a big difference in catching the error early.
    Last edited by Fubarable; 09-21-2010 at 04:20 PM.

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,344
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Addez View Post
    Yet, the actionPreformed method is never executed..
    Any idea why?
    Because the name is "actionPerformed"; I make that mistake more often than not myself.

    kind regards,

    Jos

  4. #4
    Addez is offline Senior Member
    Join Date
    Aug 2009
    Posts
    294
    Rep Power
    0

    Default

    I see.
    So I made two small code peices that illustrate how this problem appears:

    Heres code for the java file "MainClass":
    PHP Code:
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    class GameFrame extends JFrame {
        public GameFrame(){
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(1000,700);
            setTitle("Heli Challenge");
            //getContentPane().setBackground(Color.BLACK);
            this.setResizable(false);
            //pack();
            //setSize(1000,700);
            setVisible(true);
        }
    }
    
    
    public class MainClass {
        public static GameFrame gf;
        static int fps = 30;
        static boolean ok = true;
        
        public static void main(String arg[]){
            gf = new GameFrame();
            Menu.init(gf);
        }
        
        
        static void startGame(){
            
            paintIt p = new paintIt();
            gf.add(p);
            
            System.out.println("4");
            MyTimerActionListener acl = new MyTimerActionListener();
            javax.swing.Timer timer = new javax.swing.Timer(1000/fps,acl);
            System.out.println("5");
            timer.start();
            //wait(2);
            System.out.println("6");
            
            while (ok){wait(1);}
            System.out.println("END OF GAME");
        }
        private static void wait(int time){
            try{
                Thread.sleep(time*1000);
            } catch(Exception e){}
        }
    }
    
    
    class MyTimerActionListener implements ActionListener {
        long startTime = 0;
        //float currentTime = 
        boolean add = false;
        @Override
          public void actionPerformed(ActionEvent e) {
              System.out.println("Update");
              
              MainClass.gf.repaint();
          }
    }
    
    
    class paintIt extends JPanel{
        public void paintComponent(Graphics g){
    
            super.paintComponent(g);
            //fade(200,50,600,200,new Color(0,0,0),new Color(0,255,0),10,g,10);
            g.setColor(Color.cyan);
            
            
            g.setColor(Color.green);
            g.drawRect(199,49,601,201);
    
            
            g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 80));
            g.setColor(new Color(255,255,0));
            g.drawString("Game",230,130);
            g.drawString("Window",230,220);
            
        }
    
    }
    Here is for the "Menu" java file:
    PHP Code:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    
    
    
    public class Menu {
        public static void init(GameFrame gf){
            //gf.setLayout(new GridLayout(0,1, 1, 1));
            JPanel t = new title();
            t.setBackground(Color.BLACK);
            t.setLayout(new GridBagLayout());
            gf.add(t);
            
            
            addButtons(t);
            gf.repaint();
        }
        private static void addButtons(JPanel t) {
            Dimension d = new Dimension(220,30);
            GridBagConstraints c = new GridBagConstraints();
            c.weightx = 0;
            c.anchor = GridBagConstraints.CENTER;
            c.insets = new Insets(10,0,0,0);
            
            JButton b = new JButton("PLAY");
            /*JPanel p = new JPanel();
            p.setBackground(Color.blue);
            b.add(p);*/
            b.addActionListener(new Action());
            b.setPreferredSize(d);
            t.add(b,c);
            
            JButton b2 = new JButton("Exit");
            b2.setPreferredSize(d);
            c.gridy = 1 ;
            t.add(b2,c);
        }
    }
    
    class Action implements ActionListener{
        public void actionPerformed(ActionEvent e){
            String text = e.getSource().toString();
            int start = text.indexOf("text=")+5;
            String name =  text.substring(start).split(",")[0]; //text.substring(start,end);
            System.out.println(name);
            if (name.equals("PLAY")){
                MainClass.gf.removeAll();
    
                MainClass.startGame();
                MainClass.gf.validate();
                MainClass.gf.repaint();
            }
        }
    }
    
    
    class title extends JPanel{
        public void paintComponent(Graphics g){
    
            super.paintComponent(g);
            //fade(200,50,600,200,new Color(0,0,0),new Color(0,255,0),10,g,10);
            g.setColor(Color.cyan);
            
            
            g.setColor(Color.green);
            g.drawRect(199,49,601,201);
    
            
            g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 80));
            g.setColor(new Color(255,255,0));
            g.drawString("Heli",230,130);
            g.drawString("Challenge",230,220);
            
        }
    
    }
    Run the MainClass and you will see that it doesnt work well..

    Any ideas now?

  5. #5
    Addez is offline Senior Member
    Join Date
    Aug 2009
    Posts
    294
    Rep Power
    0

    Default

    I see!
    Its the while(true){wait(1) thingy!!
    But then I got another problem.

    I removed that one.
    Now why doesnt the new JPanel gets displayed?

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,305
    Rep Power
    25

    Default

    you will see that it doesnt work well
    Before anyone tries all that, can you give an explanation of what you see happen and what is wrong with it?

  7. #7
    Addez is offline Senior Member
    Join Date
    Aug 2009
    Posts
    294
    Rep Power
    0

    Default

    Ohyea :P
    How foolish of me to forget that -.-

    REMEMBER:
    First delete this line:
    Java Code:
    while (players.size()>0){wait(1);}
    Well, when you run this, then you see a display with play and exit button
    Clicking play button makes the button stay pressed.

    What it should do, is create a new JPanel called paintIt
    This should then render on the jframe the words:
    Game
    Window

    But it does not change to that jpanel for some reason I do not understand..

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

    Default

    Whenever you add or remove a component from a container, you should call revalidate and repaint on that container (in this case, the JFrame's contentPane cast as a JPanel). Then if you still don't see a component, ask yourself what size it is, and in fact I'd use a println statement to show me the size (which is [0, 0]).

    But nevermind all that, since what you want to do is swap JPanels, and for that I'd simplify things by using a CardLayout which is built to do just this.

    Also, you'll want to get rid of all the static fields and methods except for the main method.
    Last edited by Fubarable; 09-21-2010 at 05:00 PM.

  9. #9
    Addez is offline Senior Member
    Join Date
    Aug 2009
    Posts
    294
    Rep Power
    0

    Default

    Yeaa...
    Those static things are from the real program.
    I didnt cut very nice when making the tryout example..

    But now I used your card layout, and it works GREAT! :D
    Really nice solution ty :P

    Only one TINY lil problem left..

    When I switched windows, I attach a keylistener to the GameFrame.
    But I do not longer recive keystrokes...

    Should I delete previous listeners or something before switching windows?

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

    Default

    Quote Originally Posted by Addez View Post
    Yeaa...
    Those static things are from the real program.
    I didnt cut very nice when making the tryout example..
    They shouldn't be in the real program. :)


    But now I used your card layout, and it works GREAT! :D
    Really nice solution ty :P
    Glad it worked.

    Only one TINY lil problem left..

    When I switched windows, I attach a keylistener to the GameFrame.
    But I do not longer recive keystrokes...

    Should I delete previous listeners or something before switching windows?
    First off, you should avoid using key listeners if you can for several reasons, since they require focus. KeyBinding would work better.

    For what it's worth, I created a small CardLayout example, but looks like you've already fixed your problem. Anyway...
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class MainClass2 extends JPanel {
       private static final Dimension APP_SIZE = new Dimension(700, 500);
       private CardLayout cardlayout = new CardLayout();
       private IntroPanel introPanel = new IntroPanel();
       private GamePanel gamePanel = new GamePanel();
       
       public MainClass2() {
          introPanel.setPlayAction(new SwapAction("Play Game", GamePanel.GAME_PANEL, this));
          gamePanel.setBackToIntroAction(new SwapAction("Back to Intro", IntroPanel.INTRO_PANEL, this));
          
          setLayout(cardlayout);
          setPreferredSize(APP_SIZE);
          add(introPanel, IntroPanel.INTRO_PANEL);
          add(gamePanel, GamePanel.GAME_PANEL);
       }
       
       public void swapView(String name) {
          cardlayout.show(this, name);
       }
    
       private static void createAndShowUI() {
          JFrame frame = new JFrame("MainClass2");
          frame.getContentPane().add(new MainClass2());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }
    
    @SuppressWarnings("serial")
    class IntroPanel extends JPanel {
       public static final String INTRO_PANEL = "Intro Panel";
       private JButton playButton = new JButton();
       
       public IntroPanel() {
          JButton exitBtn = new JButton("Exit");
          exitBtn.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                Window window = SwingUtilities.getWindowAncestor(IntroPanel.this);
                window.dispose();
             }
          });
          
          JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 0, 10));
          buttonPanel.setOpaque(false);
          buttonPanel.add(playButton);
          buttonPanel.add(exitBtn);
          
          setBackground(Color.black);
          setLayout(new GridBagLayout());
          add(buttonPanel);
       }
       
       public void setPlayAction(javax.swing.Action action) {
          playButton.setAction(action);
       }
       
    }
    
    @SuppressWarnings("serial")
    class GamePanel extends JPanel {
       public static final String GAME_PANEL = "Game Panel";
       private JButton backToIntroBtn = new JButton();
       
       public GamePanel() {
          JPanel centerPanel = new JPanel(new GridBagLayout());
          centerPanel.add(new JLabel(GAME_PANEL));
          JPanel bottomPanel = new JPanel();
          bottomPanel.add(backToIntroBtn);
          
          setLayout(new BorderLayout());
          add(centerPanel, BorderLayout.CENTER);
          add(bottomPanel, BorderLayout.SOUTH);
       }
       
       public void setBackToIntroAction(javax.swing.Action action) {
          backToIntroBtn.setAction(action);
       }
    }
    
    @SuppressWarnings("serial")
    class SwapAction extends AbstractAction {
       private MainClass2 main;
       private String cardlayoutKey;
       
       public SwapAction(String buttonName, String cardlayoutKey, MainClass2 main) {
          super(buttonName);
          this.main = main;
          this.cardlayoutKey = cardlayoutKey;
       }
       
       @Override
       public void actionPerformed(ActionEvent e) {
          main.swapView(cardlayoutKey);
       }
    }

  11. #11
    Addez is offline Senior Member
    Join Date
    Aug 2009
    Posts
    294
    Rep Power
    0

    Default

    Ahh, yeaa the card problem was already solved :P
    But I appriciate your effort, I really do :)

    As for the keybindings..
    Im on it! :D

  12. #12
    Addez is offline Senior Member
    Join Date
    Aug 2009
    Posts
    294
    Rep Power
    0

    Default

    Okaj, so now I created these keybindings..
    Tho they do not really work/I dont know how to work them :P

    When the cards are switched to the game jpanel then I do this:
    Java Code:
    panels.getActionMap().put(KeyStroke.getKeyStroke("a"),new ActionDone());
    where the AcitonDone is here:
    Java Code:
    class ActionDone implements Action{
    
        @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub
            System.out.println(arg0.getSource().toString());
        }
    
        @Override
        public void addPropertyChangeListener(PropertyChangeListener arg0) {
            // TODO Auto-generated method stub
            
        }
    
        
    
        @Override
        public boolean isEnabled() {
            // TODO Auto-generated method stub
            return false;
        }
    
        @Override
        public void putValue(String arg0, Object arg1) {
            // TODO Auto-generated method stub
            
        }
    
        @Override
        public void removePropertyChangeListener(PropertyChangeListener arg0) {
            // TODO Auto-generated method stub
            
        }
    
        @Override
        public void setEnabled(boolean arg0) {
            // TODO Auto-generated method stub
            
        }
    
        @Override
        public Object getValue(String key) {
            // TODO Auto-generated method stub
            return null;
        }
        
    }
    But it doesnt print anything when I click a.
    How come?

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

    Default

    That's not how you use key bindings. First you need to get the proper input map, then you use the put method of the input map to associate a key stroke with a String. Then you use the put method of the action map to associated the String with an Action. For example:

    Java Code:
          int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
          InputMap inMap = getInputMap(condition);
          ActionMap actMap = getActionMap();
          
          String keyPressA = "Key Press A";
          inMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), keyPressA);
          actMap.put(keyPressA, new ActionDone());

    and
    Java Code:
    class ActionDone extends AbstractAction {
       @Override
       public void actionPerformed(ActionEvent e) {
           System.out.println("Action Command: " + e.getActionCommand());
       }
    }
    Last edited by Fubarable; 09-21-2010 at 08:47 PM. Reason: corrected

  14. #14
    Addez is offline Senior Member
    Join Date
    Aug 2009
    Posts
    294
    Rep Power
    0

Similar Threads

  1. Check difference between no. of stops, calculate cost
    By JavaStudent23 in forum New To Java
    Replies: 1
    Last Post: 11-14-2009, 04:03 PM
  2. sound works then stops!
    By smileii in forum CLDC and MIDP
    Replies: 0
    Last Post: 09-26-2009, 12:06 AM
  3. Stops when opening ObjectInputStream
    By Norberhuis in forum Networking
    Replies: 4
    Last Post: 01-09-2009, 04:19 PM
  4. Replies: 0
    Last Post: 04-04-2008, 02:46 PM
  5. Bouncing Ball Just Suddenly Stops Mid Bounce
    By adlb1300 in forum Java 2D
    Replies: 1
    Last Post: 12-03-2007, 02:58 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
  •