bobthebuilder
bobthebuilder

Reputation: 119

How to make a class run after two buttons are pressed

I am making my first game, and the last time I asked this question, I kinda didn't explain it very well. Basically, below is the opening screen of the game. I know, not very good, but it is just a rough draft. Then I also built the game. There are two buttons in the opening screen, for it is a 2 player game. Both players must click ready, and then I want to program to end, and to start the second program. However I'm not sure how to do that.

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;
public class OpeningScreen {
    JFrame frame;
    JPanel main;
    JButton ready1;
    JButton ready2;
    JPanel bottom;
    JLabel label;
public OpeningScreen(){
    UIManager.put("Button.background", Color.cyan);
    UIManager.put("Button.foreground", Color.magenta);

    UIManager.put("ToolTip.background", Color.magenta);
    frame=new JFrame("Super Tuesday");
    main=new JPanel();
    ready1=new JButton("CLICK IF READY");
    ready2=new JButton("CLICK IF READY");
    label=new JLabel("SUPER TUESDAY");
    bottom=new JPanel();
    label.setFont(label.getFont().deriveFont(50.0f));
    frame.setSize(480, 800);
    frame.setLayout(new BorderLayout());
    frame.add(main, BorderLayout.CENTER);
    bottom.setLayout(new BorderLayout());
    ready1.setToolTipText("CLICK ME TO START THE GAME");
    ready2.setToolTipText("CLICK ME TO START THE GAME");

    main.setBackground(Color.gray);
    label.setForeground(Color.white);

    ready1.setFont(ready1.getFont().deriveFont(20.0f));
    ready2.setFont(ready2.getFont().deriveFont(20.0f));
    ready1.setForeground(Color.pink);
    ready2.setForeground(Color.pink);
    ready1.setPreferredSize(new Dimension(240,150 ));
    ready2.setPreferredSize(new Dimension(240, 150));
    bottom.setPreferredSize(new Dimension(600, 150));
    main.setLayout(new FlowLayout());
    main.add(label, BorderLayout.NORTH);
    frame.add(bottom, BorderLayout.SOUTH);
    bottom.add(ready1, BorderLayout.WEST);
    bottom.add(ready2, BorderLayout.EAST);
    MyMouseManager1 mmm1=new MyMouseManager1();
    MyMouseManager2 mmm2=new MyMouseManager2();
    ready1.addMouseListener(mmm1);
    ready2.addMouseListener(mmm2);
    frame.setVisible(true);
}
    class MyMouseManager1 implements MouseListener{
        public void mouseClicked(MouseEvent e) {
            ready1.setBackground(Color.green);
            ready1.setForeground(Color.white);
            ready1.setText("READY!");


        }

          public void mousePressed(MouseEvent e) {

          }

          public void mouseReleased(MouseEvent e) {


          }

          public void mouseEntered(MouseEvent e) {

          }

          public void mouseExited(MouseEvent e) {


          }
          public void mouseDragged(MouseEvent e) {

          }
          public void mouseMoved(MouseEvent e) {

    }
    }
    class MyMouseManager2 implements MouseListener{
        public void mouseClicked(MouseEvent e) {
            ready2.setBackground(Color.green);
            ready2.setForeground(Color.white);
            ready2.setText("READY!");
        }

          public void mousePressed(MouseEvent e) {

          }

          public void mouseReleased(MouseEvent e) {


          }

          public void mouseEntered(MouseEvent e) {

          }

          public void mouseExited(MouseEvent e) {


          }
          public void mouseDragged(MouseEvent e) {

          }
          public void mouseMoved(MouseEvent e) {

    }

    }

    public static void main(String[] args){
    OpeningScreen smartie=new OpeningScreen();


    }
}

Here is the second program. Please don't copy. heh.

import javax.swing.*;



