如何将JProgressBar的值设置为另一个类的引用?

时间:2014-04-10 21:21:58

标签: java swing

我目前正在编写一个小游戏的编码过程,其中有进度条从不同的类中获取变量的值。 进度条从0到500,可以调用不同的方法来改变进度条测量的变量值。

happyBar = new JProgressBar();
        happyBar.setMinimum(0);
        happyBar.setMaximum(500);
        happyBar.setValue(cat.getHappy());
        happyBar.repaint();
        happyLabel = new JLabel("Happy");
        happyLabel.setForeground(Color.white);

我引用的cat.getHappy()似乎引发了一个错误。 当我添加这行代码时,该方法是可见的:

public static Cat cat;

有没有人有任何想法,为什么我不能通过将cat.getHappy作为当前值来更新JProgressBar?

完整代码:

接口类:

import java.awt.color.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Dimension;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.*;

public class Cat_Interface  {

private JFrame catWindow;
private JPanel topPanel, leftPanel, rightPanel, bottomPanel, allPanels, playPanel, sleepPanel, huntPanel, feedPanel, cleanPanel, walkPanel, drinkPanel;
private JLabel catLabel, happyLabel, hungryLabel, energyLabel, hygieneLabel, weightLabel, thirstLabel, picLabel;
private JButton play, sleep, feed, hunt, clean, walk, drink;
private JProgressBar happyBar, hungryBar, energyBar, thirstBar, weightBar, hygieneBar;
private JTextArea catText;
private JProgressBar happy, hungry, energy, thirst, weight, hygiene;
private int interval;
private Timer timer;


