Is there anyway I can highlight a row in JTable?

后端 未结 3 1926
野性不改
野性不改 2021-01-15 15:12

I am currently building a database using JTable and DefaultTableModel. In my program I have a function which allows users to search the database. I have the search part buil

相关标签:
3条回答
  • 2021-01-15 15:21

    I can tell you how I am doing it. I implemented my search to work as the search in a document, i.e. finding single result at a time. I am storing the current index of the selected row or starting from the first one if no row was previously selected. Then I have my model implement my interface with functionality to search for next or previous match, example below shows use of find next match method which returns an index of the row in a table where the matching string was found, then I change the selection to it else I clear the selection to let the user know there is no match.

    
        int index = serchableTableModel.findNextMatchIndex(serchedText, currentIndex);
        if(index != -1)
        table.changeSelection(index, 0, false, false);
        else
        table.clearSelection();
    
    

    I hope this sorts your problem.

    NOTE: I was not aware of the glazed lists before, they really seem promising. They would have saved me implementing sorting of tables, searching myself.

    0 讨论(0)
  • 2021-01-15 15:23

    Are you sure you want to highlight as opposed to filter out the extraneous results? If you highlight, you'll have to scroll through the whole list to find all of the matching results, whereas if you filter the display, it's a lot easier to find what you're looking for.

    If you go the filtering route I'd look into GlazedLists, a truly great Java library for doing things like dynamic filtering, sorting, etc. of JTables.

    If you still want to go the highlighting route, then there's two main ways I see of accomplishing this. The first is to use the ListSelectionModel of the JTable and ensure that all of the matching rows are in the selected set; this will cause them to be visually distinguished with a minimum of coding. On the other hand, as soon as the user drags in the table and selects something else, the visual effect is lost.

    The second way to accomplish this would be to use a custom TableCellRenderer that changes how a row is rendered if the row matches your selection criteria. An easy way to do that would be to change the background color.

    0 讨论(0)
  • 2021-01-15 15:42

    The Swing tutorial on How to Use Tables has a section on filtering so you can just dislay the data that meet the search criteria. If you want to see all the data, then you just remove the filter.

    If you really want to do separate highlighting then I would take a look at the Table Row Rendering approach.

    0 讨论(0)
提交回复
热议问题