import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.applet.Applet;
public class Clickasfastasyoucan extends java.applet.Applet{
    private JFrame w;
    private JPanel b;
    private Button p;
    private JPanel d;
    private int times;
    private JLabel number;
JPanel n;
JFrame x;
    public Clickasfastasyoucan() {  
         x=new JFrame("  ");
       n=new JPanel();
        times=0;
        number=new JLabel("How fast can you click?");
        w = new JFrame("My Smart Button");
        w.setSize(1500, 1000);
        b = new JPanel();
        p = new Button("Swipe as fast as you can");
        w.setSize(500, 500);
        b.setPreferredSize(new Dimension(1000,1500));
        d=new JPanel();
        w.add(b);
        b.add(p);
        b.setLayout(new GridLayout(1, 1));
        b.add(number, BorderLayout.CENTER);
        d.setSize(500, 500);
        MyMouseManager mmm = new MyMouseManager();
        p.addMouseListener(mmm);
        p.addMouseMotionListener(mmm);
        p.setForeground(Color.white);
        p.setBackground(Color.black);
        p.setFont(p.getFont().deriveFont(20.0f));
        p.setFont(p.getFont().deriveFont(20.0f));

        b.setSize(600, 600);
        w.setVisible(true);
    }

    class MyMouseManager implements MouseListener, MouseMotionListener {
        public void mouseClicked(MouseEvent e) {
        }

          public void mousePressed(MouseEvent e) {

              n.setBackground(Color.blue);
              x.add(n);
              x.setSize(500,  500);
              n.setSize(500, 500);
              x.setVisible(true);

          }

          public void mouseReleased(MouseEvent e) {


          }

          public void mouseEntered(MouseEvent e) {
              n.setBackground(Color.blue);
          }

          public void mouseExited(MouseEvent e) {
              n.setBackground(Color.white);

          }
          public void mouseDragged(MouseEvent e) {

          }
          public void mouseMoved(MouseEvent e) {times++;
            number.setFont(number.getFont().deriveFont(100.0f));


            number.setText(" "+times+" "); 
            if (times>=100&&times<999){
                b.setBackground(Color.red);
                number.setFont(number.getFont().deriveFont(80.0f));
                times=times+1;
            }
            if(times>=1000&&times<10000){
                b.setBackground(Color.green);
                number.setFont(number.getFont().deriveFont(70.0f));
                times=times+4;
            }
            if(times>=10000&&times<50000){
                b.setBackground(Color.yellow);
                number.setFont(number.getFont().deriveFont(70.0f));
                times=times+100;
            }if(times>=50000&&times<500000){
                b.setBackground(Color.blue);
                number.setFont(number.getFont().deriveFont(70.0f));
                times=times+500;
            }
            if(times>=500000&&times<4999999){
                b.setBackground(Color.pink);
                number.setFont(number.getFont().deriveFont(40.0f));
                times=times+1000;
            }

            if(times>=5000000){
                b.setBackground(Color.orange);
                number.setFont(number.getFont().deriveFont(20.0f));
                number.setText("WOW! YOU WON. CHECK THE OUTPUT TO SEE HOW YOU SCORED!");
                System.out.println("1 day: Are you still there?");
                System.out.println("24 hour: Snail speed");
                System.out.println("15 hours: Fail");
                System.out.println("5 hours: Slow Fingers");
                System.out.println("1 hour: Fast Fingers");
                System.out.println("30 minutes: Champion");
                System.out.println("15 minutes: You beat me!");
                System.out.println("2 minutes: Cheater");
                System.out.println("1 minute: Speed of Light");
                System.out.println("");
                System.out.println("");
                System.out.println("");
                System.out.println("");
                System.out.println("");
                System.out.println("___________________________-");


            }



        }     
          }

    public static void main(String[] args) {
        Clickasfastasyoucan clickgame= new Clickasfastasyoucan();
    }

}

I want this one to replace the first program. I'm not sure how to even start with this though, since this is my first attempt at any game, or anything beyond a one class program.

Upvotes: 1

Views: 99

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

No, you really don't want a java.awt.Applet to replace a JFrame, trust me. They're both used in two vastly different situations, and while the Swing library that underlies JFrames is about 4 years out of date, the AWT library that underlies java.awt.Applet is about 20 years out of date. Just stay clear of Applet.

