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

Java 如何将JProgressBar的值设置为来自另一个类的引用?,java,swing,Java,Swing,我目前正在编写一个小游戏,其中有进度条,可以从不同的类中获取变量的值。 进度条从0到500,可以调用不同的方法来更改进度条测量的变量的值 happyBar = new JProgressBar(); happyBar.setMinimum(0); happyBar.setMaximum(500); happyBar.setValue(cat.getHappy()); happyBar.repaint(); happy

我目前正在编写一个小游戏,其中有进度条,可以从不同的类中获取变量的值。 进度条从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;
有人有什么想法吗?比如,为什么我不能更新JProgressBar,而必须将cat.getHappy作为它的当前值

完整代码:

接口类:

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;
}

}
最后,当我运行接口时,它会给我这个错误:

Exception in thread "main" java.lang.NullPointerException
at Cat_Interface.<init>(Cat_Interface.java:75)
线程“main”java.lang.NullPointerException中的异常 在Cat_接口(Cat_Interface.java:75)
  • 如果您看到错误:
    “我引用的cat.getHappy()似乎出现了错误”
    ——然后请发布错误消息。据我们所知,您的cat变量可能为null,您可能会得到一个NullPointerException
  • cat变量绝对不应该是静态的
  • 若要让外部类更改此类的状态,请为此类提供外部类可以调用的公共方法。在方法中,然后使用传入的信息设置JProgressBar的value属性
  • 需要更多的代码和详细信息来全面帮助您。你现在的问题在这一点上是非常稀疏的
  • e、 g


    编辑

    根据MadProgrammer的说法,更好的答案是——通过使用模型-视图-控制类型的体系结构,尝试将GUI(也称为“视图”)与业务数据(也称为“模型”)分离。如果您这样做,视图将直接或间接地通过控件将侦听器添加到模型中,以便在模型更改状态时通知它,然后它可以更改数据的表示形式。这是一个更高级的编程概念,如果你刚刚开始,可能会有点过分,但它是有效的,并且肯定会在以后需要调试应用程序或想要改进应用程序时提供帮助


    编辑2
    您已验证您的异常是NPE。这是由于cat变量为空。解决方案:不要尝试对空变量调用方法,而是首先尝试为其分配一个有效引用。这可能很简单:

    Cat cat = new Cat();
    

    编辑3

  • 获取Cat类外部的Cat_接口变量。在那里没什么用
  • 当前代码将null传递到Cat_接口类,并将其分配给Cat变量。因此,当您看到NPE时,您不应该感到惊讶,因为您正试图对显式设置为null的变量调用方法!不要这样做
  • 如果main方法所做的只是创建Cat_接口对象并显示它,那么就让这个类来完成所有的工作。不要将Cat传入其构造函数,而是让它创建自己的Cat实例并使用它
    使用模型链接ui的各个元素,根据需要更改模型并更新ui以表示模型的状态UI@MadProgrammer:甚至比我的建议还要好。@HovercraftFullOfEels可以随意填写……在ipad上打印出来让我感到畏缩:p这个问题与进度条没有多大关系。@MadProgrammer:完成。我添加了我正在使用的不同类还有我收到的错误信息。也谢谢你的提示@user3521306:是的,正如我所怀疑的,这是NullPointerException或NPE。@user3521306:请参见编辑2。以这种方式引用Cat类不意味着我必须让接口类扩展Cat类,然后调用Cat构造函数吗?@user3521306:是的,这是正确的。
    Exception in thread "main" java.lang.NullPointerException
    at Cat_Interface.<init>(Cat_Interface.java:75)
    
    public void setProgress(int progress) {
      myProgressBar.setValue(progress);
    }
    
    Cat cat = new Cat();