0

I'm making a Game like the typical BreakOut Game that uses Wheels Frame for the graphic part as the teacher requests. I am now trying to implement a MenuBar inside the game and haven´t been able to get it to work.

I have gotten as far as having the Menu in one window and the game in another one.

If someone has some idea of how I can make them stick together I would greatly appreciate it. Perhaps using a different type of menu of some sort.

   package granssnitt2;

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    import javax.swing.JMenuItem;

    import granssnitt.Game;

    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;

    public class Main extends Game implements ActionListener {

    public Main() {


        JFrame f = new JFrame("Menu Demo");
        f.setSize(220, 200);

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JMenuBar jmb = new JMenuBar();

        JMenu jmFile = new JMenu("File");
        JMenuItem jmiStart = new JMenuItem("Start");
        JMenuItem jmiRestart = new JMenuItem("Restart");
        JMenuItem jmiClose = new JMenuItem("Close");
        JMenuItem jmiExit = new JMenuItem("Exit");
        jmFile.add(jmiStart);
        jmFile.add(jmiRestart);
        jmFile.add(jmiClose);
        jmFile.addSeparator();
        jmFile.add(jmiExit);
        jmb.add(jmFile);


        JMenu jmHelp = new JMenu("Help");
        JMenuItem jmiAbout = new JMenuItem("Controlls");
        jmHelp.add(jmiAbout);
        jmb.add(jmHelp);

        jmiStart.addActionListener(this);
        jmiRestart.addActionListener(this);
        jmiClose.addActionListener(this);
        jmiExit.addActionListener(this);
        jmiAbout.addActionListener(this);


        f.setJMenuBar(jmb);
        f.setVisible(true);
    }
    public void actionPerformed(ActionEvent ae) 
    {

        String comStr = ae.getActionCommand();
        System.out.println(comStr + " Selected");
        if(comStr == "Start") handleStart(); 
        else if(comStr == "Restart") handleRestart();
        else if(comStr == "Close") handleClose(); 
        else if(comStr == "Exit") handleExit(); 
        else handleHelp(); 

    }

    private void handleStart()
    {
        // TODO Auto-generated method stub

    }
    private void handleRestart()
    {
        // TODO Auto-generated method stub

    }
    private void handleClose()
    {
        // TODO Auto-generated method stub

    }
    private void handleExit()
    {
        System.exit(0);     
    }
    private void handleHelp()
    {
        // TODO Auto-generated method stub

    }
    public static void main(String args[]) {
        new Main();
    }
}

The Game code uses a Frame from Wheels. Which I don´t know if it is possible to implement into JMenu/JFrame.

package granssnitt;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList; 
import java.util.List; 
import java.util.Random; 
import wheels.users.Frame;

public class Spel extends  Frame implements Moveable, KeyListener {
    private Rektangel ruta;
    private Rektangel ruta1;
    private Rektangel ruta2;
    private Rektangel ruta3;
    private Rektangel ruta4;
    //  private MyKeyListener nyckel;
    private Cirkel boll;
    List <Moveable> ritobjekt;
    List <Moveable> lista[];
    private Collidable collidables[];
    private final int BARSTARTX = 380; 
    private final int BARSTARTY =470;
    private final int BOLLSTARTX = 380; 
    private final int BOLLSTARTY =460;
    private final int STARTXHAST = 1;
    private final int STARTYHAST = 1;
    private Boll minBoll; 

