0

So i have this project I'm working on where the user will get to choose between 5 games. Whenever I click on a button to play that game it wont load the game. Please help thanks in advance!

Main JFrame class:

import javax.swing.UIManager.LookAndFeelInfo;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;  
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.border.Border;
import java.io.RandomAccessFile;
import javax.swing.*;
import java.awt.BorderLayout;
import java.io.IOException;
import java.util.*;
import java.io.*;
public class JavaGames extends JFrame 
{
    private JMenuBar menuBar;
    public static int height;
    public static int width;
    private JTextField test;
    private JButton BrickBreaker;
    private JButton Exit;
    private JButton Trapped;
    private JButton PacMan;
    private JButton PinBall;
    private JButton Pong;
    private JTextField textfield1;
    private JPanel contentPane;
    public JavaGames() throws IOException
    {
        this.setTitle("Application Project");
        this.setSize(449,350);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        height = screenSize.height;
        width = screenSize.width;
        generateMenu();
        this.setJMenuBar(menuBar);
        contentPane = new JPanel(null);
        contentPane.setPreferredSize(new Dimension(500,400));
        contentPane.setBackground(new Color(192,192,192));
        BrickBreaker = new JButton();
        BrickBreaker.setBounds(108,69,95,35);
        BrickBreaker.setBackground(new Color(214,217,223));
        BrickBreaker.setForeground(new Color(0,0,0));
        BrickBreaker.setEnabled(true);
        BrickBreaker.setFont(new Font("SansSerif",0,11));
        BrickBreaker.setText("Brick Breaker");
        BrickBreaker.setVisible(true);
        BrickBreaker.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
               BrickBreaker(evt);
            }
        });
        Exit = new JButton();
        Exit.setBounds(219,175,95,35);
        Exit.setBackground(new Color(214,217,223));
        Exit.setForeground(new Color(0,0,0));
        Exit.setEnabled(true);
        Exit.setFont(new Font("sansserif",0,12));
        Exit.setText("Exit");
        Exit.setVisible(true);
        Exit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                Exit(evt);
            }
        });
        Trapped = new JButton();
        Trapped.setBounds(219,69,95,35);
        Trapped.setBackground(new Color(214,217,223));
        Trapped.setForeground(new Color(0,0,0));
        Trapped.setEnabled(true);
        Trapped.setFont(new Font("SansSerif",0,12));
        Trapped.setText("Trapped");
        Trapped.setVisible(true);
        Trapped.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                Trapped(evt);
            }
        });
        PacMan = new JButton();
        PacMan.setBounds(219,120,95,35);
        PacMan.setBackground(new Color(214,217,223));
        PacMan.setForeground(new Color(0,0,0));
        PacMan.setEnabled(true);
        PacMan.setFont(new Font("SansSerif",0,11));
        PacMan.setText("Pac Man Demo");
        PacMan.setVisible(true);
        PacMan.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                PacMan(evt);
            }
        });
        PinBall = new JButton();
        PinBall.setBounds(108,175,95,35);
        PinBall.setBackground(new Color(214,217,223));
        PinBall.setForeground(new Color(0,0,0));
        PinBall.setEnabled(true);
        PinBall.setFont(new Font("sansserif",0,12));
        PinBall.setText("Pin Ball");
        PinBall.setVisible(true);
        PinBall.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) 
            {
                try{
                PinBall(evt);
                }catch( IOException io ) {}
            }
        });
        Pong = new JButton();
        Pong.setBounds(108,120,95,35);
        Pong.setBackground(new Color(214,217,223));
        Pong.setForeground(new Color(0,0,0));
        Pong.setEnabled(true);
        Pong.setFont(new Font("sansserif",0,12));
        Pong.setText("Pong");
        Pong.setVisible(true);
        Pong.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                Pong(evt);
            }
        });
        textfield1 = new JTextField();
        textfield1.setBounds(160,12,100,49);
        textfield1.setBackground(new Color(255,255,255));
        textfield1.setForeground(new Color(0,0,0));
        textfield1.setEnabled(false);
        textfield1.setFont(new Font("SansSerif",0,18));
        textfield1.setText("Welcome!");
        textfield1.setVisible(true);
        contentPane.add(BrickBreaker);
        contentPane.add(Exit);
        contentPane.add(Trapped);
        contentPane.add(PacMan);
        contentPane.add(PinBall);
        contentPane.add(Pong);
        contentPane.add(textfield1);
        this.add(contentPane);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.pack();
        this.setVisible(true);  
    }
    public static String[] q = new String[1];
    private void BrickBreaker(ActionEvent evt) 
    {
        BrickGUI temp = new BrickGUI();
        temp.main(q);
    }
    private void Exit (ActionEvent evt) 
    {
        int n=0;
        System.exit(n);
    }
    private void Trapped(ActionEvent evt) 
    {
        TrappedGUI run = new TrappedGUI();
        run.main(q);
    }
    private void PacMan (ActionEvent evt) 
    {
        PacManGUI run = new PacManGUI();
        run.main(q);
    }
    private void PinBall (ActionEvent evt) throws IOException
    {
        PinBallGUI run = new PinBallGUI();
        run.main(q);
    }
    private void Pong (ActionEvent evt) 
    {
        PongGUI run = new PongGUI();
        run.main(q);
    }
    public void generateMenu()
    {
        menuBar = new JMenuBar();
        JMenu file = new JMenu("File");
        JMenu tools = new JMenu("Tools");
        JMenuItem openHS = new JMenuItem("High Scores");
        JMenuItem save = new JMenuItem("Save");
        JMenuItem exit = new JMenuItem("Exit");
        JMenuItem about = new JMenuItem("About");
        file.add(openHS);
        file.add(save);
        file.add(about);
        file.addSeparator();
        file.add(exit);
        menuBar.add(file);
        openHS.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0){
                //HighScores run = new HighScores();
               //run.main(q);
            }
        });
        exit.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0){
               int n = 0;
               System.exit(n);
            }
        });        
        about.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0){
                //about action
            }
        });  
     }
     public static void main(String[] args){
        System.setProperty("swing.defaultlaf",      "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try{
                new JavaGames();
                }catch( IOException io ) {}
            }
        });
    }
}

