【问题标题】:Filter jTable by ImageIcon column按 ImageIcon 列过滤 jTable
【发布时间】:2015-08-03 07:20:45
【问题描述】:

我有一个 JTable 有 3 列,第二列有 ImageIcons。我想仅按图像名称过滤该列,但有一个问题:该列的内容是图像的完整路径,如果我输入路径中的单词/字母,我会收到所有记录.

例如

这是我的jTabelgetColumnClass

这是没有getColumnClass

如果我在Enter value 字段中输入“资源”,则没有任何变化,因为所有单元格都有此内容。

有没有什么方法可以只按图片名称过滤而不用扩展名(例如橙色、沃达丰、cosmote)?

下面是我的代码:

package main;

import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

@SuppressWarnings("serial")
public class PhoneBook extends JFrame {

        private JPanel panel1;
        private static ImageIcon frameIcon = new ImageIcon("resources/appIcons/icon.png");
        private JComboBox<String> comboBox;
        private JComboBox<String> filterColumnBox;     
        private MyTableModel model;
        private static ArrayList<String> phoneNumberList = new ArrayList<String>();    
        private String filterValue;
        private int sortColumn;

        public PhoneBook(String group) {

        setDesign(group);        
    }

        /**
         * Set column filter
         */
    private void setColumnIndex() {
        try
        {
                if(filterColumnBox.getSelectedItem().equals("Name")) {
                        sortColumn = 0;
                }
                else if(filterColumnBox.getSelectedItem().equals("Operator")) {
                        sortColumn = 1;
                }
                else {
                        sortColumn = 2;  
                }

                System.out.println("Functia setColumnIndex: " + filterColumnBox.getSelectedItem() + " " + sortColumn);
        } catch (Exception e)
        {
                System.out.println("Exceptie: " + e.getMessage());
        }
    }

    /**
     *  Add phone numbers to ComboBox
     * @param cbColumn
     */
        private void comboBoxColumn(TableColumn cbColumn) {  

                getNumbers();

                comboBox = new JComboBox<String>();
        for (String c : phoneNumberList) {
                comboBox.addItem(c);
        }
        cbColumn.setCellEditor(new DefaultCellEditor(comboBox));

        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setToolTipText("Click for numbers");
        cbColumn.setCellRenderer(renderer);
        }

        /**
         * Get phone number and add into phoneNumberList
         */
        public void getNumbers() {
                phoneNumberList.add("0733333333");
                phoneNumberList.add("0744444444");
        }

        /**
         * Extends AbstractTableModel for table model
         */
    class MyTableModel extends AbstractTableModel {
        private String[] columnNames = {"Name",
                                        "Operator",
                                        "Numbers"};
        private Object[][] data = {
                    {"Kathy Smith", new ImageIcon("resources/opIcons/orange.png"), "0733333331"},
                    {"John Doe", new ImageIcon("resources/opIcons/vodafone.png"), "0733333332"},
                    {"Sue Black", new ImageIcon("resources/opIcons/vodafone.png"), "0733333333"},
                    {"Jane White", new ImageIcon("resources/opIcons/cosmote.png"), "0733333334"},
                    {"Jane White", new ImageIcon("resources/opIcons/cosmote.png"), "0733333335"},
                    {"Jane White", new ImageIcon("resources/opIcons/cosmote.png"), "0733333336"},
                    {"Joe Brown", new ImageIcon("resources/opIcons/orange.png"), "0733333337"}
        };

        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }

        /*public Class<?> getColumnClass(int column) {
            Class<?> returnValue;
            if ((column >= 0) && (column < getColumnCount())) {
                System.out.println("Functia getColumnClass: " + column);
              returnValue = getValueAt(0, column).getClass();
            } else {
              returnValue = Object.class;
            }
            return returnValue;
          }*/

        //For editable fields (ComboBox)
        public boolean isCellEditable(int row, int col) {
            if (col < 2) {
                return false;
            } else {
                return true;
            }
        }      

