2

在此处输入图像描述

我已经从原始帖子中更新了这个,现在我可以添加/删除项目,但是最后一个项目被卡住了......这似乎与按钮状态有关......最后一个项目的“del”按钮将变灰...单击时,“添加新项目”按钮似乎有时会影响这一点。另外,如果您对如何改进我可能的粗略代码有任何其他意见......

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

1 回答 1

0

修改可见容器的内容时​​,您必须验证并重新绘制它。所以我修改了你的removeItem()方法,如下所示,它现在可以工作了。

public void removeItem(Item item) { // -removes Item passed in: from ArrayList + GUI
    itemList.remove(item);
    window.remove(item);
    window.validate();
    window.repaint();
    runStore();
}
于 2012-09-04T08:32:59.900 回答