    public Cat_Interface(Cat cat) {
        topPanel = new JPanel();
        topPanel.setBackground(Color.lightGray);
        leftPanel = new JPanel();
        leftPanel.setBackground(Color.lightGray);
        rightPanel = new JPanel();
        rightPanel.setBackground(Color.gray);
        bottomPanel = new JPanel();
        bottomPanel.setBackground(Color.darkGray);
        allPanels = new JPanel();

        allPanels.setLayout(new BoxLayout(allPanels, BoxLayout.Y_AXIS));

        topPanel.setLayout(new GridLayout(2,0));


        play = new JButton("Play");
        sleep = new JButton("Sleep");
        feed = new JButton("Feed");
        hunt = new JButton("Hunt");
        clean = new JButton("Clean");
        walk = new JButton("Walk");
        drink = new JButton("Drink");
        bottomPanel.setBorder(BorderFactory.createEmptyBorder(25,25,25, 25));
        bottomPanel.setLayout(new GridLayout(0, 4, 50, 10));
        bottomPanel.add(play);
        bottomPanel.add(sleep);
        bottomPanel.add(feed);
        bottomPanel.add(hunt);
        bottomPanel.add(clean);
        bottomPanel.add(walk);
        bottomPanel.add(drink);

        leftPanel.setBorder(BorderFactory.createEmptyBorder());     
            ImageIcon image = new ImageIcon("images/cat_test_picture.svg");
            leftPanel.add(new JLabel(image));
            leftPanel.setVisible(true);



        rightPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        rightPanel.setLayout(new GridLayout(0, 1));

        happyBar = new JProgressBar();
        happyBar.setMinimum(0);
        happyBar.setMaximum(500);
        //happyBar.setValue(cat.getHappy());
        happyBar.repaint();
        happyLabel = new JLabel("Happy");
        happyLabel.setForeground(Color.white);

        hungryBar = new JProgressBar(0,500);
        hungryLabel = new JLabel("Hungry");
        hungryBar.repaint();
        hungryLabel.setForeground(Color.white);

        energyBar = new JProgressBar(0,500);
        energyLabel = new JLabel("Energy");
        energyBar.repaint();
        energyLabel.setForeground(Color.white);

        hygieneBar = new JProgressBar(0,500);
        hygieneBar.setIndeterminate(true);
        hygieneLabel = new JLabel("Hygiene");
        hygieneBar.repaint();
        hygieneLabel.setForeground(Color.white);

        thirstBar = new JProgressBar(0,500);
        thirstLabel = new JLabel("Thirst");
        thirstBar.repaint();
        thirstLabel.setForeground(Color.white);

        weightBar = new JProgressBar(0,500);
        weightLabel = new JLabel("Weight");
        weightBar.repaint();
        weightLabel.setForeground(Color.white);

        rightPanel.add(happyBar);
        rightPanel.add(happyLabel);
        happyLabel.setBounds(5, 5, 5, 5);
        happyBar.setBounds(15, 5, 5, 5);

        rightPanel.add(hungryBar);
        rightPanel.add(hungryLabel);
        hungryLabel.setBounds(5, 5, 5, 5);
        hungryBar.setBounds(15, 5, 5, 5);

        rightPanel.add(energyBar);
        rightPanel.add(energyLabel);
        energyLabel.setBounds(5, 5, 5, 5);
        energyBar.setBounds(15, 5, 5,5);



        rightPanel.add(hygieneBar);
        rightPanel.add(hygieneLabel);
        hygieneLabel.setBounds(5, 5, 5, 5);
        hygieneBar.setBounds(15, 5, 5, 5);

        rightPanel.add(thirstBar);
        rightPanel.add(thirstLabel);
        thirstLabel.setBounds(5, 5, 5, 5);
        thirstBar.setBounds(15, 5, 5, 5);

        rightPanel.add(weightBar);
        rightPanel.add(weightLabel);
        weightLabel.setBounds(5, 5, 5, 5);
        weightBar.setBounds(15, 5, 5, 5);

        allPanels.add(topPanel);
        allPanels.add(leftPanel);
        allPanels.add(bottomPanel);
        allPanels.add(rightPanel);

        catWindow = new JFrame();
        catWindow.setTitle("Tamagotchi Game: Cat");
        catWindow.setSize(550,300);
        catWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        catWindow.setVisible(true);
        catWindow.add(allPanels);

        catWindow.getContentPane().add(leftPanel,BorderLayout.WEST);
        catWindow.getContentPane().add(rightPanel,BorderLayout.EAST);
        catWindow.getContentPane().add(bottomPanel,BorderLayout.SOUTH);
        //catWindow.getContentPane().add(topPanel,BorderLayout.NORTH);

    }

public JButton getPlayButton() {
    return play;
}

public JButton getSleepButton() {
    return sleep;
}

public JButton getFeedButton() {
    return feed;
}

public JButton getHuntButton() {
    return hunt;
}

public JButton getWalkButton() {
    return walk;
}

public JButton getDrinkButton() {
    return drink;
}

public JButton getCleanButton() {
    return clean;
}

public JPanel getPanels() {
    return allPanels;
}

}

猫类:

import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.swing.JOptionPane;

// my own pet class for the cat animal I chose.
public class Cat extends Animal {

Cat_Interface cat = new Cat_Interface(this);
private long tDelta, tEnd; 
private long tStart = System.currentTimeMillis();
private String furColour, eyeColour;
public int whiskerLength, petDay, petMonth, petYear, ageInYears, ageInMonths,    ageInDays;


