-1

I have three classes. The frame for menu of Game from which when play button, is pressed the class of frame containing Game should play.And the main class creates the object of Menu class.But the problem is that when I pressed play button it become white and after some times it says your score is 0 and Game is over. Please help me solve this problem I have tried every thing.

public class GameFrame extends JFrame implements KeyListener {

    protected int x;
    protected int y;
    private int a;
    private int b;
    protected int c;
    protected int d;
    protected int f;
    protected int k;
    private int h;
    private int i;
    private int s;

    GameFrame() {
        /*
         * setSize(760,700);
         * setLocation(200,25);
         * setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         * setResizable(false);
         * setVisible(true);
         */
        setLayout(null);
        c = 500;
        d = 530;

        a = 1;
        b = 1;
        x = 50;
        y = 250;

        f = 50;
        k = 700;
        h = 1;
        i = -1;

        s = 1;

        addKeyListener(this);
        setFocusable(true);
    }

    public void paint(Graphics g) {
        super.paint(g);
        Graphics g1 = (Graphics) g;
        g1.setColor(Color.DARK_GRAY);
        g1.fillRect(0, 0, 1200, getHeight());
        /*
         * g1.setColor(Color.blue);
         * g1.fillRect(0, 0, 850, getHeight());
         * g1.setColor(Color.green);
         * g1.fillRect(0, 0, 845, getHeight());
         * g1.setColor(Color.yellow);
         * g1.fillRect(0, 0, 840, getHeight());
         * g1.setColor(Color.red);
         */
        g1.fillRect(0, 0, 835, getHeight());
        g1.setColor(Color.gray);
        g1.fillRect(0, 0, 830, getHeight());
        g1.setColor(Color.BLACK);
        g1.fillRect(0, 0, 825, getHeight());

        g1.setColor(Color.red);
        g1.fillOval(x, y, 20, 20);

        g1.setColor(Color.GREEN);
        g1.fillOval(k, f, 20, 20);

        g1.setColor(Color.blue);
        g1.fillRect(c, d, 100, 15);
        g1.setColor(Color.red);
        g1.fillRect(300, 300, 90, 20);

        g1.setColor(Color.pink);
        g1.drawRect(0, 80, 760, 3);

        g1.setColor(Color.orange);
        g1.setFont(new Font(null, Font.BOLD, 20));
        g1.drawString("Your Score", 500, 60);
        g1.setFont(new Font(null, Font.BOLD, 25));
        g1.drawString("Credit:", 50, 60);
        g1.setFont(new Font(null, Font.BOLD, 20));
        g1.drawString("Mohsin Hussain", 150, 60);
        g1.drawString(String.valueOf(points()), 650, 60);
    }

    // Here is Run Method. From This Method Ball Will Move in Different Direction After Collision
    public void Run() {
        if (c < 0)
            c = 1;
        if (c > 740)
            c = 675;

        if (k < 0)
            i = s;
        if (k > 700)
            i = -s;
        k = k + i;
        if (f < 80)
            h = s;
        if ((f + 20 > d && k + 20 > c && f < d + 6 && k < c + 60))
            h = -s;
        f = f + h;

        if (x < 0)
            a = s;
        if (x > 700)
            a = -s;
        x = x + a;
        if (y < 80)
            b = s;
        if ((x > 300 && x < 380) && (y == 300) && b < 0) {
            b = s;
        }
        if ((x > 300 && x < 380) && (y == 300) && b > 0) {
            b = -s;
        }

        System.out.println(x);

        if ((y + 20 > d && x + 20 > c && y < d + 6 && x < c + 60))// Control the Direction as well
            // as Collision of the Grey Ball
            // From Rectangle
            b = -s;
        y = y + b;
        finish();// Call the Method of Finish

        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        repaint();
        Run();
    } // End Bracket of Run Method

    // Method of Points that Control the Score as well as Increase the Speed
    public int points() {
        if ((y + 20 > d && x + 20 > c && y < d + 6 && x < c + 60)
                        || (f + 20 > d && k + 20 > c && f < d + 6 && k < c + 60))
            s += 1;
        return s - 1;
    } // /End Bracket of Points Method

    // Method of Finish that Control Game Over Logic
    private void finish() {
        if (y > getHeight() - 20 || f > getHeight() - 20) {
            // Logic of Set Time at the End of the Game
            /*
             * GregorianCalendar date = new GregorianCalendar();
             * 
             * int day = date.get(Calendar.DAY_OF_MONTH); int month = date.get(Calendar.MONTH); int
             * year = date.get(Calendar.YEAR);
             * 
             * int second = date.get(Calendar.SECOND); int minute = date.get(Calendar.MINUTE); int
             * hour = date.get(Calendar.HOUR);
             * 
             * System.out.println("Ending Date of Game is   "+day+"/"+(month+1)+"/"+year);
             * System.out.println("Ending Time of Game is   "+hour+" : "+minute+" : "+second);
             */
            JOptionPane.showMessageDialog(this, "your Score is " + points(), "Game Over",
                            JOptionPane.YES_NO_OPTION);
            System.exit(ABORT);
        }// End Bracket of If Statement
    }

    public void keyPressed(KeyEvent arg0) {

        if (arg0.getKeyCode() == KeyEvent.VK_LEFT)
            c -= 25;
        if (arg0.getKeyCode() == KeyEvent.VK_RIGHT)
            c += 25;
    } // End of KeyPressed

    public void keyReleased(KeyEvent arg0) {} // End of KeyReleased

