Java question - problem adding and deleting items from JComboBox

  • Comp Sci
  • Thread starter clook
  • Start date
  • Tags
    Java
In summary, the code is trying to add items to the bagelJComboBox through a textfield and button click, but there is an issue with the for loop causing a NullPointerException. Additionally, the remove method should only execute if the user has selected a variety, and an ActionListener has been implemented to handle this.
  • #1
clook
35
0
here is my code
Code:
import javax.swing.*;
import java.text.*;
import java.awt.event.*;
 
public class Ch6Bagel extends JFrame implements ActionListener, ItemListener {
	
  
	//create GUI objects
	JPanel mainPanel = new JPanel();
	JTextField bagelQuantityTextField = new JTextField(10);
	JTextField creamCheeseQuantityTextField = new JTextField(10);
	JTextField newVarietyTextField = new JTextField(10);
	JCheckBox checkBox = new JCheckBox("Add Cream Cheese");
    JButton orderButton = new JButton("Order"); 
    JButton clearButton = new JButton("Clear");  
    JButton summaryButton = new JButton("Summary");  
    JButton varietyButton = new JButton("Add Variety"); 
    JButton deleteVarietyButton = new JButton("Delete Variety");
    JLabel bagelLabel = new JLabel("Lee Bagels");
    JTextArea outputTextArea = new JTextArea("Your Total Cost:", 10, 15);
        
    
    //datatypes and objects
    
    String[] bagelString = {"Plain", "Egg", "Rye", "Salt", "Blueberry",
    	    "Garlic", "Onion", "Sesame", "Poppy Seed", "The Works"};
    String[] creamCheeseString = {"Plain", "Herb", "Garlic"};
    int quantityBagelInteger, quantityCreamCheeseInteger, counterInteger = 1;
    String bagelTypeString, creamCheeseTypeString, addVarietyString;
    
    //create comboboxes
	JComboBox bagelJComboBox = new JComboBox(bagelString);
	JComboBox creamCheeseJComboBox = new JComboBox(creamCheeseString);
 
	public static void main(String[] args) 
	{
	Ch6Bagel myBagel = new Ch6Bagel();
	myBagel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
	}
	
	
	public Ch6Bagel()
	{
		designFrame();
	}
	public void designFrame()
	{
		
		creamCheeseJComboBox.setEnabled(false);
		creamCheeseQuantityTextField.setEditable(false);
		mainPanel.add(bagelLabel);
		mainPanel.add(new JLabel("       Type of Bagel            "));
	    mainPanel.add(bagelJComboBox);
		mainPanel.add(new JLabel("       Quantity           "));
        mainPanel.add(bagelQuantityTextField);
        mainPanel.add(checkBox);
        mainPanel.add(new JLabel("       Type of Cream Cheese           "));
        mainPanel.add(creamCheeseJComboBox);
        mainPanel.add(new JLabel("           Quantity                   "));
        mainPanel.add(creamCheeseQuantityTextField);
        mainPanel.add(outputTextArea);
        mainPanel.add(orderButton);
        mainPanel.add(summaryButton);
        mainPanel.add(varietyButton);
        mainPanel.add(newVarietyTextField);
        mainPanel.add(deleteVarietyButton);
        mainPanel.add(clearButton);
	
        //add listeners
        orderButton.addActionListener(this);
        summaryButton.addActionListener(this);
        checkBox.addItemListener(this);
        clearButton.addActionListener(this);
        varietyButton.addActionListener(this);
        deleteVarietyButton.addActionListener(this);
        bagelJComboBox.addActionListener(this);
  
      //add the panel to the frame
		add(mainPanel);
		setSize(200,600);
		setVisible(true);
		
 
		
	}
	
 
	
	
	public void actionPerformed(ActionEvent evt)
	{
		//retrieve the logical of the component that fired the action event
		Object sourceObject = evt.getSource();
		if(sourceObject == orderButton)
		{
			counterInteger++;
			getInput();
			displayOutput();
			
		}
		else if(sourceObject == summaryButton)
		{
			summary();
		}
		else if(sourceObject == varietyButton)
		{
			addVariety();
		}
		else if(sourceObject == deleteVarietyButton && sourceObject == bagelJComboBox)
		{
			deleteVariety();
		}
		else if(sourceObject == clearButton)
		{
			clear();
		}
 
	}
 
	
	
