使用CardLayout切换卡时,变量保持为空

时间:2017-04-09 18:46:06

标签: java swing user-interface nullpointerexception cardlayout

我有一个程序会向用户询问他们选择选项的一系列问题。他们选择他们想要的工作,然后(理想情况下)将与该工作相关的金额输入到余额中。然后他们选择一个房子,然后从天平中移除相应的数量,依此类推。我有一个类,其中包含一个数组,其中包含每个决定的金额。问题是,虽然我可以访问相应的数组位置(作业的位置0,房屋决策的位置1)。我尝试使用一个变量作为原始数量,但它表示它为零,即使它在作业代码中打印正确的数量。

问题是,当我在另一张卡中时,我无法访问阵列中的其他位置。它给了我一个空指针异常,当我尝试打印剩余的当前余额时,它发生在House类的行中。当用户点击按钮(称为"提交")和Actionlistener时,我会访问数组,Actionlistener根据选择的单选按钮确定要打印的内容。我还打印一个对话框,打印用户已经离开的金额,使用数组中的位置0(其中Job写入原始金额)。该程序使用CardLayout。

我尽力包含所有相关信息,但是,让我们成为现实。我可能忘记了重要的事情。我已经花了几个小时在这上面并且无法弄明白,所以这可能是CardLayout如何运作的问题。

这是主要课程。

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class Main extends JPanel {
private Arrow arrow = new Arrow();                          //creates a new Arrow object
public Main() {
    JPanel btnPanel = new JPanel();
    btnPanel.add(new JButton(new NextAction("Next")));      //creates a "Next" button that is universal      

    setLayout(new BorderLayout());


    add(arrow, BorderLayout.NORTH);
    add(btnPanel, BorderLayout.PAGE_END);
}

private class NextAction extends AbstractAction {
    public NextAction(String name) {
        super(name);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        arrow.next();  // *** call arrow's public next method
    }
}

private static void createAndShowGui() {
    Main mainPanel = new Main();
    JFrame frame = new JFrame("Iowa Budget Simulation");
    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(() -> createAndShowGui());
}

}

这是创建持卡人的类。

import java.awt.BorderLayout;
 import java.awt.CardLayout;
 import java.awt.Color;
 import java.awt.Dimension;
import java.awt.Font;
import javax.swing.*;

class Arrow extends JPanel {
    private static final long serialVersionUID = 1L;
    private CardLayout cardLayout = new CardLayout();       // make me a field
    private JPanel cardHolder = new JPanel(cardLayout);     //creates a master JPanel


public Arrow() {
    for (int i = 0; i < 1; i++) {
        cardHolder.add(createCard(i), "card " + i);
    }

    Job j = new Job();
    HousingPurchase ownHouse = new HousingPurchase();
    HousingRent rentHouse = new HousingRent();
    HealthCare hc = new HealthCare();
    Transport t = new Transport();
    Child c = new Child();
    Clothes clo = new Clothes();
    Entertainment e = new Entertainment();

    cardHolder.add(j, "Job");
    cardHolder.add(ownHouse, "Housing - Own");
    cardHolder.add(rentHouse, "Housing - Rent");
    cardHolder.add(t, "Transport");
    //cardHolder.add(hc, "Health Care");  
    cardHolder.add(c, "Childcare");
    setLayout(new BorderLayout());
    add(cardHolder, BorderLayout.NORTH);
}


// public method that other objects can call
public void next() {
    cardLayout.next(cardHolder);  // call next on the correct object
}

// simply creates a "pretty" new JPanel to be the "title" screen
private JComponent createCard(int i) {
    setLayout(null);
    setBounds(0, 0, 10 , 10);
    JLabel label = new JLabel("Iowa Budget Simulation");
    label.setFont(label.getFont().deriveFont(Font.BOLD, 50f));

    float h = (float)Math.random();
    Color c = Color.getHSBColor(h, 1f, 1f);
    label.setForeground(c.darker());

    //JPanel panel = new JPanel(new GridBagLayout());

    JPanel panel = new JPanel();

    panel.add(label);
    panel.setBorder(BorderFactory.createLineBorder(c.darker(), 20));
    panel.setBackground(c.brighter().brighter());

    panel.setPreferredSize(new Dimension(860, 870)); // first number is width, second number is height
    return panel;
}
}

这是DecisionObject类。这个类包含数组。

public class DecisionObject {
    private String decision;
    double amount;
    public double total;
    public DecisionObject finalMSG[] = new DecisionObject[10];

public DecisionObject(String d, double a){
    decision = d;
    amount = a;
}

public DecisionObject(){

}

