如何从 ArrayList 填充 jTable? [英] How to populate a jTable from an ArrayList?

查看:41
本文介绍了如何从 ArrayList 填充 jTable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该程序旨在接收用户输入并将其存储在一个数组列表中.然后用户可以将详细信息打印到 jtable 上.之后,他可以通过选择一行从 jtable 中删除一个项目.

The program is meant to take the user input and store it in an arraylist. Then the user can print the details onto the jtable. After, he can remove an item from the jtable by selecting a row.

我有两个问题.

第一个问题是我在遍历数组列表时出错.

First problem is that I get errors while looping through the arraylist.

第二个问题是当用户删除一行时,该项目将从表中删除,但我也想从数组中删除该特定项目.这样如果用户再次单击打印按钮,该项目就不会再次出现.

Second problem is when the user removes a row, the item is removed from the table but I also want to delete that particular item from the array too. So that if the user clicks on print button again, the item doesn't appear again.

问题在这里,循环遍历数组列表:

Problem here, Looping through arraylist:

model = (DefaultTableModel) table.getModel();
    for (int i=0; i<lib.data.size(); i++){
            book = lib.data.get(i);

    }

    model.addRow(book);

我有 3 个课程,测试、图书馆和书籍

I have 3 classes, Test, Library, and Book

测试类

 import javax.swing.*;
  import java.awt.*;
   import java.awt.event.*;
  import java.util.*;
   import javax.swing.table.*;
      import javax.swing.border.*;

   public class Test extends JFrame{

    static Library lib = new Library();
    static Book book = new Book();

    private JFrame frame = new JFrame("Book");
    private JPanel panel = new JPanel();

    private JLabel label2, label3;

    private JTextField textfield1, textfield2;

    private JButton button1, button2, button3;

    private DefaultTableModel model;
    private JTable table;
    private JScrollPane pane;

    void form(){

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
    panel.setLayout(null);

    model = new DefaultTableModel();
    table = new JTable(model);
    pane = new JScrollPane(table);
    model.addColumn("Title");
    model.addColumn("Author");
    pane.setBounds(11, 221, 125, 21);
    panel.add(pane);

    pane.setSize(200, 100);
    pane.setVisible(true);
    setVisible(false);
    setSize(60, 60);

    label2 = new JLabel("title:");
    label2.setBounds(9, 61, 123, 13);
    panel.add(label2);

    label3 = new JLabel("author:");
    label3.setBounds(9, 91, 123, 13);
    panel.add(label3);


    textfield1 = new JTextField(10);
    textfield1.setBounds(121, 63, 125, 21);
    panel.add(textfield1);

    textfield2 = new JTextField(10);
    textfield2.setBounds(121, 93, 125, 21);
    panel.add(textfield2);

    button1 = new JButton("Store");
    button1.setBounds(351, 226, 125, 21);
    panel.add(button1);

    button2= new JButton("View");
    button2.setBounds(351, 256, 125, 21);
    panel.add(button2);

    button3= new JButton("Delete");
    button3.setBounds(351, 286, 125, 21);
    panel.add(button3);


    frame.add(panel);
    frame.setSize(545,540);
    frame.setVisible(true);

    //Store
    button1.addActionListener(new ActionListener(){
    public  void actionPerformed(ActionEvent e){

    String title = textfield1.getText();
    String author = textfield2.getText();

    book = new Book(title, author);
    lib.addBook(book);

    System.out.println(book);

    }
    });

    //View
    button2.addActionListener(new ActionListener(){
    public  void actionPerformed(ActionEvent e){

    model = (DefaultTableModel) table.getModel();    

            String title = textfield1.getText();
            String author = textfield2.getText();

            book = new Book(title, author);
    lib.addBook(book);


    book = new Book();
    book.setTitle(title);
    book.setAuthor(author);
    lib.addBook(book);
    lib.fireTableDataChanged();



    }
    });


    //Delete
    button3.addActionListener(new ActionListener(){
    public  void actionPerformed(ActionEvent e){

    model = (DefaultTableModel) table.getModel();

    int numRows = table.getSelectedRows().length; 
    for(int i=0; i<numRows ; i++ ) 
    model.removeRow(table.getSelectedRow());

    }
    });


    }

    public static void main(String [] args){

        Test a = new Test();
        a.form();
        }


    }