    public Cat(String aName, Gender aGender ,String aTrait,String aAgeEffect, DateOfBirth aDateOfBirth,int aWeight, int aPetDay, int aPetMonth, int aPetYear, int aWhiskerLength, String aFurColour, String aEyeColour){

    super(aName, aGender , aTrait,  aWeight, aDateOfBirth,  aAgeEffect);
    petDay = aPetDay;
    petMonth = aPetMonth;
    petYear = aPetYear;
    whiskerLength = aWhiskerLength;
    furColour = aFurColour;
    eyeColour = aEyeColour;
    if (super.getHungry() <=0) {
        Death();
        JOptionPane.showMessageDialog(null, "Reason:\nYou didn't feed it enough.");
    }
    if (super.getEnergy() <=0) {
        super.passOut();
    }
    if (super.getWeight() >=100) {
        Death();
        JOptionPane.showMessageDialog(null, "Reason:\nIt was too heavy.");
    }
}
// getters
public String getFurColour() {
    return furColour;
}

public int getWhiskerLength() {
    return whiskerLength;
}

public String getEyeColour() {
    return eyeColour;
}
// setters
public void setFurColour(String aFurColour) {
    furColour = aFurColour;
}

public void setWhiskerLength(int aWhiskerLength) {
    whiskerLength = aWhiskerLength;
}

public void setEyeColour(String aEyeColour) {
    eyeColour = aEyeColour;
}
//custom methods
public void hunt() {
    //my custom method for the cat. This enables the cat to hunt for food when    it is too hungry.
    super.setHappy(super.getHappy() - 10);
    super.setEnergy(super.getEnergy() - 20);
    super.setHungry(super.getHungry() + 30);
    JOptionPane.showMessageDialog(null, super.getName() + " has hunted and consumed some food. \nFeed " +super.getName() + " more in the future so he doesn't have to do this.");


}

public void cleanSelf() {
// my custom method for the cat. Cats clean themselves and become happier and , obviously, cleaner as a result.
    JOptionPane.showMessageDialog(null, super.getName() + " has cleaned itself as you have not cleaned it in a while.");
    super.setHygiene(super.getHygiene() + 20);
    super.setHappy(super.getHappy() + 10);



}

//overridden methods from the animal class
@Override
//method to feed the cat, overriding the feed method from the animal class.
public void feed() {
    if (super.getHungry() > 50) {
        super.setHungry(super.getHungry() + 60);
        super.setWeight(super.getWeight() + 5);
        super.setEnergy(super.getEnergy() + 20);
        JOptionPane.showMessageDialog(null, "You have fed " + super.getName());
    } else {
        JOptionPane.showMessageDialog(null, "You cannot feed " + super.getName() + " as they are not hungry. \nWait for the hungriness to fall below 50.");
    }
}
@Override
public void clean() {
    super.setHygiene(super.getHygiene() + 30);
    super.setHappy(super.getHappy() - 20);
    JOptionPane.showMessageDialog(null, "You have cleaned " + super.getName());
}

@Override
public void play() {
    if (super.getEnergy() >= 50 ) {
        super.setHappy(super.getHappy() + 60);
        super.setEnergy(super.getEnergy() - 40);
        super.setHungry(super.getHungry() - 50);
        JOptionPane.showMessageDialog(null, "You have played with " + super.getName() + " and they are happy.");
                                    } else {
                                        JOptionPane.showMessageDialog(null, "You must let " + super.getName() + " rest before you can play with them." + "\nThe energy level must be above 50 to play.");
                                    }
    }   
@Override
public void sleep() {
    if (super.getEnergy() <= 120) {
        super.setHappy(super.getHappy() + 30);
        super.setHungry(super.getHungry() - 50);
        super.setEnergy(super.getEnergy() + 50);
        JOptionPane.showMessageDialog(null, "You have put " + super.getName() + " to sleep.");

    } else {
        JOptionPane.showMessageDialog(null, "You cannot put " + super.getName() + " to sleep until their energy is below 120." + "\nPlay with them more to decrease the energy level.");
    }

}

@Override
public void passOut() {
    super.setHappy(super.getHappy() - 30);
    JOptionPane.showMessageDialog(null, super.getName() + " has passed out due to being too tired.");
}
// A method that when called will produce a pop up window with the cat's stats.
public void showStats() {

    JOptionPane.showMessageDialog(null, "Name: " + super.getName()+ "\nAge: " + findAgeInYears() + " years, " + findAgeInMonths() + " months and " + findAgeInDays() + " days old." +
    "\nTrait:  " + super.getTrait() + "\nHungry: " + super.getHungry() + "\nEnergy: " + super.getEnergy() +
"\nHappy: " + super.getHappy() + "\nHygiene: " + super.getHygiene() + "\nWeight: " + super.getWeight() + "\nThirst: " + super.getThirst() + "\nTime spent together: " + getTimeSpent() +" seconds");
}
// A method that allows you to take the cat on a walk.
public void walk() {
    if (super.getEnergy() >= 50) {
    super.setHappy(super.getHappy() + 60);
    super.setEnergy(super.getEnergy() - 40);
    super.setHungry(super.getHungry() - 10);
    super.setHygiene(super.getHygiene() - 30);
    JOptionPane.showMessageDialog(null, "You have taken " + super.getName() + " for a walk.");
} else {
    JOptionPane.showMessageDialog(null, "The energy must be above 40 for " + super.getName() + " to be able to go for a walk.");
}

    }
// This method will kill the cat when certain stats are reached eg hungry <= 0
@Override
public void Death() {
    JOptionPane.showMessageDialog(null, super.getName() + " has died.\nLook after your pets in the future.");
    System.exit(5);
}
//This method will calculate the time spent with the cat.
public double getTimeSpent() {
    tEnd = System.currentTimeMillis();
    tDelta = tEnd - tStart;
    double elapsedSeconds = tDelta / 1000.0;
    return elapsedSeconds;

}
@Override
public void drink() {
    super.setThirst(super.getThirst() + 50);
}

@Override
public void runAway() {
    JOptionPane.showMessageDialog(null, super.getName() + " has run away. Take better care of them in the future.");
    System.exit(5);
}
/**
 * This handy method findAgeInYears() uses a gregorian calendar to give me the value for      the age of the animal in years. It uses the aPetMonth variable that is passed
 * in through the  constructor and uses it in it's calculations.
 * @return the age in years.
 */
public int findAgeInYears(){
    Calendar cal1 = new GregorianCalendar();
    int tempMonth = (petMonth - 1);
    cal1.add(Calendar.DAY_OF_MONTH, -petDay);
    cal1.add(Calendar.MONTH, -(tempMonth));
    cal1.add(Calendar.YEAR, -petYear);
    ageInYears= (cal1.get(Calendar.YEAR));
    return ageInYears;

}
/**
* This handy method findAgeInMonths() uses a gregorian calendar to give me the value     for the age of the animal in months. It uses the aPetMonth variable that is passed
* in through the  constructor and uses it in it's calculations.
* @return the age in months.
*/
public int findAgeInMonths(){
    Calendar cal1 = new GregorianCalendar();
    int tempMonth = (petMonth - 1);
    cal1.add(Calendar.DAY_OF_MONTH, -petDay);
    cal1.add(Calendar.MONTH, -(tempMonth));
    cal1.add(Calendar.YEAR, -petYear);
    ageInMonths = (cal1.get(Calendar.MONTH));
    return ageInMonths;
}
/**
* This handy method findAgeInDays() uses a gregorian calendar to give me the value for the age of the animal in days. It uses the aPetDay variable that is passed
* in through the  constructor and uses it in it's calculations.
* @return the age in days.
*/
public int findAgeInDays(){
    Calendar cal1 = new GregorianCalendar();
    int tempMonth = (petMonth - 1);
    cal1.add(Calendar.DAY_OF_MONTH, -petDay);
    cal1.add(Calendar.MONTH, -(tempMonth));
    cal1.add(Calendar.YEAR, -petYear);
    ageInDays = (cal1.get(Calendar.DAY_OF_MONTH));
    return ageInDays;
}

}

