Java - 按钮从arrayList和window(jframe)中删除当前项/对象

时间:2012-09-03 13:59:26

标签: java arraylist

enter image description here

我已经从原帖更新了这个,现在我可以添加/删除项目但是剩下的最后一项被卡住......这似乎与按钮状态有关...最后一项的“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
    //}
}

1 个答案:

答案 0 :(得分: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();
}