图书馆类

   import java.util.*;
     import javax.swing.*;
   import javax.swing.table.AbstractTableModel;

   class Library extends AbstractTableModel {

List<Book> data;
String[] columnNames = {"Title", "Author"};

public Library() {
    data = new ArrayList<Book>();

    //data.add(new Book("Java", "William"));



}


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

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

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

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    Book book = data.get(rowIndex);
    switch (columnIndex) {
    case 0:
        return book.getTitle();
    case 1:
        return book.getAuthor();
    default:
        return null;
    }
}

public void addBook(Book book){

    int firstRow = data.size() - 1;
    int lastRow = firstRow;
    fireTableRowsInserted(firstRow, lastRow);
    data.add(book);

}

public void fireTableDataChanged() {

}   

public void removeBook(Book book){
        data.remove(book);
}
   }

书本课

public class Book{

private String title;
private String author;

public Book(){

title = "";
author = "";

}

public Book(String title, String author){

this.title = title;
this.author = author;

}

public String getTitle(){
    return title;   
}
public void setTitle(String title){
    title = title;  
}
public String getAuthor(){
    return author;
}
public void setAuthor(String author){
    author = author;
}




public String toString(){

    return  "Title: " + getTitle() + "\n" + 
            "Author: " + getAuthor() + "\n";

  }

  }

编辑

这是我添加到我的库类中的内容:

This is what I added to my library class:

      public void addBook(Book book){

    int firstRow = data.size() - 1;
    int lastRow = firstRow;
    fireTableRowsInserted(firstRow, lastRow);
    data.add(book);

}

public void fireTableDataChanged() {

}

这是我添加到主类(按钮)中的内容:

This is what I added to my main class (button):

           book = new Book();
    book.setTitle(title);
    book.setAuthor(author);
    lib.addBook(book);
    lib.fireTableDataChanged();

推荐答案

如果你想使用你的 Library 类作为 TableModel 的核心,你可以,但你需要:

If you want to use your Library class as the nucleus of a TableModel, you can, but you'll need to:

  • 让库类扩展 AbstractTableModel
  • Library 将需要更多方法,例如 getRowCount()getColumnCount()getColumnClass(...)getValueAt(...)setValueAt(...) 以及实际上 AbstractTableModel 类的所有抽象方法.
  • addBook(Book book) 方法需要调用 AbstractTableModel 的 fireXXX(...) 方法之一来通知听众添加.
  • 考虑给它一个 removeBook(Book book) 方法,同样在删除后触发通知方法.
  • have the Library class extend AbstractTableModel
  • Library will need more methods such as getRowCount(), getColumnCount(), getColumnClass(...), getValueAt(...), setValueAt(...) and in fact all the abstract methods of the AbstractTableModel class.
  • The addBook(Book book) method would need to call one of the fireXXX(...) methods of AbstractTableModel to notify listeners of the addition.
  • Consider giving it a removeBook(Book book) method that likewise fires a notification method after removal.

JTable 教程可以帮助您进一步解决这个问题,本网站上发布的许多示例也可以通过一些搜索找到.

The JTable tutorial can help you further with this as can the many examples posted on this site which can be found with a little searching.

编辑
关于您的最新代码,当模型的数据更改时,您仍然没有调用任何 fireXXX 方法,这表明您没有按照我的建议学习教程.请先执行此操作,因为它可以比我们更好地解释事情.

这是链接:教程:如何使用表格
这里有一些有用的 stackoverflow 答案:

Here is the link: Tutorial: How to use Tables
And here are some useful stackoverflow answers:

  • dont updating jtable
  • Check Boxes not able to be Selected — They are Editable! Java Swing (MadProgrammer has some excellent code you would do well to study here).

您可以轻松搜索 StackOverflow 以获取更多示例.运气.

You can easily search StackOverflow for more examples. Luck.

这篇关于如何从 ArrayList 填充 jTable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