简体   繁体   English

如何从ArrayList填充jTable?

[英]How to populate a jTable from an ArrayList?

The program is meant to take the user input and store it in an arraylist. 该程序旨在获取用户输入并将其存储在arraylist中。 Then the user can print the details onto the jtable. 然后,用户可以将详细信息打印到jtable上。 After, he can remove an item from the jtable by selecting a row. 之后,他可以通过选择一行从jtable中删除一个项目。

I have 2 problems. 我有两个问题。

First problem is that I get errors while looping through the arraylist. 第一个问题是遍历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: 问题在这里,遍历arraylist:

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

    }

    model.addRow(book);

I have 3 classes, Test, Library, and Book 我有3个班级:测试,图书馆和书籍

Test Class 测试班

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


    }

Library Class 图书馆课

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

Book Class 书类

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";

  }

  }

EDIT 编辑

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();

If you want to use your Library class as the nucleus of a TableModel, you can, but you'll need to: 如果要使用Library类作为TableModel的核心,可以,但是您需要:

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

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. JTable教程可以帮助您进一步解决此问题,该站点上发布的许多示例也可以通过一些搜索就可以找到。


Edit 编辑
Regarding your latest code, you're still not calling any fireXXX methods when the model's data changes, which suggests that you haven't studied the tutorial as I've suggested. 关于您的最新代码,当模型的数据更改时,您仍然不会调用任何fireXXX方法,这表明您没有像我建议的那样学习本教程。 Please do this first as it can explain things far better than we can. 请首先做到这一点,因为它可以解释的事情远比我们所能。

Here is the link: Tutorial: How to use Tables 这里是链接: 教程:如何使用表
And here are some useful stackoverflow answers: 这是一些有用的stackoverflow答案:

You can easily search StackOverflow for more examples. 您可以轻松搜索StackOverflow以获取更多示例。 Luck. 运气。

Try this code 试试这个代码

  JTable  booktable = new JTable();


            String[] colName = { "Call No", "Name", "Category", "Author ",
                    "Publisher", "From", "Price", "Remarks" ,"Edit/Delete"};
            booktable.getTableHeader().setBackground(Color.WHITE);
            booktable.getTableHeader().setForeground(Color.BLUE);
            Font Tablefont = new Font("Book Details", Font.BOLD, 12);
            booktable.getTableHeader().setFont(Tablefont);

            List<Book> books = new ArrayList<Book>();
            books = ServiceFactory.getBookService().findAllBook();

            Object[][] object = new Object[100][100];
            int i = 0;
            if (books.size() != 0) {
                for (Book book : books) {
                    object[i][0] = book.getCallNo();
                    object[i][1] = book.getName();
                    object[i][2] = book.getCategory_id().getName();
                    object[i][3] = book.getAuthor();
                    object[i][4] = book.getPublisher();
                    object[i][5] = book.getFrom();
                    object[i][6] = book.getPrice();
                    object[i][7] = book.getRemark();
                    object[i][8] = getEditDeleteButton();
                    i++;
                    booktable = new JTable(object, colName);
                }
            }

To populate JTable from your ArrayList of Books, you need to create DefaultTableModel with Object[] that contains column names as a parameter, and also number of rows (start with 0) as a parameter. 要从您的ArrayList中填充JTable,您需要使用Object []创建DefaultTableModel,该Object []包含列名作为参数,还包含行数(以0开头)作为参数。 Loop through your ArrayList, get Title and Author fields, place them in Object[], add row to table model using that Object[] as a parameter and then set table model using DefaultTableModel that you created at the beginning of this method as parameter. 遍历ArrayList,获取Title和Author字段,将它们放在Object []中,使用该Object []作为参数将行添加到表模型中,然后使用在此方法开始时创建的DefaultTableModel作为参数来设置表模型。 Method for adding data from ArrayList to JTable: 将数据从ArrayList添加到JTable的方法:

public void showDataInTable(ArrayList<Book> listOfBooks, JTable table){
     DefaultTableModel model = new DefaultTableModel(new Object[]{"Title", "Author"}, 0);
     for(Book book:listOfBooks){
          model.addRow(new Object[]{book.getTitle(), book.getAuthor()});
     }
     table.setModel(model);
}

Now if you want to delete a selected Book from JTable and also from ArrayList you could use Iterator. 现在,如果要从JTable和ArrayList中删除选定的Book,则可以使用Iterator。 Instantiate iterator, loop through it using hasNext() method as condition in while loop. 实例化迭代器,并在has循环中使用hasNext()方法循环遍历它。 Instantiate new Book object using iterators next() method. 使用迭代器的next()方法实例化新的Book对象。 In if statement check if title and author from that Book matches with Title and Author from selected row in your JTable. 在if语句中,检查该书的标题和作者是否与JTable中所选行的标题和作者相匹配。 If you have a match iterator will remove that Book from ArrayList loop will stop because of break command. 如果您有匹配的迭代器,则它将从ArrayList中删除该Book,该循环将由于break命令而停止。 Then call first method I wrote and it will show all Books from ArrayList without that book that you deleted. 然后调用我编写的第一个方法,它将显示ArrayList中所有未删除的书。

    public void deleteRecord(JTable table, ArrayList<Book> listOfBooks){
         Iterator<Book> it = listOfBooks.iterator();
         while(it.hasNext()){
              Book book = it.next();
              if(book.getTitle.equals(String.valueOf(table.getValueAt(table.getSelectedRow(), 0))) && book.getAuthor.equals(String.valueOf(table.getValueAt(table.getSelectedRow(), 1)))){
              it.remove();
              break;
              }
         }
         showDataInTable(listOfBooks, table);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM