Java Swing将对象添加到表中

时间:2018-01-30 22:42:21

标签: java swing

我很难将对象添加到表中。 我的表有4列,我试图添加的对象是通过用户输入创建的。 当用户点击按钮"验证"时,我试图将其添加到表中。 (我没有发布我的所有代码,但这个代码太长了,但你在这里有重要的部分)

final Object[] columnNames = {"Card type", "Account Number","Card Number", "Amount", "Select"};
final Cards[][] rows = new MyCards[columnNames.length][];
table = new JTable(rows, columnNames);

approve.addActionListener(new ActionListener() { 
            public void actionPerformed(ActionEvent e) {
                Cards newCard = new Cards();
                if(comboCardTypes.getSelectedItem().equals(Cards.CardType.DEBIT)){
                    newCard.setType(Cards.CardType.DEBIT);  

                }
                if(comboCardTypes.getSelectedItem().equals(Cards.CardType.CREDIT)){
                    newCard.setType(Cards.CardType.CREDIT);
                }
                newCard.setAccountNb(Integer.parseInt(answerTxt2.getText()));
                newCard.setCardNumber(Integer.parseInt(answerTxt3.getText()));
                newCard.setMoneyCurrent(Double.parseDouble(answerTxt4.getText()));
                table.add(newCard, index);


                index++;
            } 
        });

2 个答案:

答案 0 :(得分:1)

使用table = new JTable(rows, columnNames);在幕后构建DefaultTableModel

DefaultTableModel以非结构化的方式管理各个行和列,这意味着您必须分解任何对象值并将它们推入模型中,并从您从表中提取的数据中重新组合任何对象。

这会产生相反的效果,尤其是当您已经有一个包含要管理的基本数据的对象时。

更好的解决方案是定义和使用您自己的TableModel,它旨在管理对象本身。

例如......

public static class CardTableModel extends AbstractTableModel {

    protected static String[] COLUMN_NAMES = {"Card type", "Account Number","Card Number", "Amount", "Select"};
    protected static Class[] COLUMN_CLASSES = {String.class, Integer.class, Integer.class, Double.class, Boolean.class};        

    private Set<Integer> selected;
    private List<Card> cards;

    public CardTableModel() {
        cards = new ArrayList<>(25);
        selected = new TreeSet<Integer>();
    }

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

    @Override
    public int getColumnCount() {
        return COLUMN_NAMES.length;
    }

    @Override
    public String getColumnName(int column) {
        return COLUMN_NAMES[column];
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        return COLUMN_CLASSES[columnIndex];
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return columnIndex == 4;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Card card = cards.get(rowIndex);
        switch (columnIndex) {
            case 0: return card.getCartType().toString();
            case 1: return card.getAccountNumber();
            case 2: return card.getCardNumber();
            case 3: return card.getAmmount();
            case 4: return selected.contains(rowIndex);
        }
        return null;
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        if (columnIndex != 4) {
            return;
        }
        if (!(aValue instanceof Boolean)) {
            return;
        }
        boolean isSelected = (Boolean)aValue;
        if (isSelected) {
            selected.add(rowIndex);
        } else {
            selected.remove(rowIndex);
        }

        fireTableCellUpdated(rowIndex, columnIndex);
    }

    public void add(Card card) {
        int index = cards.size();
        cards.add(card);
        fireTableRowsInserted(index, index);
    }

    public Card cardAt(int rowIndex) {
        return cards.get(rowIndex);
    }

}

然后,您可以将Card信息保存在一个位置,并降低其不同步的风险,并且无需解码&#34;和&#34;编码&#34;数据。

有关详细信息,请查看How to use tables

可运行的示例......

这是一个简单的可运行示例,演示了使用CardTableModel

的基本概念
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;

public class Test {

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

    private CardTableModel model;

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

                model = new CardTableModel();
                JTable table = new JTable(model);

                JButton btn = new JButton("Add");
                btn.addActionListener(new ActionListener() {
                    private Random rnd = new Random();
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Card.CardType type;
                        int accountNumber = rnd.nextInt();
                        int cardNumnber = rnd.nextInt();
                        double amount = rnd.nextDouble();
                        if (rnd.nextBoolean()) {
                            type = Card.CardType.CREDIT;
                        } else {
                            type = Card.CardType.DEBIT;
                        }

                        Card card = new MyCard(type, accountNumber, cardNumnber, amount);
                        model.add(card);
                    }
                });

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

    public interface Card {
        public enum CardType {
            CREDIT, DEBIT;
        }

        public CardType getCardType();
        public int getAccountNumber();
        public int getCardNumber();
        public double getAmount();
    }

    public class MyCard implements Card {
        private CardType cardType;
        private int accountNumber;
        private int cardNumber;
        private double amount;

        public MyCard(CardType cardType, int accountNumber, int cardNumber, double amount) {
            this.cardType = cardType;
            this.accountNumber = accountNumber;
            this.cardNumber = cardNumber;
            this.amount = amount;
        }

        @Override
        public CardType getCardType() {
            return cardType;
        }

        public void setCardType(CardType cardType) {
            this.cardType = cardType;
        }

        @Override
        public int getAccountNumber() {
            return accountNumber;
        }

        public void setAccountNumber(int accountNumber) {
            this.accountNumber = accountNumber;
        }

        @Override
        public int getCardNumber() {
            return cardNumber;
        }

        public void setCardNumber(int cardNumber) {
            this.cardNumber = cardNumber;
        }

        @Override
        public double getAmount() {
            return amount;
        }

        public void setAmount(double amount) {
            this.amount = amount;
        }

    }

    public static class CardTableModel extends AbstractTableModel {

        protected static String[] COLUMN_NAMES = {"Card type", "Account Number", "Card Number", "Amount", "Select"};
        protected static Class[] COLUMN_CLASSES = {String.class, Integer.class, Integer.class, Double.class, Boolean.class};

        private Set<Integer> selected;
        private List<Card> cards;

        public CardTableModel() {
            cards = new ArrayList<>(25);
            selected = new TreeSet<Integer>();
        }

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

        @Override
        public int getColumnCount() {
            return COLUMN_NAMES.length;
        }

        @Override
        public String getColumnName(int column) {
            return COLUMN_NAMES[column];
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return COLUMN_CLASSES[columnIndex];
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return columnIndex == 4;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Card card = cards.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    return card.getCardType().toString();
                case 1:
                    return card.getAccountNumber();
                case 2:
                    return card.getCardNumber();
                case 3:
                    return card.getAmount();
                case 4:
                    return selected.contains(rowIndex);
            }
            return null;
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            if (columnIndex != 4) {
                return;
            }
            if (!(aValue instanceof Boolean)) {
                return;
            }
            boolean isSelected = (Boolean) aValue;
            if (isSelected) {
                selected.add(rowIndex);
            } else {
                selected.remove(rowIndex);
            }

            fireTableCellUpdated(rowIndex, columnIndex);
        }

        public void add(Card card) {
            int index = cards.size();
            cards.add(card);
            fireTableRowsInserted(index, index);
        }

        public Card cardAt(int rowIndex) {
            return cards.get(rowIndex);
        }

    }
}

答案 1 :(得分:0)

假设您的行和列如下所示,那么您唯一缺少的就是TableModel。所以添加到JTable的整个结构必须是这样的

String[] columnNames = {"First Name",
        "Last Name",
        "Sport",
        "# of Years",
        "Vegetarian"};
Object[][] rowData = {
        {"Kathy", "Smith",
         "Snowboarding", new Integer(5), new Boolean(false)},
        {"John", "Doe",
         "Rowing", new Integer(3), new Boolean(true)},
        {"Sue", "Black",
         "Knitting", new Integer(2), new Boolean(false)},
        {"Jane", "White",
         "Speed reading", new Integer(20), new Boolean(true)},
        {"Joe", "Brown",
         "Pool", new Integer(10), new Boolean(false)}
    };
JTable table = new JTable();
TableModel dataModel = new AbstractTableModel() {
    public String getColumnName(int col) {
        return columnNames[col].toString();
    }
    public int getRowCount() { return rowData.length; }
    public int getColumnCount() { return columnNames.length; }
    public Object getValueAt(int row, int col) {
        return rowData[row][col];
    }
    public boolean isCellEditable(int row, int col)
        { return true; }
    public void setValueAt(Object value, int row, int col) {
        rowData[row][col] = value;
        fireTableCellUpdated(row, col);
    }
};
table.setModel(dataModel);

如果你试试这个代码,你会发现它完全正常。但你只需要使它与你的代码兼容(因为我对你的代码一无所知,我不能用你的代码作为例子)