    public double getAmount(){
        return amount;
}

public double getAmount(int a){
    return total;
}

public double getAmount(DecisionObject x){
    return x.getAmount();
}

public void changeBalance(double x){
    total = total - x;
}

public void setBalance(double x){
    total = x;
}

public double getTotal(){
    return total;
}
}

这是工作班。为简单起见,我删除了重复的部分

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

class Job extends JPanel {

public DecisionObject x = new DecisionObject(); 
private static final long serialVersionUID = 1L;

public Job() {
    setLayout(null);
    setBounds(0, 0, 10 , 10);
    //label.setFont(label.getFont().deriveFont(Font.BOLD, 50f));

    JLabel titlelable = new JLabel("JOB");
    titlelable.setFont(new Font("Times New Roman", Font.PLAIN, 22));
    titlelable.setBounds(409, 11, 49, 27);
    add(titlelable);

    JTextArea highend = new JTextArea();
    highend.setWrapStyleWord(true);
    highend.setLineWrap(true);
    highend.setText("\"This job is for a warehouse associate. The hours are Monday - Friday, from 6AM to 6PM. Applicants must have a mode of reliable transportation, will be on their feet for 12 hrs a day, and be able to lift 75 pounds. The pay is $12/hr.\"");
    highend.setBounds(99, 49, 306, 197);
    DecisionObject h1 = new DecisionObject("Let's hope you don't mind physical labor. You're gonna be on your feet for 12 hours and will be doing some lifting.", 2880);
    add(highend);

    JTextArea house2 = new JTextArea();
    house2.setWrapStyleWord(true);
    house2.setLineWrap(true);
    house2.setText("\"This job is for a sterile fill technician. The hours are Monday - Friday, from 6AM to 2:30PM. The pay is $13/hr.\"");
    DecisionObject h3 = new DecisionObject("", 2210);
    house2.setBounds(99, 299, 306, 177);
    add(house2);


    JRadioButton LeftTop = new JRadioButton("Job 1: ");
    LeftTop.setBounds(99, 253, 109, 23);
    add(LeftTop);

    ButtonGroup group = new ButtonGroup();
    group.add(LeftTop);


    JButton submit = new JButton("SUBMIT");
    submit.setFont(new Font("Times New Roman", Font.PLAIN, 20));
    submit.setBounds(342, 751, 184, 48);
    add(submit);

    submit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            if (LeftTop.isSelected()){
                x.finalMSG[0] = h1;
                double b = x.finalMSG[0].getAmount();
                //double b = x.getAmount(x.finalMSG[0]);
                x.setBalance(b);
                String a = "Balance: " + x.getTotal();
                JOptionPane.showMessageDialog(null, a);
            }

            x.setBalance(2800);
        }
    });//Close submit button actionlistener


}

}

最后,这是House课程。

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

class HousingPurchase extends JPanel {

private DecisionObject x = new DecisionObject();    
private static final long serialVersionUID = 1L;

public HousingPurchase() {
    setLayout(null);
    setBounds(0, 0, 10 , 10);

    JLabel titlelable = new JLabel("HOUSING - PURCHASE");
    titlelable.setFont(new Font("Times New Roman", Font.PLAIN, 22));
    titlelable.setBounds(358, 11, 227, 27);
    add(titlelable);

    JTextArea highend = new JTextArea();
    highend.setWrapStyleWord(true);
    highend.setLineWrap(true);
    highend.setText("\"This house costs $1,011 per month. It has 2 beds, 1 bath, and was built in 1922. It has had recent updates, has refinished hardwood and tiled floors as well as new yard landscaping. In addition, it has an enclosed front porch and a screened back porch as well as a garage with a new driveway. If it were not more perfect, it is very close to schools and the freeway.\"");
    DecisionObject h1 = new DecisionObject("Let's hope you don't mind physical labor. You're gonna be on your feet for 12 hours and will be doing some lifting.", 1011);
    highend.setBounds(99, 49, 306, 197);
    add(highend);

    JRadioButton LeftTop = new JRadioButton("House 1: ");
    LeftTop.setBounds(99, 253, 109, 23);
    add(LeftTop);

    ButtonGroup group = new ButtonGroup();
    group.add(LeftTop);
    JButton submit = new JButton("SUBMIT");
    submit.setFont(new Font("Times New Roman", Font.PLAIN, 20));
    submit.setBounds(342, 751, 184, 48);
    add(submit);

    submit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            if (LeftTop.isSelected()){
                x.finalMSG[1] = h1;
                double b = x.getAmount(h1);
                JOptionPane.showMessageDialog(null, "Balance: " + (/*x.finalMSG[0].getAmount()*/ x.getTotal() - x.finalMSG[1].getAmount()));
            }
        }
    });//Close submit button actionlistener
}
}

这是错误:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at HousingPurchase$1.actionPerformed(HousingPurchase.java:117)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

0 个答案:

没有答案