gpt4 book ai didi

Java Swing 将对象添加到表中

转载 作者:行者123 更新时间:2023-11-30 06:19:14 24 4
gpt4 key购买 nike

我在向表添加对象时遇到困难。我的表有 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++;
}
});

最佳答案

使用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);
}

}

这样您就可以在一个位置维护信息,并降低其不同步的风险,并且无需“解码”和“编码”数据。

看看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);
}

}
}

关于Java Swing 将对象添加到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48531699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com