Results 1 to 10 of 10
  1. #1
    Flopet17 is offline Member
    Join Date
    Mar 2014
    Posts
    60
    Rep Power
    0

    Unhappy JButton not working properly

    Hello guys,
    I have a game where is a bug and you have to shoot it. And once you shoot it the bug will splash so I added a slash image in the action listener.
    But when I click the button, the image is working but, the button goes again in the initial spot and I don't know why. Please someone explain.
    Here is the code:
    Java Code:
    package clickmegame3;
    
    public class ShootTheInsect {
    
        public static void main(String[] args) {
            
            //The first Frame, with the rules
            Start s = new Start();
            s.setVisible(true);
            
            //While the button is not clicked... The program waits...
            while( Start.av == false )
            {
                try {
                    Thread.sleep(100);
                } catch (Exception ex) {}
            }
            
            //Go through the levels of the game
            for(int i = 0; i<5; i++){
                
                //Each level rules
                LevelGameRules l = new LevelGameRules();
                l.setVisible(true);
                
                //While the button in LevelGameRule is not clicked... The program waits...
                while( LevelGameRules.clicked == false )
                {
                    try {
                        Thread.sleep(100);
                    } catch (Exception ex) {}
                }
                
                //Each level game
                Levels ls = new Levels();
                ls.setVisible(true);
                
                //If you wonned the level...
                if(Levels.won == true){
                    ls.setVisible(true);
                    try {
                        Thread.sleep(2500);
                    } catch (Exception ex) {}
                    ls.setVisible(false);
                    continue;
                }
                else
                    break;
            }
        }
    }
    Java Code:
    package clickmegame3;
    
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextArea;
    
    public class Start extends JFrame implements ActionListener{
        
        public static boolean av;//TEST IF THE BUTTON WAS CLICKED
        private JLabel l;
        private JButton b;
        private JTextArea ta;
        private Dimension dta, dl, db, center; // dl = dim label; db = dim button; center = set frame in the center of the screen;
        
        
        public Start(){
            
            //JFRAME
            setSize(350,250);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setTitle("Catch me Game!");
            
            //SET LAYOUT
            setLayout(new BorderLayout());
            setContentPane(new JLabel(new ImageIcon("/home/flopet17/Java/Home Practice/ClickMeGame3/src/clickmegame3/rsz_index.jpg")));
            
            //PUT JFRAME IN THE MIDDLE OF THE SCREEN
            center = Toolkit.getDefaultToolkit().getScreenSize();
            setLocation(center.width/2-getSize().width/2, center.height/2-getSize().height/2);
            
            //JLABEL
            l = new JLabel("<html>"
                    + "<i> Rules of the game: </i> <br> "
                    + "Shoot the insect!<br>"
                    + "There are 5 levels of the game: <br>"
                    + "<i>1. Elephant(30s-20score-speed:1s); <br>"
                    + "2. Tiger (30s-20score-speed:0.8s); <br>"
                    + "3. Kangaroo (20s-20score-speed:0.6s); <br>"
                    + "4. Lion (20s-20score-speed:0.4s); <br>"
                    + "5. Cheetah (30s-20score-speed:0.2s); <br> </i> "
                    + "To start the game click the button bellow: </p> </html>");
            
            l.setFont(new Font("Serif", Font.LAYOUT_NO_LIMIT_CONTEXT, 12));
            l.setForeground(Color.blue);
            
            //JBUTTON
            b = new JButton("Start!");
            
            //JTEXTAREA
            ta = new JTextArea("Enter Name");
            
            //DIMENSION
            dl = l.getPreferredSize();
            db = b.getPreferredSize();
            
            //SETBOUNDS
            l.setBounds(20, 10, dl.width, dl.height);
            b.setBounds(120, 180, db.width, db.height);
            ta.setBounds(120, 150, 100, 20);
            
            //ADD ACTIONLISTENER
            b.addActionListener(this);
            
            //ADD ELEMENTS TO FRAME
            add(l);
            add(ta);
            add(b);
        }
        
        
        public void actionPerformed(ActionEvent e) {
            if(e.getSource() == b){
                setVisible(false);
                av = true;
            }
        }
        
    }
    Java Code:
    package clickmegame3;
    
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    
    public class LevelGameRules extends JFrame implements ActionListener{
        
        private static JButton b;
        private JLabel l;
        private Dimension center;
        private static int level = 0;
        private int time, sec;
        private double speed;
        public static boolean clicked;
        
        public LevelGameRules(){
            //INCREMENT THE LEVEL
            level++;
            clicked = false;
            
            //TEST THE LEVELS
            if (level == 1)
            {
                time=20;
                sec=30;
                speed=1;
            }
            else if (level == 2)
            {
                time=20;
                sec=20;
                speed=0.8;
            }
            else if (level == 3)
            {
                time=20;
                sec=20;
                speed=0.7;
            }
            else if (level == 4)
            {
                time=10;
                sec=30;
                speed=0.5;
            }
            else if (level == 5)
            {
                time=20;
                sec=30;
                speed=0.4;
            }
            
            //JFRAME
            setSize(300,200);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setTitle("Level "+level);
            setLayout(new FlowLayout(FlowLayout.CENTER,50,20));
            
            //PUT JFRAME IN THE MIDDLE OF THE SCREEN
            center = Toolkit.getDefaultToolkit().getScreenSize();
            setLocation(center.width/2-getSize().width/2, center.height/2-getSize().height/2);
            
            //JLABEL
            l= new JLabel("<html>Level "+level+"!<br>"
                        + "To complete this level<br>"
                        + "Shoot the insect<br>"
                        + +time+" times in "+sec+" seconds;<br>"
                        + "speed="+speed+"</html>");
    
            //JBUTTON
            b = new JButton("Start!");
            b.addActionListener(this);
            
            //ADD BUTTON TO FRAME
            add(l);
            add(b);
            
            
        }
        public void actionPerformed(ActionEvent e) {
            if(e.getSource() == b){
                this.setVisible(false);
                clicked=true;
            }
        }
    }
    Java Code:
    package clickmegame3;
    
    import java.awt.Color;
    import java.awt.Cursor;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.text.DecimalFormat;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    
    public class Levels extends JFrame implements ActionListener{
        
        private int score, ran, ran1;
        private static int highscore = 0;
        private JButton b = new JButton();
        private JLabel l;
        private Dimension db, center;
        private ImageIcon icon = new ImageIcon("/home/flopet17/Java/Home Practice/ClickMeGame3/src/clickmegame3/bug.gif");
        private ImageIcon icon2 = new ImageIcon("/home/flopet17/Java/Home Practice/ClickMeGame3/src/clickmegame3/smashed.png");;
        private static float time;
        private static int speed;
        private static int level = 0;
        private float timeR=0f;
        public static boolean won; 
        private DecimalFormat f = new DecimalFormat("##.00");
        
        private void ChangeIcon() {
            b.setIcon(icon2);
        }
        
        public Levels(){
            //INCREMENT THE LEVEL
            score = 0;
            level++;
            won = false;
            
            //TEST THE LEVEL
            if (level == 1)
            {
                speed=1000;
                time=30000/speed;
                
            }
            else if (level == 2)
            {
                speed=800;
                time=30000/speed;
            }
            else if (level == 3)
            {
                speed=700;
                time=20000/speed;
            }
            else if (level == 4)
            {
                speed=500;
                time=20000/speed;
            }
            else if (level == 5)
            {
                speed=400;
                time=30000/speed;
            }
            
            timeR=1.0f*speed*time/1000.0f;
            
            //JFRAME
            setVisible(true);
            setSize(400,400);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setTitle("Level "+level);
            getContentPane().setBackground(Color.white);
            setLayout(new FlowLayout(FlowLayout.CENTER,50,20));
            
            //PUT JFRAME IN THE MIDDLE OF THE SCREEN
            center = Toolkit.getDefaultToolkit().getScreenSize();
            setLocation(center.width/2-getSize().width/2, center.height/2-getSize().height/2);
            
            //CHANGE CURSOR
            setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
            
            //JBUTTON
            b.setIcon(icon);
            b.setMargin(new Insets(0,0,0,0));
            b.setBorder(null);
            b.setBackground(Color.white);
            
            //DIMENSION
            db = b.getPreferredSize();
            b.setBounds(ran, ran1, db.width, db.height);
            
            //ADD BUTTON TO FRAME
            add(b);
                
            //ADD ACTIONLISTENER
            b.addActionListener(this);
            
            //GENERATE BUTTON IN DIFFERENT PLACES
            for(int i = 0; i<=time; i++)
            {   
                //RANDOM NUMBER GENERATED
                ran = (int) Math.floor(Math.random()*331);
                ran1 = (int) Math.floor(Math.random()*361);
                
                //BUTTON SET IN DIFFERENT PLACES
                b.setBounds(ran, ran1, db.width, db.height);
                b.setVisible(true);
                b.setIcon(icon);
               
                //SLEEP THE GAME
                try {
                    Thread.sleep(speed);
                }catch(Exception e){}
                
                //SET TITLE OF FRAME
                setTitle("Level " + level + " Score: " + score + " Time remaining: " + f.format(timeR)+"s");
                timeR=timeR-(speed/1000.0f);
            }
            //SCORE TEST
            if(score>=2)
            {
                b.setVisible(false);
                setTitle("Level "+level+" Complete!");
                setSize(400,130);
                
                //HIGHSCORE
                highscore += score;
                System.out.println("Highscore: "+highscore);
                
                //IF LEVEL = 5(FINAL LEVEL
                if (level == 5)
                    l = new JLabel("Congratulation you wonned the game!");
                
                //ELSE
                else
                    l= new JLabel("<html>Congratulation you reached the next level!<br>"
                            + "Total score= "+highscore+"</html>");
    
                //WON BUTTON CLICKED
                won=true;
            }
            
            //IF LOST GAME
            if(score<2){
                b.setVisible(false);
                setTitle("Try Again!");
                l= new JLabel("<html>Sorry, You Lost!<br>"
                        + " Try again!</html>");
            }
            add(l);
        }
        public void actionPerformed(ActionEvent e) {
                //INCREMENT THE SCORE
                score++;    
                
                ChangeIcon();
                
                //SET TITLE OF THE FRAME
                setTitle("Level " + level + " Score: " + score + " Time remaining: " + f.format(timeR)+"s");
        }
        
    }
    Thank you guys, again! :)

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,559
    Rep Power
    25

    Default Re: JButton not working properly

    button goes again in the initial spot
    Where is the button supposed to go? What variables control where the button goes? What code changes the value of those variables?

    Add some println statements to print out the value of the variables that are used to control the location of the button. Print a message showing their new value every time their value is changed. The print out will show you where the location is being set the way it is.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    Flopet17 is offline Member
    Join Date
    Mar 2014
    Posts
    60
    Rep Power
    0

    Default Re: JButton not working properly

    I used the setBounds to set the button to certain location. And as param. I used random.Math... Why when I click the button, in the Levels class, it goes in the ActionEvent and when the button change the image, the button goes in the first location... It makes no sense to me... If i comment out the ChangeIcon in the ActionEvent, everything goes well, the score increments everytime I click the button... But when I want to manipulate the button in the action event... something goes wrong, I can't understand why.

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,559
    Rep Power
    25

    Default Re: JButton not working properly

    something goes wrong, I can't understand why.
    Have you tried printing out the values as I suggested so you can see what is happening?
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    Flopet17 is offline Member
    Join Date
    Mar 2014
    Posts
    60
    Rep Power
    0

    Default Re: JButton not working properly

    I did printed out the ran(random) values... but they work properly... It's something else...

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,559
    Rep Power
    25

    Default Re: JButton not working properly

    Please post the output that shows the values that the jbutton location is set to.

    Does the printed output agree with where the JButton is shown on the GUI? If not please explain what the differences are.

    For example
    if the location is 1,1 is the button in the upper left
    if the location is 1, 300 is the button in the lower left
    Last edited by Norm; 04-02-2014 at 06:41 PM.
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    Flopet17 is offline Member
    Join Date
    Mar 2014
    Posts
    60
    Rep Power
    0

    Default Re: JButton not working properly

    Ran in for: 247 & Ran1 in for: 226
    "Ran in actionPerformed: 203 & Ran1 in actionPerformed: 25
    Ran in for: 203 & Ran1 in for: 25
    Ran in actionPerformed: 296 & Ran1 in actionPerformed: 317
    Ran in for: 296 & Ran1 in for: 317
    Ran in actionPerformed: 52 & Ran1 in actionPerformed: 303
    Ran in for: 52 & Ran1 in for: 303"

    Output when I put one println in the for and one println in the actionPerformed(When the bug is shooted);
    I think it does something if you use a button method in the actionPerformed... I don't know.

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,559
    Rep Power
    25

    Default Re: JButton not working properly

    Does the printed output agree with where the JButton is shown on the GUI?
    If not please explain what the differences are.

    Suggestion: the print outs don't need to be so wordy.
    for: ran=247 & Ran1= 226
    aP: ran=203 & Ran1=25

    You said:
    the button goes again in the initial spot
    Which are the values of the initial spot?
    Where do the values go back to the initial values?
    Last edited by Norm; 04-02-2014 at 08:18 PM.
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    Flopet17 is offline Member
    Join Date
    Mar 2014
    Posts
    60
    Rep Power
    0

    Default Re: JButton not working properly

    That is my question too... Because I can't find to see a place in the code where the button has initial spot declared... I think it has something to do with the Layout... no?
    I think that the button is positioned where the layout says... What do you think?

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,559
    Rep Power
    25

    Default Re: JButton not working properly

    I can't find to see a place in the code where the button has initial spot declared..
    You can get the button's position by call its getBounds() method.
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. Replies: 10
    Last Post: 05-07-2013, 08:34 PM
  2. setCaretPosition not working properly
    By phyzix5761 in forum AWT / Swing
    Replies: 6
    Last Post: 11-17-2012, 09:11 AM
  3. Properly buffering a custom JButton
    By Reskaillev in forum New To Java
    Replies: 2
    Last Post: 04-08-2012, 08:32 PM
  4. Help, I can't make the JButton to work properly
    By furieux in forum New To Java
    Replies: 11
    Last Post: 01-07-2012, 05:13 PM
  5. [SOLVED] JButton does not display ImageIcon properly
    By Singing Boyo in forum New To Java
    Replies: 1
    Last Post: 04-17-2009, 03:47 AM

Posting Permissions

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