-1

Hello guys I started a personal project to where I would basically make a meal planner based of how many calories a person wants to consume per day for myself. I know it maybe a tough challenge for me since I'm a beginner, but I can do it! I will leave the backend later, but for now I wanted to work on the UI and I'm having trouble with this piece of code. I want to make a list of panels to be held in a panel, based on how many number of meals they want is how many panels will appear. any insight on this will be much appreciated.

package mealplanner;

import javax.swing.*;

/**
 * Created by Usman on 6/8/2017.
 */
public class MealPlannerPanel extends JPanel {

    JPanel[] panel;
    int mealsPerDay, caloriesPerDay;
    public MealPlannerPanel(){
        mealsPerDay = Integer.parseInt(JOptionPane.showInputDialog("How many meals would you like per day?",null));
        caloriesPerDay = Integer.parseInt(JOptionPane.showInputDialog("What is your daily calorie aim?",null));
        panel = new JPanel[mealsPerDay];
        for(int i = 0; i < panel.length; i++){
            add(panel[i]);
        }
    }
    public static void main(String[] args){
        MealPlannerPanel planner = new MealPlannerPanel();
        JFrame frame = new JFrame("Meal Planner");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(planner);
        frame.pack();
        frame.setVisible(true);
    }
}
silversk8terz
  • 91
  • 1
  • 1
  • 9

1 Answers1

1
panel = new JPanel[mealsPerDay];

That statement just creates an array that is able to hold the given number of panels.

It does not actually create the panel (so when you index into the array you will get a null object).

So you need something like:

    for(int i = 0; i < panel.length; i++){
        JPanel onePanel = new JPanel();
        panel[i] = onePanel;
        add(panel[i]);
    }

Also, be more descriptive with you variable names. "panel" implies a single component. Given it is meant to represent an array the least you can do is call it "panels" so we know there is more than one.

camickr
  • 321,443
  • 19
  • 166
  • 288