简体   繁体   中英

How to add global JPanels to a JFrame

I am currently in a programming course in highschool and we are focusing on Java, one of the programs required to be built is a Rock Paper Scissors game. I have done this easily and it works but i decided to try and figure out how to make it work in a window of its own. this led me to research JFrames and how to use them. I have loked up many tutorials to introduce it and I have 5 different examples from the oracle site saved to use for reference, yet i have not be able to figure out why this program won't work.

package rps;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
 * Name: Steven Biro
 * Course Code: ICS3U
 * Teacher: Mr.Carron
 * Date: 23-Apr-2014
 * Program Description: 
 */
public class RPS 
                implements ActionListener {
    static JPanel text,buttons;

    /**
     * @param args the command line arguments
     */
    public void RPS() {
        JButton Rock,Paper,Scissors;
        buttons = new JPanel();
        Rock = new JButton("Rock");
        Paper = new JButton("Paper");
        Scissors = new JButton("Scissors");
        Rock.setMnemonic(KeyEvent.VK_D);
        Paper.setMnemonic(KeyEvent.VK_M);
        Scissors.setMnemonic(KeyEvent.VK_E);
        Rock.setActionCommand("Rock");
        Paper.setActionCommand("Paper");
        Scissors.setActionCommand("Scissors");
        Rock.addActionListener(this);
        Paper.addActionListener(this);
        Scissors.addActionListener(this);
        buttons.add(Rock);
        buttons.add(Paper);
        buttons.add(Scissors);

    }

    public void actionPerformed(ActionEvent e) {
        String PC,Player;
        int outcome;
    PC="";
    Player=(e.getActionCommand());
    int computer = (int)(Math.random()*3+1);
    if (computer==1) {
        PC="Rock";
    } else if (computer==2) {
        PC="Paper";
    } else {
        PC="Scissors";
    } if (Player.equals(PC)) {
        outcome=0; //tied
    } else {
        if ("Rock".equals(PC)) {
            if ("Paper".equals(Player)) {
                outcome=1; //win
            } else { 
                outcome=2; //lose
            }
        } else if ("Paper".equals(PC)) {
            if ("Scissors".equals(Player)) {
                outcome=1; //win
            } else {
                outcome=2; //lose
            }
        } else {
            if ("Rock".equals(Player)) {
                outcome=1; //win
            } else {
                outcome=2; //lose
                }
            }
        }
    JLabel r;
        if (outcome==0) {
            r = new JLabel ("You Tied.");
        } else if (outcome==1) {
            r = new JLabel ("You Win.");
        } else if (outcome==2) {
            r = new JLabel ("You Lose.");
        } else {
            System.exit(2);
            r = new JLabel ("wont ever execute");
        }
        text = new JPanel();
        text.add(r);
    }

 public static void GUI() {
                       //Create and set up the window.
        JFrame frame = new JFrame("RockPaperScissors");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        frame.add(buttons);
        frame.add(text);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
        frame.setSize(250,150);
    }


    public static void main(String[] args) {

        GUI();

    }

}

If you can help me figure out why the JPanels called "buttons" and "text" wont add I would be very grateful.

If I remove

        //Create and set up the content pane.
    frame.add(buttons);
    frame.add(text);

from my program, then it runs without a problem and is just a blank window as would be expected, so i am at a loss of what to do.

EDIT: The error i get after i make the correction of removing void from public void RPS() {

Exception in thread "main" java.lang.NullPointerException at java.awt.Container.addImpl(Container.java:1091) at java.awt.Container.add(Container.java:1003) at javax.swing.JFrame.addImpl(JFrame.java:564) at java.awt.Container.add(Container.java:415) at rps.RPS.GUI(RPS.java:102) at rps.RPS.main(RPS.java:114) Picked up _JAVA_OPTIONS: -Djava.net.preferIPv4Stack=true Java Result: 1

If i remove static from static JPanel text,buttons; then netbeans "corrects" each method so it never says static for any of them including Main so it says it cant find main.

sorry if im coming across as stupid, but if anyone could please help me figure this out i would be very appreciative.

  • You never create a RPS instance anywhere via new RPS() .
  • You have a "pseudo-constructor" in your RPS class. ie, this, public void RPS() { is not a constructor. Get rid of the void return type as constructors should have no return type: public RPS() {
  • Your Swing component fields should most definitely not be static.
  • You're adding components to a JFrame without respect for its layout manager, the BorderLayout. Your current code is adding null components, but if they weren't null, they'd both be added BorderLayout.CENTER, the last one covering up the previous one.
  • Create a master JPanel in the RPS class, and then add that to the JFrame in the main method, via non-static methods.

For example, RPS could potentially extend JPanel, and if that's the case, then you'd add it to the JFrame like so:

JFrame frame = new JFrame("RPS");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(new RPS());

Other suggestions:

  • Check out enums as Rock Paper Scissors lends itself well to this, including giving the enum methods to test for win
  • By using an enum, it would be easier to modify the code later to allow for additional states, such as Lizard and Spock.
  • Try to separate the logic portion of your program from the view -- the GUI portion.
  • Avoid having your GUI classes implement your listener interfaces as this leads to creation of "switch-board" listeners, kind of like you're writing -- a bear to debug or enhance. Instead experiment with anonymous inner classes, or private inner classes here.

This is probably because

public void RPS() {

is not the constructor, but a method (because it has a return type), and so is never called.

Remove the void and you should be good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM