gpt4 book ai didi

java - 带有行过滤器的 JTable - 如何仅迭代过滤的行

转载 作者:行者123 更新时间:2023-11-30 03:31:36 25 4
gpt4 key购买 nike

我有JTable,其中行由RowFilter过滤(行B被隐藏)。

如何迭代仅可见行(而不是隐藏的 B 行)?

不幸的是,下面的示例还打印了我想跳过的 B 行。

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class JTableFilterDemo {
public static void main(String[] args) {
Object[][] data = { { "A", 5 }, { "B", 2 }, { "C", 4 }, { "D", 8 } };
String columnNames[] = { "Item", "Value" };
TableModel model = new DefaultTableModel(data, columnNames) {
public Class<?> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
JTable table = new JTable(model);

RowFilter<Object, Object> filter = new RowFilter<Object, Object>() {
public boolean include(Entry entry) {
Integer population = (Integer) entry.getValue(1);
return population.intValue() > 3;
}
};

TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(
model);
sorter.setRowFilter(filter);
table.setRowSorter(sorter);
JScrollPane scrollPane = new JScrollPane(table);
JFrame frame = new JFrame("Filtering Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton btnNewButton = new JButton("Print values");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int row = 0;row < table.getModel().getRowCount();row++) {
System.out.println(table.getModel().getValueAt(row, 0));
}
}
});
frame.getContentPane().add(btnNewButton, BorderLayout.SOUTH);
frame.getContentPane().add(scrollPane);
frame.setSize(300, 200);
frame.setVisible(true);
}
}

最佳答案

线条

         for(int row = 0;row < table.getModel().getRowCount();row++) {
System.out.println(table.getModel().getValueAt(row, 0));
}

应替换为:

            for(int row = 0;row < table.getRowCount();row++) {
System.out.println(table.getModel().getValueAt(table.convertRowIndexToModel(row), 0));
}

关于java - 带有行过滤器的 JTable - 如何仅迭代过滤的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28878819/

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