动物类:

import java.util.Calendar;
import java.util.GregorianCalendar;

/**
* This is the generic super class animal witch will be inherited by 
* each individual animal. It contains generic instance variables and methods.
* 
* @author Group 5 Tuesday 
*
*/
public class Animal {


private String name, trait, ageEffect;
private Gender gender;
private DateOfBirth dateOfBirth;
private int happy, hungry, energy, weight, hygiene, age, thirst;

/**
 * This is the constructor for the animal class. It initialises all the instance 
 * variables for the animal class.
 * @param aName - The name of the animal
 * @param aTrait - The trait of the animal
 * @param aWeight - the weight of the animal
 * @param aDateOfBirth - the date of birth of the animal
 */
public Animal (String aName,Gender aGender ,String aTrait, int aWeight, DateOfBirth aDateOfBirth, String aAgeEffect)
{

    name = aName;
    gender = aGender;
    dateOfBirth = aDateOfBirth;
    age = 2014 - dateOfBirth.getYear(); 
    trait = aTrait;
    happy = 500;
    energy = 500;
    hungry = 500;
    weight = aWeight;
    hygiene = 500;
    thirst = 500;
    ageEffect = aAgeEffect;
}



// getter and setter methods

/**
 * This method returns the animal name
 * @return the name
 */
public String getName() {
    return name;
}

/**
 * 
 * @return the gender of the animal
 */
public Gender getGender()
{
    return gender;
}
/**
 * This method returns the trait of the animal
 * @return the Trait
 */
public String getTrait() {
    return trait;
}
/**
 * This method returns the Age effect of the animal
 * @return the Age Effect
 */
public String getAgeEffect() {
    return ageEffect;
}
/**
 * This method returns the happiness of the animal
 * @return the happy stat
 */
public int getHappy() {
    return happy;
}
/**
 * This method returns the hungry statistic of the animal
 * @return the hungry
 */
public int getHungry() {
    return hungry;
}
/**
 * This method returns the Energy statistic of the animal
 * @return the energy
 */
public int getEnergy() {
    return energy;
}
/**
 * This method returns the Weight statistic of the animal
 * @return the weight
 */
public int getWeight() {
    return weight;
}
/**
 * This method returns the Hygiene statistic of the animal
 * @return the hygiene
 */
public int getHygiene() {
    return hygiene;
}
/**
 * This method returns the age of the animal
 * @return the age
 */
public int getAge() {
    return age;
}
/**
 * This method returns the Thirst statistic of the animal
 * @return the thirst
 */
public int getThirst()
{
    return thirst;
}


/**
 * This method it used to change the Name of the animal
 * @param nName - the new name
 */
public void setName(String nName) {
    name = nName;
}

public void setGender(Gender nGender)
{
    gender = nGender;
}
/**
 * This method it used to change the trait of the animal
 * @param nTrait- the new trait of the animal
 */
public void setTrait(String nTrait) {
    trait = nTrait;
}
/**
 * This method it used to change the age effect of the animal
 * @param nAgeEffect - the new age affect of the animal
 */
public void setAgeEffect(String nAgeEffect) {
    ageEffect = nAgeEffect;
}
/**
 * This method it used to change the happy statistic  of the animal
 * @param nHappy - the new happy statistic of the animal
 */
public void setHappy(int nHappy) {
    happy = nHappy;
    if (happy > 500) {happy = 500;}
    if (happy < 0 ){happy = 0;}
}
/**
 * This method it used to change the hungry statistic  of the animal
 * @param nHungry the new hungry statistic of the animal
 */
public void setHungry(int nHungry) {
    hungry = nHungry;
    if (hungry > 500) {hungry = 500;}
    if (hungry < 0 ){hungry = 0;}
}
/**
 * This method it used to change the happy statistic  of the animal
 * @param nEnergy- the new energy statistic of the animal.
 */
public void setEnergy(int nEnergy) {
    energy = nEnergy;
    if (energy > 500) {energy = 500;}
    if (energy < 0 ){energy = 0;}
}
/**
 * This method it used to change the Weight statistic  of the animal
 * @param nWeight - the new weight statistic of the animal
 */
public void setWeight(int nWeight) {
    weight = nWeight;
}
/**
 * This method it used to change the Hygiene statistic  of the animal
 * @param nHygiene - the new hygiene statistic of the animal
 */
public void setHygiene(int nHygiene) {
    hygiene = nHygiene;
    if (hygiene > 500) {hygiene = 500;}
    if (hygiene < 0 ){hygiene = 0;}
}
/**
 * This method it used to change the age of the animal
 * @param nAge - the animals new age
 */
public void setAge(int nAge) {
    age = nAge;
}
/**
 * This method is used to change the thirst statistic of the animal
 * @param nThirst - the animals new thirst statistic
 */
public void setThirst(int nThirst)
{
    thirst = nThirst;
    if (thirst > 500) {thirst = 500;}
    if (thirst < 0 ){thirst = 0;}
}
/**
 * This method will be used by the end user to interact with the animal. 
 * Playing with the animal will make it happy
 */
public void play() 
{
    happy = happy + 50;
    energy = energy - 50;
    weight = weight - 5;
}

/**
 * This method will be used by the end user to interact with the animal.
 * cleaning the animal will increase it's hygiene. but will make it more unhappy
 */
public void clean()
{
    hygiene = hygiene + 50;
    happy = happy - 25;
}

/**
 * This method will be used by the end user to interact with the animal.
 * Feeding the animal will make it less hungry
 */
public void feed()
{
    System.out.println("You have fed " + name);
    hungry = hungry + 50;
}

/**
 * This method will be used by the end user to interact with the animal.
 * Giving the animal a drink will increase the thirst variable.
 */
public void drink()
{
    thirst = thirst + 50;
}

/**
 * This method will be used by the end user to interact with the animal.
 * Letting the animal sleep will increase it's energy
 */
public void sleep()
{
    System.out.println(name + " is now sleeping");
    energy = energy + 50;
}

/**
 * This method will be called if the animal's energy drops below a certain level
 * If an animal passes out it's energy will increase but it's happiness will decrease a lot
 */
public void passOut()
{
    System.out.println(name + " has passed out from being to tired");
    happy = happy - 50;
    energy = energy + 25;
}

public void Death()
{
    System.out.println("Your animal has now died");
}

public void runAway()
{
    System.out.println("Your animal has run away because of you poor care");
}


}

