1

So I have successfully implemented a search feature into my tiny program but when I click the button to sort, it works fine but the images don't display. This is the code that I added for the sorter which works fine but the images for each row don't show up. When I take out this code, the images show up but the sorting doesn't work. Is there away that I can make the images show when sorting?

    // Sorter Code. Images show up when this code gets taken out.
    table = new JTable(model);
    final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    table.setRowSorter(sorter);
    search_button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          String text = search.getText();
          if (text.length() == 0) {
            sorter.setRowFilter(null);
          } else {
            sorter.setRowFilter(RowFilter.regexFilter(text));
          }
        }
      });
   // sorter code ends here.
Henry Pe
  • 47
  • 2
  • 8
  • If the RowFilter is firing a TableChanged event, it may resetting your cell renderers. Try reapply the cell renders either directly after the .setRowFilter call or via an SwingUtilities.invokeLater call – MadProgrammer Aug 05 '12 at 07:15
  • @MadProgrammer good idea, except that a _RowFilter_ must not fire anything back to the table, it's just a dumb predicate which decides which rows should be included. Sounds like something wrong in the code we are not seeing. Please show a SSCCE that demonstrates the problem – kleopatra Aug 05 '12 at 16:04

1 Answers1

3
  • have to synchronize JTables view with its model,

  • have look at methods convertXxxIndexToXxx

  • add int modelRow = convertRowIndexToModel(row); to your Renderer or prepareRenderer

  • example convertRowIndexToModel

EDIT

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.util.regex.PatternSyntaxException;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.*;

public class TableIcon extends JFrame implements Runnable {

    private static final long serialVersionUID = 1L;
    private JTable table;
    private JLabel myLabel = new JLabel("waiting");
    private int pHeight = 40;
    private boolean runProcess = true;
    private int count = 0;
    private JTextField filterText = new JTextField(15);

    public TableIcon() {
        ImageIcon errorIcon = (ImageIcon) UIManager.getIcon("OptionPane.errorIcon");
        ImageIcon infoIcon = (ImageIcon) UIManager.getIcon("OptionPane.informationIcon");
        ImageIcon warnIcon = (ImageIcon) UIManager.getIcon("OptionPane.warningIcon");
        String[] columnNames = {"Picture", "Description"};
        Object[][] data = {{errorIcon, "About"}, {infoIcon, "Add"}, {warnIcon, "Copy"},};
        DefaultTableModel model = new DefaultTableModel(data, columnNames) {

            private static final long serialVersionUID = 1L;
            //  Returning the Class of each column will allow different
            //  renderers to be used based on Class

            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
        };
        table = new JTable(model);
        table.setRowHeight(pHeight);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
        table.setRowSorter(sorter);
        filterText.setMaximumSize(new Dimension(400, 30));
        filterText.setFont(new Font("Serif", Font.BOLD, 20));
        filterText.setForeground(Color.BLUE);
        filterText.getDocument().addDocumentListener(new DocumentListener() {

            private void searchFieldChangedUpdate(DocumentEvent evt) {
                String text = filterText.getText();
                if (text.length() == 0) {
                    sorter.setRowFilter(null);
                    table.clearSelection();
                } else {
                    try {
                        sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                    } catch (PatternSyntaxException pse) {
                        JOptionPane.showMessageDialog(null, "Bad regex pattern", "Bad regex pattern", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }

            @Override
            public void insertUpdate(DocumentEvent evt) {
                searchFieldChangedUpdate(evt);
            }

            @Override
            public void removeUpdate(DocumentEvent evt) {
                searchFieldChangedUpdate(evt);
            }

            @Override
            public void changedUpdate(DocumentEvent evt) {
                searchFieldChangedUpdate(evt);
            }
        });
        add(filterText, BorderLayout.NORTH);
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);
        myLabel.setPreferredSize(new Dimension(200, pHeight));
        myLabel.setHorizontalAlignment(SwingConstants.CENTER);
        add(myLabel, BorderLayout.SOUTH);
        new Thread(this).start();
    }

    public void run() {
        while (runProcess) {
            try {
                Thread.sleep(1250);
            } catch (Exception e) {
                e.printStackTrace();
            }
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    ImageIcon myIcon = (ImageIcon) table.getModel().getValueAt(count, 0);
                    String lbl = "JTable Row at :  " + count;
                    myLabel.setIcon(myIcon);
                    myLabel.setText(lbl);
                    count++;
                    if (count > 2) {
                        count = 0;
                    }
                }
            });
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TableIcon frame = new TableIcon();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.setLocation(150, 150);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}
Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • also a good idea, but shouldn't be the problem here - typically, there is simply nothing to do in addition to setting the filter (that's one advantage of having the filter in the view realm as opposed to having it in the data realm - the table itself does all the heavy lifting) – kleopatra Aug 05 '12 at 16:07
  • Thanks guys for all your help but I'm still having a problem figuring this out. I have edited my original post to include my full code of my program. Please take a look at my original post for my entire code. Thanks in advance. – Henry Pe Aug 05 '12 at 18:19
  • @mKorbel: thanks but I'm still not sure how to do it. It's been like 2 months since I have started learning java so I'm not really good at this. I have posted my entire code in the original post, could you please take a look at it or somebody else? Thanks! – Henry Pe Aug 06 '12 at 16:50
  • @Henry Pe somehow I didn't see your comment, maybe this one can help you – mKorbel Aug 07 '12 at 07:16
  • @mKorbel: Thank you very much sir. That seems to do the trick. Thanks! :D – Henry Pe Aug 08 '12 at 04:37