
I have updated this from the original post, now I can add/remove items but the last item left gets stuck … it seems to be to do with the button states… the last item’s “del” button will be grayed out… also the “add new item” button seems to sometimes affect this when clicking. Also if you have any other observations about how my probably crude code could be improved….
package com.jlab.inventory;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Item extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
JTextField volume = new JTextField("#vol");
JButton deleteItem = new JButton("-del");
Inventory inventory;
public Item(Inventory inv) {
deleteItem.addActionListener(this);
this.setBackground(Color.gray);
this.setPreferredSize(new Dimension(400, 50));
this.add(volume);
this.add(deleteItem);
inventory = inv;
}
public void actionPerformed(ActionEvent e) {
System.out.println("item action");
inventory.removeItem(this);
}
}
package com.jlab.inventory;
import java.awt.Color;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.awt.event.*;
public class Inventory implements ActionListener {
JTextField volumeTotal = new JTextField("Volume Total Value"); // count total item Volume
JFrame window = new JFrame(); // new items to be added during run
JButton newItemButton = new JButton("Add new item");
public ArrayList<Item> itemList = new ArrayList<Item>(); // not static
public static void main(String args[]) {
Inventory store = new Inventory();
store.runStore();
}
public Inventory() { // constructor initializes program's main interface and data
newItemButton.addActionListener(this);
window.setPreferredSize(new Dimension(460, 700));
window.setLayout(new FlowLayout());
window.add(volumeTotal);
window.add(newItemButton);
window.pack();
window.setVisible(true);
}
public void runStore() {
System.out.println("revalidating");
window.revalidate();
}
public void actionPerformed(ActionEvent e) {
System.out.println("adding new item");
itemList.add(new Item(this));
System.out.println(itemList.size());
window.add(itemList.get(itemList.size()-1));
runStore();
}
public void removeItem(Item item) { // -removes Item passed in: from ArrayList + GUI
itemList.remove(item);
window.remove(item);
runStore();
}
//addItem(Item i) {
// add item to arraylist
// add item to gui
//}
}
When modifying the contents of a visible container, you have to validate and repaint it. So I modified your
removeItem()method like below and it works now.