JFrame class to load the game:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class BrickGUI extends JFrame
{
    public BrickGUI() 
    {
        BrickGame gui = new BrickGame();
        this.setSize(600,600+20);
        this.setTitle("Brick Breaker");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
        this.getContentPane().add(new BrickGame());
        this.add(gui);
        gui.init(600,600);
        gui.start();
        gui.run();
    }
    public static void main(String[] args)
    {
        new BrickGUI();  
    }
}

Class where the game is drawn and such:

import java.awt.*;
import javax.swing.*;
import java.applet.*;
import java.util.*;
import java.io.*;
import java.awt.event.*;
import java.awt.event.KeyListener;
public class BrickGame extends JPanel implements Runnable,KeyListener
{    
    Thread runner; 
    private Image Buffer;
    private Graphics gBuffer;
    private char c = 'e';
    int width,height;
    BrickBall B1;
    ArrayList BrickBallList;
    BrickBall temp,temp2;
    ArrayList bricks;
    BrickRectangle rTemp;
    int bx,by,bw,bh;
    BrickRectangle R1,R2;
    boolean leftKey;
    boolean rightKey;
    boolean spaceKey;
    Paddle p;
    int points;
    public void init(int W,int H)
   {  
        width=590;
        height=590;
        Buffer=createImage(width,height);
        gBuffer=Buffer.getGraphics();
        B1 = new BrickBall(-1);
        p = new Paddle();
        bricks = new ArrayList();
        bx = 5;
        by = 5;
        bw = 20;
        bh = 10;
        int count = 0;
       for(int i = 0; i < 160;i++)
       {
           rTemp = new BrickRectangle(bx,by,bw,bh,0,0);
           bx = bx + 25;
           count++;
           if(count == 32)
           {
               by = by + 15;
               bx = 5;
               count = 0;
           }
        bricks.add(rTemp);
    }
    addKeyListener(this);
    points = 0;
}
public void start()
{ 
    if (runner == null)
    {   
        runner = new Thread (this);
        runner.start();
    }
}
public void stop()
{  
    runner = null;
}
public void run() 
{  
    while(true)
    {
        if(rightKey){p.moveRight();}
        if(leftKey){p.moveLeft();}
        repaint();
        try {runner.sleep(25);}
        catch (Exception e) { }    
        gBuffer.setColor(Color.black);
        gBuffer.fillRect(0,0,width,height);
        B1.moveBrickBall(width,height);
        p.ballCollision(B1);
        for(int j = 0; j < bricks.size();j++)
        {
             rTemp = (BrickRectangle)bricks.get(j);
             if(rTemp.BrickBallCollision(B1))
             {
                 bricks.remove(j);
                 points = points + 1;
                 break;
             }
        }
        String P = String.valueOf(points);
        gBuffer.setColor(Color.blue);
        gBuffer.setFont(new Font("Calibri",20,60));
        gBuffer.drawString(P,0,540);
        for(int i = 0; i < bricks.size();i++)
        {
            rTemp = (BrickRectangle)bricks.get(i);
            rTemp.paint(gBuffer);
        }
        B1.paint(gBuffer);
        p.paint(gBuffer);
        if(B1.getY()>height)
        {
            String s1 = "Game Over";
            String s2 = "You Lose!";
            String s3 = "You got " +points +" Points";
            String s4 = "Hit space key to continue";
            gBuffer.drawString(s1,50,90);
            gBuffer.drawString(s2,50,160);
            gBuffer.drawString(s3,50,230);
            gBuffer.setFont(new Font("Calibri",20,50));
            gBuffer.drawString(s4,50,300);
            BrickHS temp = new BrickHS();
            try{
                boolean t = temp.checkHS(points);
                if(t)
                {
                    gBuffer.drawString("New High Score",50,360);
                }
            }catch( IOException io ) {}
            if(spaceKey){System.exit(1);}
        }
        repaint();
    }//while(true)
} //run    
public void update(Graphics g)
{  
    paint(g);
} 
public void paint(Graphics g)
{
    g.drawImage(Buffer,0,0, this);
}
public void addNotify() 
{
    super.addNotify();
    requestFocus();
}
public void keyPressed(KeyEvent e) 
{
    switch(e.getKeyCode())
       {
           case KeyEvent.VK_LEFT:
           leftKey = true;
           break;
           case KeyEvent.VK_RIGHT:
           rightKey = true;
           break;
           case KeyEvent.VK_SPACE:
           spaceKey = true;
           break;
       }
}
public void keyReleased(KeyEvent e) 
{
    switch(e.getKeyCode())
       {
           case KeyEvent.VK_LEFT:
           leftKey = false;
           break;
           case KeyEvent.VK_RIGHT:
           rightKey = false;
           break;
           case KeyEvent.VK_SPACE:
           spaceKey = false;
           break;
        }
}
public void keyTyped(KeyEvent e) 
{
    c = e.getKeyChar();
    repaint();
}
}

