5

I am writing a program for a black jack game. It is an assignment we are not to use gui's but I am doing it for extra credit I have created two frames ant they are working. On the second frame I want to be able to switch back to the first when a button is pressed. How do I do this?

first window.............

import javax.swing.* ;
import java.awt.event.* ;
import java.awt.* ;
import java.util.* ;


public class BlackJackWindow1 extends JFrame implements ActionListener
{
  private JButton play = new JButton("Play");
  private JButton exit = new JButton("Exit");
  private JPanel pane=new JPanel();
  private JLabel lbl ;

  public BlackJackWindow1()
  {
    super();
    JPanel pane=new JPanel();
    setTitle ("Black Jack!!!!!") ;
    JFrame frame = new JFrame("");

    setVisible(true);
    setSize (380, 260) ;
    setLocation (450, 200) ;
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) ;

    setLayout(new FlowLayout());
    play = new JButton("Start");
    exit = new JButton("exit");
    lbl = new JLabel ("Welcome to Theodores Black Jack!!!!!");

    add (lbl) ;
    add(play, BorderLayout.CENTER);
    play.addActionListener (this);
    add(exit,BorderLayout.CENTER);
    exit.addActionListener (this);
  }
  @Override
  public void actionPerformed(ActionEvent event)
  {
    // TODO Auto-generated method stub
    BlackJackWindow2 bl = new BlackJackWindow2();
    if (event.getSource() == play)
    {
      bl.BlackJackWindow2();
    }
    else if(event.getSource() == exit){
      System.exit(0);
    }
  }

second window....

import javax.swing.* ;

import java.awt.event.* ;
import java.awt.* ;
import java.util.* ;

public class BlackJackWindow2 extends JFrame implements ActionListener
{
  private JButton hit ;
  private JButton stay ;
  private JButton back;
  //private JLabel lbl;

  public void BlackJackWindow2() 
  {
    // TODO Auto-generated method stub
    JPanel pane=new JPanel();
    setTitle ("Black Jack!!!!!") ;
    JFrame frame = new JFrame("");

    setVisible(true);
    setSize (380, 260) ;
    setLocation (450, 200) ;
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) ;

    setLayout(new FlowLayout());
    hit = new JButton("Hit");  
    stay = new JButton("stay");
    back = new JButton("return to main menu");

    // add (lbl) ;
    add(hit, BorderLayout.CENTER);  
    hit.addActionListener (this) ;
    add(stay,BorderLayout.CENTER);
    stay.addActionListener (this) ;
    add(back,BorderLayout.CENTER);
    back.addActionListener (this) ;
  }

  @Override
  public void actionPerformed(ActionEvent event) 
  {
    // TODO Auto-generated method stub
    BlackJackWindow1 bl = new BlackJackWindow1();
    if (event.getSource() == hit)
    {
      //code for the game goes here i will complete later
    }
    else if(event.getSource() == stay){
      //code for game goes here i will comeplete later.
    }
    else 
    {
      //this is where i want the frame to close and go back to the original.
    }
  }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
namdizy
  • 49
  • 1
  • 1
  • 4

3 Answers3

5

The second frame needs a reference to the first frame so that it can set the focus back to the first frame.

Also your classes extend JFrame but they are also creating other frames in their constructors.

jzd
  • 23,473
  • 9
  • 54
  • 76
  • i searched and i found that i could just do this. setVisible(false); dispose(); on the else statement and it closes the frame and returns to the original frame and in the original frame i do the same after the call for the second window, it seems to work. what do you think? – namdizy Apr 14 '11 at 20:06
  • What if your user minimizes the first frame? Do you really want to close the second frame? It sounds like you should be using a modal dialog if that is really what you are after. – jzd Apr 14 '11 at 20:14
  • i'll check on the modal dialog. If my user is on the first frame and pressed the "start" button it goes to the second frame and closes the first one, then when the "return to menu" button is pressed it closes the second frame and returns to the first one. so both frames are not open at the same time. – namdizy Apr 14 '11 at 20:23
  • 2
    @illbliss, why not just change the content on one screen instead of opening and closing frames? – jzd Apr 15 '11 at 11:17
