Java JList 设置项目的颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10251142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java JList setting color of items
提问by Jano Nepovinne Bu?fy
could you please help me, how to change color of items showed in JList?
你能帮我吗,如何改变 JList 中显示的项目的颜色?
I'm making an user JList where I can see online and offline users, and I need the offline users to have different colors than online users.
我正在制作一个用户 JList,我可以在其中看到在线和离线用户,我需要离线用户与在线用户具有不同的颜色。
My code for creating users
我创建用户的代码
final String [] strings=database.getUsers(myLogin);
jList1.setModel(new javax.swing.AbstractListModel() {
@Override
public int getSize() { return strings.length; }
@Override
public Object getElementAt(int i) { return strings[i]; }
});
采纳答案by mKorbel
I think that you have to read tutorial How to Use Lists, especially part Writing a Custom Cell Renderer, concept of Renderer is the same for JList, JTableor for JComboBoxtoo
examples are hereand on this forum here
回答by Jar Yit
I hope this code will totally help you
我希望这段代码能完全帮助你
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.util.Vector;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class UserList {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame("Users");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(300, 300);
JList list = new JList(new Vector<User>() {
{
add(new User("A", false));
add(new User("B", true));
add(new User("C", true));
add(new User("D", false));
}
});
list.setCellRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof User) {
User nextUser = (User) value;
setText(nextUser.name);
if (nextUser.loggedIn) {
setBackground(Color.GREEN);
} else {
setBackground(Color.RED);
}
if (isSelected) {
setBackground(getBackground().darker());
}
} else {
setText("whodat?");
}
return c;
}
});
f.add(new JScrollPane(list), BorderLayout.CENTER);
f.setVisible(true);
}
});
}
static class User {
String name = "NN";
boolean loggedIn = false;
public User(String name, boolean loggedIn) {
this.name = name;
this.loggedIn = loggedIn;
}
}
}
}