There is also a few other classes that go with this game but those are mainly just to make the objects and what not. Again thanks in advance!

Zackc95
  • 11
  • 2
  • Don't run a game from the thread that invokes an event handler. Don't use the same name for a variable and a method. Don't use names starting with an upper class letter for variables. Don't call a static method in some class via an object of that class. – laune May 14 '15 at 20:38
  • 1
    That is a *lot* of code to ask volunteers to swim through - you might consider trimming it down to only the pieces that reproduce the issue you experience (eg an [MCVE](http://stackoverflow.com/help/mcve)) – copeg May 14 '15 at 20:44
  • See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) – Andrew Thompson May 14 '15 at 20:47

1 Answers1

2

Whenever a BrickGame is created, it enters into an infinite while loop by calling run - this is occurring on the Event Dispatch Thread (EDT) and leads to a frozen user interface as the EDT cannot paint, create events, etc... Your code starts a new thread by calling start - there is no reason for the additional call to run.

Some other pieces of advice:

  1. Override paintComponent rather than paint
  2. Call super.paintComponent as one of the first calls within the implementation in (1)
  3. You should not override update, nor addNotify
  4. Setting the reference of Thread to null will not stop the Thread - instead, use a flag which cases the while loop to terminate (this flag may need to be declared volatile).
  5. Variable names should start with a lower case letter.
  6. Avoid null layouts - use an appropriate LayoutManager
copeg
  • 8,290
  • 19
  • 28
  • I took out when it calls run and it works now! thanks so much for the advice and your help – Zackc95 May 14 '15 at 20:45
  • @Zackc95 Glad to hear it, but please don't forget to take the rest of the advice seriously - they can cause headaches beyond comparison to this one. – copeg May 14 '15 at 20:47