    public void keyTyped(KeyEvent arg0) {}// End of KeyTyped
}

The Frame containing the menu for the Game from where when we press play button the Game should start.

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class GameMenu extends JFrame {

    private JButton play;
    private JButton exit;
    private JButton about;
    private JButton credit;
    private ImageIcon img;
    private JLabel imgLabel;
    private JPanel panel;
    private float h = (float) 0.333;
    private float b = (float) 0.600;
    private float s = 1;
    boolean runCheck = false;
    public GameFrame frame;

    GameMenu() {
        setLayout(null);
        setResizable(false);

        panel = new JPanel();
        panel.setLayout(null);
        panel.setSize(760, 700);
        panel.setBackground(Color.getHSBColor(h, s, b));
        add(panel);
        play = new JButton("PLAY");
        play.setSize(100, 50);
        play.setLocation(360, 400);
        panel.add(play);

        about = new JButton("ABOUT");
        about.setSize(play.getSize());
        about.setLocation(play.getX(), play.getY() + play.getHeight() + 50);
        panel.add(about);

        exit = new JButton("EXIT");
        exit.setSize(play.getSize());
        exit.setLocation(about.getX() + about.getWidth() + 50, about.getY());
        panel.add(exit);

        credit = new JButton("CREDIT");
        credit.setSize(play.getSize());
        credit.setLocation(about.getX() - about.getWidth() - 50, about.getY());
        panel.add(credit);

        img = new ImageIcon("C:\\Users\\Ghulam Haider\\Downloads\\b.jpg");

        imgLabel = new JLabel(img);
        imgLabel.setSize(imgLabel.getPreferredSize());
        imgLabel.setLocation(230, 45);
        panel.add(imgLabel);
        mouseListener mouse = new mouseListener();
        Action action = new Action();
        play.addMouseListener(mouse);
    }

    private class Action implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {}
    }

    private class mouseListener implements MouseListener, Runnable {
        @Override
        public void mouseClicked(MouseEvent get) {}

        @Override
        public void mousePressed(MouseEvent e) {
            if (e.getSource() == play) {
                frame = new GameFrame();
                frame.setSize(760, 700);
                frame.setLocation(200, 25);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setResizable(false);
                frame.setVisible(true);
                frame.Run();
                // end of while
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {}

        @Override
        public void mouseEntered(MouseEvent e) {}

        @Override
        public void mouseExited(MouseEvent e) {}

        @Override
        public void run() {
            frame.Run();
            // end of while
        }
    }
}

and at last the main class which calls menu frame.

import javax.swing.JFrame;

public class RunGame {
    public static void main(String args[]) {
        GameMenu menu = new GameMenu();
        menu.setSize(760, 700);
        menu.setLocation(200, 25);
        menu.setVisible(true);
        menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
Tom
  • 16,842
  • 17
  • 45
  • 54
  • `panel.setLayout(null);` I highly recommend using an appropriate [LayoutManager](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html) – copeg Jun 01 '15 at 17:53
  • Is this your current code? Where is `GameFrame.run` called? – copeg Jun 01 '15 at 17:58
  • It is in the GameMenu Class.Inside the action listener. – Ghulam Haider Jun 01 '15 at 18:11
  • The `ActionListener` in `GameMenu` is an empty implementation. You call `frame.Run` in the `run` method (eg Runnable implementation), but I do not see where this is ever called. – copeg Jun 01 '15 at 18:13
  • 1) See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) 2) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Jun 01 '15 at 18:38
  • OK. thank you I will try this . – Ghulam Haider Jun 01 '15 at 19:09

2 Answers2

2

But the problem is that when I pressed play button it become white and after some times it says your score is 0 and Game is over.

You are calling the GameFrame.Run method on the EDT - Swing is single threaded, and all painting, events, etc.. run on the EDT. If you have something which blocks it (for instance calling Thread.sleep on the EDT as the GameFrame.Run method does) then none of these can occur. Instead, create a Thread or using a Timer

Some other suggestions:

  1. Don't paint to a JFrame - paint to a JPanel by overriding the paintComponent method.
  2. Avoid using null layouts. Choose the appropriate LayoutManager for the layout you seek.
  3. If looking for button clicks, use an ActionListener rather than MouseListener
  4. Class names should start with an uppercase (eg mouselistener), and method names with lowercase. Avoid any potential naming conflicts with API names
copeg
  • 8,290
  • 19
  • 28
  • I have tried all this and tried timer instead of thread.sleep It look like working and not showing white screen but it is now just open and say your score is zero and Game over. – Ghulam Haider Jun 01 '15 at 19:11
  • See other answer provided by @ReDMapLe027 – copeg Jun 01 '15 at 19:15
  • Presumably `finish` is being called prematurely - run your code through a debugger, or add println's in there to see why. This is a different question than your original, so consider asking a new question, but also keep in mind the suggestions in my answer above so they aren't rehashed again by someone else – copeg Jun 01 '15 at 19:23
0

Your if statement that contains finish() is not surrounded by brackets. Therefore after the it sees the condition it simply moves along and runs finish()

if((y+20>d&&x+20>c&&y<d+6&&x<c+60))//Control the Direction as well as Collision of the Grey Ball From Rectangle
b=-s;
y=y+b;
finish();//Call the Method of Finish

so everytime the run method is called it will terminate because finish() is also always called.

Try surrounding your if statement so that it only calls finish() if the statement is true. Or write a separate if statement where when the condition is met finish() is called.