简体   繁体   English

如何将全局JPanels添加到JFrame

[英]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. 我目前正在读高中的编程课程,我们的重点是Java,需要构建的程序之一是Rock Paper Scissors游戏。 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. 这促使我研究了JFrames以及如何使用它们。 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. 我搜集了很多教程来介绍它,并且从oracle站点保存了5个不同的示例以供参考,但我无法弄清为什么该程序无法运行。

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. 如果您可以帮助我弄清楚为什么JPanels不能添加“按钮”和“文本”,我将不胜感激。

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() { 编辑:错误,我收到后我做删除的修正voidpublic 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; 如果我从static JPanel text,buttons;删除static 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. 然后netbeans“纠正”每种方法,因此它对包括Main在内的任何方法都不会说是static ,因此它说找不到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() . 您永远不会通过new RPS()在任何地方创建RPS实例。
  • You have a "pseudo-constructor" in your RPS class. 您的RPS类中有一个“伪构造函数”。 ie, this, public void RPS() { is not a constructor. 也就是说,此public void RPS() {不是构造函数。 Get rid of the void return type as constructors should have no return type: public RPS() { 摆脱void返回类型,因为构造函数应该没有返回类型: public RPS() {
  • Your Swing component fields should most definitely not be static. 您的Swing组件字段绝对应该不是静态的。
  • You're adding components to a JFrame without respect for its layout manager, the BorderLayout. 您在向JFrame添加组件时不考虑其布局管理器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. 您当前的代码正在添加null组件,但是如果它们不为null,则将它们都添加到BorderLayout.CENTER中,最后一个覆盖前一个。
  • Create a master JPanel in the RPS class, and then add that to the JFrame in the main method, via non-static methods. 在RPS类中创建一个主JPanel,然后通过非静态方法将其添加到main方法的JFrame中。

For example, RPS could potentially extend JPanel, and if that's the case, then you'd add it to the JFrame like so: 例如,RPS可能会扩展JPanel,如果是这种情况,则可以将其添加到JFrame中,如下所示:

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 签出枚举,因为Rock Paper Scissors非常适合此操作,包括提供枚举方法来测试获胜
  • By using an enum, it would be easier to modify the code later to allow for additional states, such as Lizard and Spock. 通过使用枚举,以后修改代码以允许其他状态(例如蜥蜴和Spock)会更容易。
  • Try to separate the logic portion of your program from the view -- the GUI portion. 尝试从视图中分离程序的逻辑部分-GUI部分。
  • 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. 避免让您的GUI类实现您的侦听器接口,因为这会导致创建“配电盘”侦听器,就像您正在编写的一样-需要调试或增强。 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. 删除void ,您应该会很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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