0

I have a program that asks the user a series of questions where they choose options. They choose which job they want, which then (ideally) enters the amount of money cooresponding with that job into the balance. Then they choose a house which will then remove the cooresponding amount from the balance and so on. I have a class that houses an array that holds the amount from each decision. The problem is that while I can access the corresponding array position (position 0 for job, position 1 for house decision). I tried using a variable for the original amount, but it says it is zero, even if it prints the correct amount while in the Job code.

The problem is that I can't access other positions in the array when I'm in a different card. It gives me a null pointer exception, which happens in the line in the House class when I attempt to print the current balance amount left. I access the array when the user hits a button (called "Submit") and with an Actionlistener which decides exactly what to print based on which radio button was selected. I also print a dialog box printing the amount the user has left, using position 0 in the array (where Job writes the original amount). The program uses CardLayout.

I have done my best to include all relevant information, but, let's be real. I probably forgot something important. I've spent several hours on this and haven't been able to figure it out, so it's probably an issue with how CardLayout operates.

Here is the main class.

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

}

Here is the class that creates the card holder.

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

Here is the DecisionObject class. This class holds the array.

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

Here is the Job Class. I removed duplicate parts for simplicity

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


}

}

Finally, here is the House class.

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

Here is the error:

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)
Josh
  • 71
  • 1
  • 2
  • 11
  • 1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) See [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/q/3988788/418556) & [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/q/218384/418556) – Andrew Thompson Apr 09 '17 at 19:32
  • .. 3) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Apr 09 '17 at 19:33

0 Answers0