我试图在悬停时更改 JList 单元格的背景颜色,但我不知道该怎么做。这是我目前拥有的:
package cats.youtube.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.util.LinkedList;
import javax.swing.AbstractListModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import cats.youtube.search.YoutubeSearchResult;
public class SearchResultsList extends JPanel{
private class Renderer extends DefaultListCellRenderer{
public Component getListCellRendererComponent(JList list, Object value, int index, boolean selected, boolean focused){
final JTextArea area = new JTextArea(model.get(index).toString());
area.setBorder(new EmptyBorder(5, 0, 5, 0));
area.setForeground(selected || focused ? Color.WHITE : Color.BLACK);
area.setBackground(selected || focused ? Color.RED : Color.WHITE);
return area;
}
}
public class Model extends AbstractListModel<String>{
private LinkedList<YoutubeSearchResult> results;
private Object lock;
private Model(){
results = new LinkedList<YoutubeSearchResult>();
lock = new Object();
}
public int getSize(){
return results.size();
}
public String getElementAt(final int i){
return results.get(i).toString();
}
public YoutubeSearchResult get(final int i){
return results.get(i);
}
public void add(final YoutubeSearchResult r){
synchronized(lock){
results.add(r);
fireContentsChanged(this, 0, getSize());
try{
lock.wait(500L);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public void remove(final YoutubeSearchResult r){
results.remove(r);
fireContentsChanged(this, 0, getSize());
}
public void removeAll(){
results.clear();
fireContentsChanged(this, 0, getSize());
}
}
private JList<String> list;
private JScrollPane scroll;
private Model model;
private Renderer renderer;
public SearchResultsList(){
super(new BorderLayout());
list = new JList<String>(){
public void processMouseMotionEvent(final MouseEvent e){
super.processMouseMotionEvent(e);
final int i = locationToIndex(e.getPoint());
if(i > -1){
final Rectangle bounds = getCellBounds(i, i+1);
if(bounds.contains(e.getPoint())){
// <--------- here is line 95
}
}
}
};
list.setModel(model = new Model());
list.setCellRenderer(renderer = new Renderer());
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
add(scroll = new JScrollPane(list), BorderLayout.CENTER);
}
public Model getModel(){
return model;
}
}
问题在第 95 行;我不知道该放什么。我尝试了多种方法,一种是通过我的渲染器调用该getListCellRendererComponent
方法并像那样更改背景,但这不起作用。
悬停部分确实有效(它确实获得了正确的索引)我只是不知道在第 95 行放什么。如果有人可以帮助我,将不胜感激。