        //For changing values in ComboBox
        public void setValueAt(Object value, int row, int col) {  
            data[row][col] = value;
            fireTableCellUpdated(row, col);          
        }      
    }  

    /**
     * GUI design
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
        private void setDesign(String group) {

        setTitle("Phone Book Application - " + group);         
        setSize(600, 500);
        setIconImage(frameIcon.getImage());

        model = new MyTableModel();
        final JTable table = new JTable(model);
        table.setPreferredScrollableViewportSize(new Dimension(500, 200));
        table.setFillsViewportHeight(false);

        final TableRowSorter<MyTableModel> sorter = new TableRowSorter<MyTableModel>(model);
        table.setRowSorter(sorter);

        //Table row height
        table.setRowHeight(35);


        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        //Render last column

        comboBoxColumn(table.getColumnModel().getColumn(2));

        GridBagLayout gridBagLayout = new GridBagLayout();
        gridBagLayout.columnWidths = new int[]{600, 0};
                gridBagLayout.rowHeights = new int[]{280, 220, 0};
                gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
                gridBagLayout.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
                setLayout(gridBagLayout);

        GridBagConstraints gbc_scrollPaneTable = new GridBagConstraints();
                gbc_scrollPaneTable.insets = new Insets(0, 0, 5, 0);
                gbc_scrollPaneTable.fill = GridBagConstraints.BOTH;
                gbc_scrollPaneTable.gridx = 0;
                gbc_scrollPaneTable.gridy = 0;

        add(scrollPane, gbc_scrollPaneTable);

        JScrollPane scrollPaneInfo = new JScrollPane();
                GridBagConstraints gbc_scrollPaneInfo = new GridBagConstraints();
                gbc_scrollPaneInfo.fill = GridBagConstraints.BOTH;
                gbc_scrollPaneInfo.gridx = 0;
                gbc_scrollPaneInfo.gridy = 1;
                add(scrollPaneInfo, gbc_scrollPaneInfo);

                panel1 = new JPanel();
                scrollPaneInfo.setViewportView(panel1);
                GridBagLayout gbl_panel = new GridBagLayout();
                gbl_panel.columnWidths = new int[]{150, 100, 100, 100, 150, 0};
                gbl_panel.rowHeights = new int[]{25, 25, 25, 25,25, 25,25, 25,20};
                gbl_panel.columnWeights = new double[]{1.0, 1.0, Double.MIN_VALUE};
                gbl_panel.rowWeights = new double[]{1.0, 1.0, 1.0, 1.0, 1.0, 1.0, Double.MIN_VALUE};

                panel1.setLayout(gbl_panel);

        JLabel filterColumnLbl = new JLabel("Choose a column");
        GridBagConstraints gbc_filterColumnLbl = new GridBagConstraints();
        //gbc_filterColumnLbl.fill = GridBagConstraints.VERTICAL;
        gbc_filterColumnLbl.anchor = GridBagConstraints.WEST;
        gbc_filterColumnLbl.insets = new Insets(5, 15, 0, 0);
        gbc_filterColumnLbl.gridx = 0;
        gbc_filterColumnLbl.gridy = 0;    
                panel1.add(filterColumnLbl, gbc_filterColumnLbl);


                String[] columnName = { "Name", "Operator", "Numbers" };
            filterColumnBox = new JComboBox(columnName);
        GridBagConstraints gbc_filterColumnBox = new GridBagConstraints();
        //gbc_filterColumnBox.fill = GridBagConstraints.VERTICAL;
        gbc_filterColumnBox.anchor = GridBagConstraints.WEST;
        gbc_filterColumnBox.insets = new Insets(5, 15, 0, 0);
        gbc_filterColumnBox.gridx = 1;
        gbc_filterColumnBox.gridy = 0;        
                panel1.add(filterColumnBox, gbc_filterColumnBox);              

        JLabel filterValueLbl = new JLabel("Enter value");
        GridBagConstraints gbc_filterValueLbl = new GridBagConstraints();
        //gbc_filterValueLbl.fill = GridBagConstraints.VERTICAL;
        gbc_filterValueLbl.anchor = GridBagConstraints.WEST;
        gbc_filterValueLbl.insets = new Insets(5, 15, 0, 0);
        gbc_filterValueLbl.gridx = 0;
        gbc_filterValueLbl.gridy = 1;        
                panel1.add(filterValueLbl, gbc_filterValueLbl);

        final JTextField filterValueTxt = new JTextField();
        GridBagConstraints gbc_filterValueTxt = new GridBagConstraints();
        //gbc_filterValueTxt.fill = GridBagConstraints.VERTICAL;
        gbc_filterValueTxt.anchor = GridBagConstraints.WEST;
        gbc_filterValueTxt.insets = new Insets(5, 15, 0, 0);
        gbc_filterValueTxt.gridx = 1;
        gbc_filterValueTxt.gridy = 1;        
                panel1.add(filterValueTxt, gbc_filterValueTxt);
                filterValueTxt.setColumns(10);


        JButton filterBtn = new JButton("Apply filter");
        GridBagConstraints gbc_filterBtn = new GridBagConstraints();
        //gbc_filterValueTxt.fill = GridBagConstraints.VERTICAL;
        gbc_filterBtn.anchor = GridBagConstraints.WEST;
        gbc_filterBtn.insets = new Insets(5, 15, 0, 0);
        gbc_filterBtn.gridx = 0;
        gbc_filterBtn.gridy = 2;        
        filterBtn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                if(!filterValueTxt.getText().equals("")) {
                         filterValue = filterValueTxt.getText();
                         setColumnIndex();
                     if(sortColumn == 1) {
                        filterValue = filterValue.toLowerCase();
                         System.out.println("Operator: " +  filterValue.toLowerCase());
                     }
                     if (filterValue.length() == 0) {                
                       sorter.setRowFilter(null);
                     } else {
                       System.out.println("Apply listener" + filterValue + " "+filterValue.length() + " sort: "+ sortColumn );
                       sorter.setRowFilter(RowFilter.regexFilter(filterValue, sortColumn));
                     }
                }              
                else {
                        JOptionPane.showMessageDialog(null, "Enter a value!");
                }              
              }
                });
                panel1.add(filterBtn, gbc_filterBtn);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // important
        pack();
        setVisible(true); // important

    }
}

【问题讨论】:

  • 每次XxxRenderer重绘JTables视图时使用局部变量而不是加载Icon
  • “按 ImageIcon 列过滤 jTable” 这很反直觉。那么,用户必须知道图像的 name 才能获得该列的过滤器吗?为什么不将名称放在旁边的列中,然后对其进行过滤?否则,我会提供一个过滤器来呈现图像本身以供用户选择,而不是图像的文件 names
  • 1) 按照@AndrewThompson 所说的去做,但作为一种技术解决方案,只需将共享路径添加到键入的字符串。 2) 粘贴MCVE,而不是链接到您的完整代码。
  • 顺便说一句-您是否尝试过过滤“乔”然后恢复整个列表?我找不到如何做到这一点 - 按原样使用代码。如果文本字段为空,最好返回整个(未过滤的)列表。顺便说一句 - 你遵循@user1803551 的建议并发布代码很好,但是 MCVE 需要main(string[]) 来运行它。例如,获取图像的一种方法是热链接到在this Q&A 中看到的图像(尽管这些图像不会有您的示例中看到的“好”字符串名称)。
  • 你的过滤器区分大小写,有点奇怪。

标签: java swing filter jtable


【解决方案1】:

也许您可以在要过滤的正则表达式中包含路径?喜欢:

String path = "resources\/opIcons\/";
RowFilter.regexFilter("^"+path+".*"+filterValue+".*$", sortColumn)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 2011-07-30
    • 2012-09-29
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多