3

A couple of suggestions:

You're adding components to a JPanel that uses FlowLayout but are using BorderLayout constants when doing this which you shouldn't do as it doesn't make sense:

  add(play, BorderLayout.CENTER);

Rather, if using FlowLayout, just add the components without those constants.

Also, rather than swap JFrames, you might want to consider using a CardLayout and swapping veiws in a single JFrame. For instance:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class FooBarBazDriver {
   private static final String INTRO = "intro";
   private static final String GAME = "game";
   private CardLayout cardlayout = new CardLayout();
   private JPanel mainPanel = new JPanel(cardlayout);
   private IntroPanel introPanel = new IntroPanel();
   private GamePanel gamePanel = new GamePanel();

   public FooBarBazDriver() {
      mainPanel.add(introPanel.getMainComponent(), INTRO);
      mainPanel.add(gamePanel.getMainComponent(), GAME);

      introPanel.addBazBtnActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            cardlayout.show(mainPanel, GAME);
         }
      });

      gamePanel.addBackBtnActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            cardlayout.show(mainPanel, INTRO);
         }
      });
   }

   private JComponent getMainComponent() {
      return mainPanel;
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("Foo Bar Baz");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new FooBarBazDriver().getMainComponent());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

class IntroPanel {
   private JPanel mainPanel = new JPanel();
   private JButton baz = new JButton("Baz");
   private JButton exit = new JButton("Exit");

   public IntroPanel() {
      mainPanel.setLayout(new FlowLayout());
      baz = new JButton("Start");
      exit = new JButton("exit");

      mainPanel.add(new JLabel("Hello World"));
      mainPanel.add(baz);
      mainPanel.add(exit);

      exit.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            Window win = SwingUtilities.getWindowAncestor(mainPanel);
            win.dispose();
         }
      });
   }

   public void addBazBtnActionListener(ActionListener listener) {
      baz.addActionListener(listener);
   }

   public JComponent getMainComponent() {
      return mainPanel;
   }

}

class GamePanel {
   private static final Dimension MAIN_SIZE = new Dimension(400, 200);
   private JPanel mainPanel = new JPanel();

   private JButton foo;
   private JButton bar;
   private JButton back;

   public GamePanel() {
      foo = new JButton("Foo");
      bar = new JButton("Bar");
      back = new JButton("return to main menu");

      mainPanel.add(foo);
      mainPanel.add(bar);
      mainPanel.add(back);
      mainPanel.setPreferredSize(MAIN_SIZE);
   }

   public JComponent getMainComponent() {
      return mainPanel;
   }

   public void addBackBtnActionListener(ActionListener listener) {
      back.addActionListener(listener);
   }

}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
2

Since I had to test it myself if it is in fact so easy to implement, I built this simple example. It demonstrates a solution to your problem. Slightly inspired by @jzd's answer (+1 for that).

import java.awt.Color;
import java.awt.HeadlessException;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class FocusChangeTwoFrames
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() 
        {
            @Override
            public void run()
            {   
                createGUI();
            }
        });
    }

    private static void createGUI() throws HeadlessException
    {
        final JFrame f2 = new JFrame();
        f2.getContentPane().setBackground(Color.GREEN);     
        final JFrame f1 = new JFrame();     
        f1.getContentPane().setBackground(Color.RED);
        f1.setSize(400, 300);
        f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f1.setVisible(true);
        MouseListener ml = new MouseAdapter()
        {
            @Override
            public void mousePressed(MouseEvent e)
            {
                if(f1.hasFocus())
                    f2.requestFocus();
                else
                    f1.requestFocus();
            }
        };
        f1.addMouseListener(ml);
        f2.setSize(400, 300);
        f2.setLocation(200, 150);
        f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f2.setVisible(true);
        f2.addMouseListener(ml);
    }
}

Enjoy, Boro.

Boro
  • 7,913
  • 4
  • 43
  • 85