Instead your GUI classes should be geared towards creating JPanels, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. This will greatly increase the flexibility of your GUI coding, and in fact this is what I recommend -- that you swap views via a CardLayout.

Also -- don't use MouseListeners for your JButton listeners but instead use ActionListeners. MouseListeners won't respond to space bar presses, won't be disabled if the button becomes disabled, and can be capricious if you base behavior on the mouseClicked method. Use the proper tool for the job: ActionListeners, or even better, Actions.

For example:

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.geom.AffineTransform;

import javax.swing.*;

public class MainGui extends JPanel {
   private CardLayout cardLayout = new CardLayout();
   private StartUpPanel startUpPanel = new StartUpPanel(this);
   private GamePanel gamePanel = new GamePanel(this);

   public MainGui() {
      setLayout(cardLayout);
      add(startUpPanel, startUpPanel.getName());
      add(gamePanel, gamePanel.getName());
   }

   public void nextCard() {
      cardLayout.next(this);
   }

   private static void createAndShowGui() {
      MainGui mainPanel = new MainGui();

      JFrame frame = new JFrame("MainGui");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class StartUpPanel extends JPanel {
   public static final String CLICK_IF_READY = "Click If Ready";
   public static String SUPER_TUESDAY = "SUPER TUESDAY";
   public static final String READY = "READY";
   public static final int MAX_READY = 2;
   private static final float TITLE_FONT_POINTS = 40f;
   public static final String START_UP_PANEL = "Startup Panel";
   private static final int PREF_W = 600;
   private static final int PREF_H = PREF_W;
   private int readyCount = 0;
   private MainGui mainGui;

   public StartUpPanel(MainGui mainGui) {
      this.mainGui = mainGui;
      setName(START_UP_PANEL);

      JLabel titleLabel = new JLabel(SUPER_TUESDAY, SwingConstants.CENTER);
      titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, TITLE_FONT_POINTS));

      JButton button1 = new JButton(new StartupAction());
      JButton button2 = new JButton(new StartupAction());
      button1.setFont(button1.getFont().deriveFont(Font.BOLD, TITLE_FONT_POINTS));
      button2.setFont(button1.getFont());

      JPanel southPanel = new JPanel(new GridLayout(1, 0));
      southPanel.add(button1);
      southPanel.add(button2);

      setLayout(new BorderLayout());
      add(titleLabel, BorderLayout.CENTER);
      add(southPanel, BorderLayout.PAGE_END);

   }

   @Override
   public Dimension getPreferredSize() {
      Dimension superSize = super.getPreferredSize();
      if (isPreferredSizeSet()) {
         return superSize;
      }
      int prefW = Math.max(superSize.width, PREF_W);
      int prefH = Math.max(superSize.height, PREF_H);

      return new Dimension(prefW, prefH);
   }

   private class StartupAction extends AbstractAction {
      public StartupAction() {
         super(CLICK_IF_READY);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         if (getValue(NAME).equals(CLICK_IF_READY)) { // check if button active
            putValue(NAME, READY); // swap button's name
            ((AbstractButton) e.getSource()).setFocusable(false); // lose focus
            readyCount++; // increment ready count. 
            if (readyCount >= MAX_READY) { // if all buttons pushed
               mainGui.nextCard();  // tell main GUI to swap cards
            }
         }
      }
   }

}

// simple mock class to represent the game
class GamePanel extends JPanel {
   public static final String GAME = "Game";
   private static final float FONT_POINTS = 30F;
   private MainGui mainGui;

   public GamePanel(MainGui mainGui) {
      this.mainGui = mainGui;
      setName(GAME);

      JLabel label = new JLabel(GAME, SwingConstants.CENTER);
      label.setFont(label.getFont().deriveFont(Font.BOLD, FONT_POINTS));

      setLayout(new GridBagLayout());
      add(label);
   }
}

Upvotes: 6

Related Questions