    public void Game() {
        Frame._dp.addKeyListener(this);
        Frame._dp.setFocusable(true);
        //      Random rand = new Random();
        boolean koll=true;
        int i = 0, j = 0;
        boolean xflag = false, yflag = false;
        //ruta.move(RUTASTARTX, RUTASTARTY); 
        minBoll.move(BOLLSTARTX, BOLLSTARTY); 
        Random r = new Random();
        int x = r.nextInt(10);
        int y = r.nextInt(5);
        while (koll){

            if(xflag)
                i--;
            else
                i++;
            if(yflag)
                j--;
            else
                j++;
            minBoll.move(x+i,y+j);

            if(minBoll.getX()>Frame._dp.getWidth()){

                //this.minBoll.move((x+i)*-1,(y+i)*-1);
                xflag = true;
            }
            if(minBoll.getX()<0){
                //this.minBoll.move((x+i)*-1,(y+i)*-1);
                xflag = false;
            }

            if(minBoll.getX()==ruta1.getX())
                xflag=true;
            if(minBoll.getX()==ruta1.getY())
                xflag=false;

            if(minBoll.getY()>Frame._dp.getHeight()){
                //this.minBoll.move((x+i)*-1,(y+i)*-1);
                System.out.println("GAME OVER");
                minBoll.move(ruta.getX()+22,ruta.getY()-13);
                koll=false;


            }

            if(minBoll.getY()<0){
                if(minBoll.getY()==ruta1.getY())
                    //this.minBoll.move((x+i)*-1,(y+i)*-1);
                    yflag = false;
            }
            /*for(Collidable c: collidables)
                for(Collidable d: collidables)
                    if(c!=null) 
                        if(d!=null)
                            if(c!=d)
                                if(c.isCollision(d)) System.out.println("Krock mellan objekt " + c + " och " + d); */
            /*if(minBoll.getY()>480)
            {
            kolla=new empty();
            koll=false;
            }*/
            try { Thread.sleep(5);
            }
            catch (InterruptedException e) { 
            }


        }

    } 

    public Game() { 

        ruta = new Rektangel(BARSTARTX, BARSTARTY, 50, 10, Color.BLUE); 
        //boll = new Cirkel(20,30,10, Color.CYAN); 
        minBoll = new Boll(BOLLSTARTX, BOLLSTARTY, STARTXHAST, STARTYHAST); 
        ritobjekt = new ArrayList<Moveable>();
        ritobjekt.add(minBoll);
        ritobjekt.add(ruta);
        ritobjekt.add(ruta2);
        //      MyKeyListener nyckel= new MyKeyListener();
        Frame._dp.addKeyListener(this);
        collidables = new Collidable[100];
        //skapaCirklar(); 

        for(int n=2; n<22;n++ ){
            ruta1=new Rektangel(50+n*24, 70, 20, 10, Color.BLACK);
        }

        for(int n=2;n<22;n++)
        {
            ruta2=new Rektangel(50+n*24, 90, 20, 10, Color.orange);
            for(int t=22;t<42;t++){
                collidables[t]=this.ruta2;

            }
        }
        for(int n=2;n<22;n++)
        {
            ruta3=new Rektangel(50+n*24, 110, 20, 10, Color.pink);
            for(int t=42;t<62;t++){
                collidables[t]=this.ruta3;

            }
        }
        for(int n=2;n<22;n++)
        {
            ruta4=new Rektangel(50+n*24, 130, 20, 10, Color.cyan);
            for(int t=62;t<82;t++){
                collidables[t]=this.ruta4;


            }
        }

        collidables[0]=ruta;

        collidables[1]=boll; 

    }


    /*private void setRandomSpeed() {
        Random r = new Random();
        for(Moveable m: ritobjekt) { 
            minBoll.setxHast(r.nextInt(3)+1);
            minBoll.setyHast(r.nextInt(3)+1);
        }
    }*/

    @Override
    public void move(int x, int y) {
        // TODO Auto-generated method stub

    }

    @Override
    public void move() {
        // TODO Auto-generated method stub

    }

    @Override
    public void setxHast(int aSpeed) {
        // TODO Auto-generated method stub

    }

    @Override
    public void setyHast(int aSpeed) {
        // TODO Auto-generated method stub

    }

    @Override
    public int getxHast() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public int getyHast() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public int getX() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public int getY() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void keyTyped(KeyEvent e) {

        // TODO Auto-generated method stub

    }

    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode=e.getKeyCode();
        if(e.getKeyCode()==KeyEvent.VK_ESCAPE)
            System.out.println("yyoyoyo");
        else if(e.getKeyCode()==KeyEvent.VK_LEFT)
            ruta.move(ruta.getX() - 10 , ruta.getY());
        else if(e.getKeyCode()==KeyEvent.VK_RIGHT)
            ruta.move(ruta.getX() + 10 , ruta.getY());
        e.consume();
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub

    }


}

