How can i change the background color of a JList item that is not selected?

TheAlexGamer :

Heyy. I am writing a tool in Java which deletes non-whitelisted files. Don't ask. It lists a directory that the user selects with the JFileChooser. This works well, all filenames are listet in a JList (in my case inside a JScrollPane) and displayed inside of the frame.

Now i want to read filenames from a .txt file and check if they match the names in the list. The reading and comparing is no problem. But i would like to set a green background if the file matches one of the files inside the .txt file. If not, then the background of the displayed item should be red. But how can i change these backgrounds for one line if its even possible?

Alec B. :

Simple, set a custom ListCellRenderer to your JList using:

list.setCellRenderer(myListCellrenderer);

Now inside the overridden method getListCellRendererComponent() do something like this:

public Component getListCellRendererComponent(.....) {
    Component c = super.getListCellRendererComponent();
    c.setBackGround(Color.blue)
    return c;
}

When the logic determines you should show the row as green (when the file names are equal), you also have the option of setting the state on the backing object of the row and test it for that state within getListCellRendererComponent(), setting the background green if the state is correct. Again, you have the option of setting a Swing Timer to revert the state on the backing object.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=126732&siteId=1