	public void itemStateChanged(ItemEvent evt)
	{
		if(checkBox.isSelected())
		{
		creamCheeseJComboBox.setEnabled(true);
		creamCheeseQuantityTextField.setEditable(true);
	
		}
		else
		{
		creamCheeseJComboBox.setEnabled(false);
		creamCheeseQuantityTextField.setEditable(false);
	
		}
	}
	
	
	public void getInput()
	{
	 
		bagelTypeString = (String) bagelJComboBox.getSelectedItem();
		creamCheeseTypeString = (String) creamCheeseJComboBox.getSelectedItem();
		
		
		
		if (bagelQuantityTextField.getText().length() == 0)
		{
		JOptionPane.showMessageDialog(null, "Please enter a number!");
		}
		else
		{
        quantityBagelInteger = Integer.parseInt(bagelQuantityTextField.getText());
        }
		
	    if (creamCheeseQuantityTextField.getText().length() == 0 && checkBox.isSelected())
	    {
	    JOptionPane.showMessageDialog(null, "Please enter a number!");
	    }
	    else
	    {
		quantityCreamCheeseInteger = Integer.parseInt(creamCheeseQuantityTextField.getText());
	    }
	}
 
		
			
 
 
        
	
	public void displayOutput()
	{
      DecimalFormat formatDecimalFormat = new DecimalFormat("$0.00");
      double bagelCostDouble, creamCheeseCostDouble, totalCostDouble;
      
      Calculate myBagelCost = new Calculate(quantityBagelInteger, quantityCreamCheeseInteger, counterInteger);      
      bagelCostDouble = myBagelCost.getBagelCost();
      creamCheeseCostDouble = myBagelCost.getCheeseCost();
      totalCostDouble = myBagelCost.getTotalCost();
     
 
     
	    outputTextArea.setText("Type of Bagel:" + bagelTypeString +
	    '\n' + "Quantity: " + quantityBagelInteger +
	    '\n' + "Cream Cheese: " + creamCheeseTypeString +
	    '\n' + "Quantity: " + quantityCreamCheeseInteger +
	    '\n' + "Bagels: " + formatDecimalFormat.format(bagelCostDouble)  +
	    '\n' + "Cream Cheese: " + formatDecimalFormat.format(creamCheeseCostDouble) 
	    + '\n' + "Total Cost: " + formatDecimalFormat.format(totalCostDouble));
	  
	  
	}
	
	public void summary()
	{
		DecimalFormat formatDecimalFormat = new DecimalFormat("$0.00");
 
		double totalBagelCostDouble, totalCreamCheeseCostDouble, averageBagelsBoughtDouble;
		Calculate myBagelCost = new Calculate(quantityBagelInteger, quantityCreamCheeseInteger, counterInteger);    		
		totalBagelCostDouble = myBagelCost.getTotalBagelCost();
		totalCreamCheeseCostDouble = myBagelCost.getTotalCheeseCost();
		averageBagelsBoughtDouble = myBagelCost.getAverageBagels();
		
		JOptionPane.showMessageDialog(null, 
		    		'\n' + " Total Cost of Bagels  " + formatDecimalFormat.format(totalBagelCostDouble)+
		    		'\n' + " Total Cost of Cream Cheese  " + formatDecimalFormat.format(totalCreamCheeseCostDouble)
		    		+ '\n' + "Average Number of Bagels Bought" + averageBagelsBoughtDouble);
	}
	
	public void addVariety()
	{
		int i = 0;
		for (i = 0; i < 9; i++) 
		{
		if (addVarietyString.equals(bagelString[i]))
	    JOptionPane.showMessageDialog(null, "Duplicate Variety!");	
		else  
		addVarietyString = newVarietyTextField.getText();
		bagelJComboBox.insertItemAt(addVarietyString, 10);
		}
 
	}
	
	public void deleteVariety()
	{
		bagelJComboBox.removeItemAt(bagelJComboBox.getSelectedIndex());
	}
		
	public void clear()
	{
		bagelQuantityTextField.setText("");
		creamCheeseQuantityTextField.setText("");
		newVarietyTextField.setText("");
	}
	
}


I am trying to add items via a textfield and the clicking of "varietyButton" in the addVariety() method.
In the method, I am trying to implement a for loop that will compare the inputted string with all the items in the array that is in the bagelJComboBox.