Any ideas would be appreciated. If I can make a simple Menu and get the game to start in the same window.

Thanks in advance! I have a lot of different classes. So, if requested I will post the code.

Redtama
  • 1,603
  • 1
  • 18
  • 35
  • 2
    Use a [`CardLayout`](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html) as shown in [this answer](http://stackoverflow.com/a/5786005/418556). – Andrew Thompson Dec 04 '15 at 15:43
  • 2
    *"I have alot of diffrent classes. So if requested I will post it."* A handy technique you should learn for later, is boiling a problem down to the minimum to figure out how to proceed. For example, instead of all this complexity, try to do it first with one panel that is red, and another that is blue. Even if you can't figure it out yourself, you'll have a [mcve] to show others. – Andrew Thompson Dec 04 '15 at 15:46
  • Where does the `wheels.users.Frame` class come from? Is there perhaps a jar file available publicly that contains this class and related classes? – Freek de Bruijn Dec 04 '15 at 17:02
  • Andrew Thompson. Thanks. Just started out with coding, and don't know really what to show and what not to show. And boiling it down to the minimum is hard in that case. But Ill keep that in mind thanks! The wheels.users.Frame comes from here: http://wps.aw.com/aw_sanders_oopjava_1/36/9390/2403930.cw/index.html It was provided by the teacher so we use the graphical part from there. So we learn more how to build it are selves. – Magnus Cristiansson Dec 04 '15 at 17:34

2 Answers2

0

The javax.swing.JFrame API documentation provide a lot of methods you can use to customize a frame so you don't need to use an existing frame e.g. wheels this will really simplify your work.Try implementing MVC(Model View Control Design Pattern), that is, let the actual logic behind you game be in a separate java class file and the the GUI building code be in another java class file then you can link the two by means of instantiating. Let the actions in the game be functions which you can invoke when events are triggered by users' interaction with the GUI components e.g. if buttonA is clicked you can have the following code in the GUI class

buttonA.addActionListener(
          new ActionListener(){
              public void actionPerformed(ActionEvent event){
                      //then call a function from the class  with the
                      // module that should follow this event

                       jtextField.setText(logicClass.getCurrentScores())[1];                       
              }
          }
); 

You can learn more here

Hey and good-luck developing the game, all the best

Frakcool
  • 10,915
  • 9
  • 50
  • 89
Samuel Owino
  • 747
  • 1
  • 12
  • 24
0

From looking at the Frame JavaDocs and the Frame.java code, I get the impression that adding a menu would require some trickery:

" The JFrame is actually contained by the class instead of subclassed so that the frame can be updated (packed) when components are added."

The Frame class has a JFrame as its private field (private static JFrame _frame;), which makes it hard to add a menu bar to it like you did in your example (by calling the JFrame.setJMenuBar method). You might want to check with your teacher whether this is the preferred approach or if there is an alternative way.

You could for example use the Wheels components to create a different way to start a game (and do other actions). Maybe you can use an Image or ConversationBubble component where you respond to mouse click events:

Screenshot with example image and conversation bubble

import java.awt.event.MouseEvent;
import wheels.users.*;

public class TestWheels extends Frame {
    public static void main(String[] arguments) {
        new TestWheels().run();
    }

    private void run() {
        Image startImage = new Image("[some path]/start.png") {
            @Override
            public void mouseClicked(MouseEvent mouseEvent) {
                System.out.println("Start the game (via the image)...");
            }
        };
        startImage.setLocation(80, 40);

        // Note: the mouse click event does not occur when you click the text in
        // the conversation bubble.
        ConversationBubble conversationBubble = new ConversationBubble("") {
            @Override
            public void mouseClicked(MouseEvent mouseEvent) {
                System.out.println("Start the game (via the conversation bubble)...");
            }
        };
        conversationBubble.setLocation(300, 28);
        conversationBubble.setSize(200, 40);
        conversationBubble.setText("Let's start a game...");
    }
}

Note: the mouse click event does not occur when you click on the text in the conversation bubble, which makes it confusing and less suiteble as a "button".

Good luck with your project!

Freek de Bruijn
  • 3,552
  • 2
  • 22
  • 28