带自定义模型的java Jtable

时间:2014-06-11 08:22:54

标签: java swing jtable tablemodel

我正试图在我的一个Jtable中解雇一个变种。

我有一个Parser类和一个commandItem类;

public class CommandItem {    
  private Integer quantity;
  private final MenuItem item;
  private Double totalPrice;
  public Integer getQuantity() {
    return quantity;
  }   
  public MenuItem getMenuItem(){
    return item;
  }
  public void setQuantity(Integer quantity) {
    this.quantity = quantity;
    this.calculatePrice();
  }

  public CommandItem(Integer quantity, MenuItem item) {
    this.quantity = quantity;
    this.item = item;
    this.calculatePrice();      
  }    
  private void calculatePrice(){
    this.totalPrice = this.quantity * this.item.getPrice();        
  }
  public Double getTotalPrice() {
    return totalPrice;
  }    
}

public class MenuParser {
  private ArrayList<CommandItem> commandItems;

  public ArrayList<CommandItem>  getCommandItems(){
    return commandItems;
  }

  //somewhere in the code
  commandItems.add( add(new CommandItem( 2, item));
  Menu.updateTable(commandItems);

}

并在我的框架中:

public class Menu extends javax.swing.JFrame {

  private static ModelCommandItems model;
  private static JTable table;

  public Menu() {
    initComponents();

    menuParser = new MenuParser();


    Menu.model = new ModelCommandItems((this.menuParser.getCommandItems()));        
    //at this stage, model is empty
    Menu.table = new JTable(Menu.model);

    JScrollPane scrollPane = new JScrollPane(Menu.table);
    jPanel6.add(scrollPane);
  }

  public static void updateTable(ArrayList<CommandItem>  items){
    Menu.model.setData(items);
    Menu.table.setModel(Menu.model);
  }

我的ModelCommandItems表模型几乎遵循标准

public class ModelCommandItems implements TableModel {

  private final String[] columnNames;

  private ArrayList<CommandItem> data;

  public ModelCommandItems(ArrayList<CommandItem> data) {
    this.data = data;
    this.columnNames = new String[]{"quantity", "name", "price"};
  }

  public void setData(ArrayList<CommandItem> data) {
    this.data = data;        
  }

我无法让我的表实际显示arrayList的内容。

2 个答案:

答案 0 :(得分:0)

此处您必须检查..“ArrayList”列值应与“quantity”,“name”,“price”值匹配,Means Array列项也应该在3中。

答案 1 :(得分:0)

除了@MadProgrammer评论之外,你没有告诉表应该从哪个位置获取应该包含的值。

为此,您需要从ModelCommandItems

延长AbstractTableModel课程

例如

public class ModelCommandItems extends AbstractTableModel {

List<Object[]> list; // init list with your data

public int getRowCount() {
    // TODO Auto-generated method stub
    return list.size();
}

public int getColumnCount() {
    // check the list size before
    return list.get(0).length;
}

public Object getValueAt(int rowIndex, int columnIndex) {
    Object[] row = list.get(rowIndex);
    return row[columnIndex];
}

}