-2

好的,所以我所拥有的是一个带有表格设置的 GUI,(大多数情况下,仍然存在一些问题)但我需要知道的是这个。将以下代码:

public void removeSelectedRows(JTable table)
    {
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        int[] rows = table.getSelectedRows();
        for (int x=0;x<rows.length;++x){
            model.removeRow(rows[x]-x);
        }
        for (int x=0;x<animals;++x)
        {
            if (Pets[x][0].equalsIgnoreCase(table.getValueAt(table.getSelectedRow(),0)+""))
            {
                Pets[x][0]=null;
                Pets[x][1]=null;
                Pets[x][2]=null;
                Pets[x][3]=null;
                Pets[x][4]=null;
            }
        }
        animals=animals-1;
    }

删除用户选择的行?(我的意思是简单地单击该行,然后单击删除按钮)。我不希望删除行本身,但我希望删除用户选择的行中包含的值。

4

1 回答 1

2

准备好弄脏你的手。

在某些时候,DefaultTableModel将不再满足您的需求,您应该准备好推出自己的实现。

第一件事。您正在使用面向对象的语言,您应该利用这一事实并将您的数据表示为对象。

其次,当从表中删除多个值时,很快就会变得非常棘手。删除第一行后,索引不再匹配,您需要某种方法将值映射回它们出现在模型中的索引。

第三,可见的行索引可能与模型的不同,尤其是在对表进行排序时。

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;

public class TestJTable {

    public static void main(String[] args) {
        new TestJTable();
    }

    public TestJTable() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                List<Pet> pets = new ArrayList<>(25);
                pets.add(new Pet("Tyrannosauridae", "TYRANNOSAURUS", 20, 35));
                pets.add(new Pet("Dromaeosauridae", "VELOCIRAPTOR", 45, 90));
                pets.add(new Pet("Ceratopsidae", "TRICERATOPS", 15, 30));
                pets.add(new Pet("Stegosauridae", "STEGOSAURUS", 22, 25));
                pets.add(new Pet("Titanosauridae", "MALAWISAURUS", 22, 25));
                pets.add(new Pet("Compsognathidae", "COMPSOGNATHUS", 8, 25));
                pets.add(new Pet("Brachiosauridae", "BRACHIOSAURUS", 8, 25));
                pets.add(new Pet("Diplodocidae", "DIPLODOCUS", 8, 25));

                final PetTableModel model = new PetTableModel(pets);
                final JTable table = new JTable(model);

                InputMap im = table.getInputMap(JTable.WHEN_FOCUSED);
                ActionMap am = table.getActionMap();
                im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "delete");
                am.put("delete", new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        int[] indices= table.getSelectedRows();
                        // Convert the view's row indices to the models...
                        int[] mapped = new int[indices.length];
                        for (int index = 0; index < indices.length; index++) {
                            mapped[index] = table.convertRowIndexToModel(indices[index]);
                        }
                        model.removePets(mapped);
                    }
                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(table));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class PetTableModel extends AbstractTableModel {

        private List<Pet> pets;

        public PetTableModel() {
            pets = new ArrayList<>(25);
        }

        public PetTableModel(List<Pet> pets) {
            this.pets = pets;
        }

        @Override
        public int getRowCount() {
            return pets.size();
        }

        public void removePets(int... indicies) {
            // Build a tempory list of Pet objects based
            // on the supplied indices...
            List<Pet> old = new ArrayList<>(indicies.length);
            for (int index : indicies) {
                old.add(pets.get(index));
            }

            // For each pet, get it's index in the model
            // remove it from the model
            // notify any listeners of the change to the model...
            for (Pet pet : old) {
                int index = pets.indexOf(pet);
                pets.remove(pet);
                fireTableRowsDeleted(index, index);
            }
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            Class clazz = String.class;
            switch (columnIndex) {
                case 2:
                case 3:
                    clazz = Float.class;
            }
            return clazz;
        }

        @Override
        public String getColumnName(int column) {
            String name = "??";
            switch (column) {
                case 0:
                    name = "Breed";
                    break;
                case 1:
                    name = "Category";
                    break;
                case 2:
                    name = "Buy Price";
                    break;
                case 3:
                    name = "Sell Price";
                    break;
            }
            return name;
        }

        @Override
        public int getColumnCount() {
            return 4;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Pet pet = pets.get(rowIndex);
            Object value = null;
            switch (columnIndex) {
                case 0:
                    value = pet.getBreed();
                    break;
                case 1:
                    value = pet.getCategory();
                    break;
                case 2:
                    value = pet.getBuyPrice();
                    break;
                case 3:
                    value = pet.getSellPrice();
                    break;
            }
            return value;
        }

        public void add(Pet pet) {
            pets.add(pet);
            fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1);
        }

    }

    public class Pet {

        private String breed;
        private String category; 
        private float buyPrice; 
        private float sellPrice; 

        public Pet(String breed, String category, float buyPrice, float sellPrice) {
            this.breed = breed;
            this.category = category;
            this.buyPrice = buyPrice;
            this.sellPrice = sellPrice;
        }

        public String getBreed() {
            return breed;
        }

        public float getBuyPrice() {
            return buyPrice;
        }

        public String getCategory() {
            return category;
        }

        public float getSellPrice() {
            return sellPrice;
        }

    }

}
于 2013-02-28T03:32:34.297 回答