主要方法:

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

public class CatInterface_Tester  {
public static void main(String[] args) {
    Cat_Interface myInterface = new Cat_Interface(null);}

}

最后,当我运行界面时,它给了我这个错误:

Exception in thread "main" java.lang.NullPointerException
at Cat_Interface.<init>(Cat_Interface.java:75)

1 个答案:

答案 0 :(得分:2)

  1. 如果您看到错误:"The cat.getHappy() that I am referencing seems to pull up an error" - 请发布错误消息。就我们所知,你的cat变量可能为null,你可能会得到一个NullPointerException。
  2. cat变量绝对不应该是静态的。
  3. 要让外部类更改此类的状态,请为此类提供外部类可以调用的公共方法。在该方法中,然后使用传入的信息来设置JProgressBar的value属性。
  4. 需要更多代码和更多详细信息才能完全帮助您。你当前的问题很少见。
  5. 如,

    public void setProgress(int progress) {
      myProgressBar.setValue(progress);
    }
    

    修改

    更好的答案是根据MadProgrammer - 尝试将您的GUI(也称为“视图”)与业务数据分开,使用模型 - 视图 - 控制类型的架构来分析您的“模型”。如果你走这条路线,你的视图将通过控件直接或间接地将监听器添加到模型中,以便在模型改变状态时通知它,然后它可以改变其数据的表示。这是一个更高级的编程概念,如果你刚刚开始,可能会过度杀戮,但它是有效的,当你需要调试你的应用程序或想要改进它时,它肯定有助于。


    编辑2
    您已验证您的例外是NPE。这是因为cat变量为null。解决方案:不要尝试在空变量上调用方法,而是首先尝试为其分配有效的引用。这可能很简单:

    Cat cat = new Cat();
    

    编辑3

    1. 获取Cat类之外的Cat_Interface变量。它没有生意。
    2. 您当前的代码将null传递给Cat_Interface类,并将其分配给Cat变量。所以你不应该对看到NPE感到惊讶,因为你试图在变量上调用一个明确设置为null的方法!不要这样做。
    3. 如果所有main方法都是创建Cat_Interface对象并显示它,那么让这个类完成所有操作。不要将Cat传递给它的构造函数,而是让它创建自己的Cat实例并使用它。