Here is the code for the method
Code:
public void addVariety()
	{
		addVarietyString = newVarietyTextField.getText();
		int i = 0;
		for (i = 0; i < 9; i++) 
		{
		if (addVarietyString.equals(bagelString[i]))
	    JOptionPane.showMessageDialog(null, "Duplicate Variety!");	
		else  
		bagelJComboBox.addItem(addVarietyString);
		}
 
	}



I always get a NullPointerException whenever I try to add the item. What exactly is wrong?

The remove method deleteVariety() works fine. However, I am trying to make it only execute when the user has clicked and selected a variety, as opposed to the default item ("Plain")
I have implemented an actionListener to bagelJComboBox for this purpose and even implemented it in the actionPerformed method, but it still does not work. What gives?
 
Physics news on Phys.org
  • #2



There are a few issues with your code that could be causing the NullPointerException and the issue with the deleteVariety() method not working as expected.

First, in your addVariety() method, you are not checking if the inputted string is equal to the default item "Plain" before adding it to the combo box. This could be causing the NullPointerException because the default item is not in the bagelString array, so the for loop will try to access an index that does not exist.

To fix this issue, you can add an additional check before the for loop to make sure the inputted string is not equal to "Plain". If it is, you can display a message to the user and not add it to the combo box.

Secondly, in your deleteVariety() method, you are using the getSelectedIndex() method, which will return -1 if no item is selected. This could be causing the method to not execute as expected. To fix this, you can use the getSelectedItem() method instead, which will return the selected item or null if no item is selected. You can then check if the selected item is not null before executing the remove method.

Lastly, make sure you are adding the action listener to the correct combo box in your actionPerformed() method. You should add it to the bagelJComboBox instead of the deleteVarietyButton, as that is the combo box you want to listen for changes on.

Here is the updated code for the addVariety() and deleteVariety() methods:

public void addVariety() {
addVarietyString = newVarietyTextField.getText();
if (addVarietyString.equals("Plain")) {
JOptionPane.showMessageDialog(null, "Duplicate Variety!");
} else {
for (int i = 0; i < 9; i++) {
if (addVarietyString.equals(bagelString)) {
JOptionPane.showMessageDialog(null, "Duplicate Variety!");
break;
} else {
bagelJComboBox.addItem(addVarietyString);
break;
}
}
}
}

public void deleteVariety() {
if (bagelJComboBox.getSelectedItem() != null) {
bagelJComboBox.removeItem(bagelJComboBox.getSelectedItem());
}
}

Also, make sure you are adding the action listener to the correct combo box in your actionPerformed() method:

bagelJComboBox.addActionListener(this);
 
  • #3


I would suggest checking the code for any potential errors or bugs that could be causing the NullPointerException. It could be a problem with the way the items are being added to the JComboBox or with the comparison in the for loop. I would also recommend debugging the code and checking the values of the variables at each step to see where the problem occurs.

Additionally, for the deleteVariety() method, you could check if the selected index is greater than 0 before removing the item, to ensure that a variety has been selected.

In terms of the actionListener for bagelJComboBox, make sure it is properly implemented and that the method is being called correctly. You could also try using a different approach, such as using a separate button for deleting the variety, to see if that resolves the issue.

Overall, it's important to carefully check and test the code to identify and fix any errors that may be causing the issues.
 

1. What is a JComboBox in Java?

A JComboBox is a Swing component in Java that allows users to select an item from a drop-down list. It is commonly used in user interfaces to provide a list of options for the user to choose from.

2. How do I add items to a JComboBox?

To add items to a JComboBox, you can use the addItem() method and pass in the item you want to add as a parameter. You can also use the addItems() method to add multiple items at once.

3. How do I delete items from a JComboBox?

To delete an item from a JComboBox, you can use the removeItem() method and pass in the item you want to remove as a parameter. You can also use the removeItemAt() method to remove an item at a specific index.

4. How do I get the selected item from a JComboBox?

To get the selected item from a JComboBox, you can use the getSelectedItem() method. This will return the selected item as an object, so you may need to cast it to the appropriate type.

5. How do I add an ActionListener to a JComboBox?

To add an ActionListener to a JComboBox, you can use the addActionListener() method and pass in an ActionListener object as a parameter. This will allow you to perform an action when an item in the JComboBox is selected.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
2
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
4K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
4K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
5K
  • Programming and Computer Science
Replies
1
Views
1K
  • Computing and Technology
Replies
6
Views
2K
  • Programming and Computer Science
Replies
2
Views
3K
Back
Top