这里我有两个方法,一个是基于实例生成一个列表,另一个是使用drawString()来显示一些文本......
private Map<String, Color> hashMap = new HashMap<String, Color>();
for (int u = 0; u < people.size(); u++) {
if (people.get(u) instanceof Boy) {
list[u]="B";
hashMapMap.put(list[u], Color.red);
System.out.print("B");
} else if (people.get(u) instanceof Girl) {
System.out.print("G");
list[e] = "G";
hashMap.put(list[u], Color.green);
}
}
所以这给了我两个数组,分别称为&#39; list&#39;和&#39; hashMap&#39;。
所以现在我的数组的内容 list [B,G,B,G]和hashMap分别为列表数组中的这些值提供值和键。我使用下面的代码,但它无法正常工作。我的问题是:如何根据哈希映射列表中的键为每个值着色?
public void paint(Graphics g){
g.drawString(list, 10, 10)
// will like to colour each value according to its key in the hashMap list
}
答案 0 :(得分:2)
使用以下代码:
public class MyClass extends JComponent {
HashMap<String, Color> map = new HashMap<>();
private static final String BOY = "B";
private static final String GIRL = "G";
public MyClass() {
String[] peopleArray = new String[people.size()];
map.put(BOY, Color.RED);
map.put(GIRL, Color.GREEN);
for (int i = 0; i < people.size(); i++) {
if (people.get(i) instanceof Boy) {
peopleArray[i] = BOY;
System.out.print(BOY);
} else if (people.get(i) instanceof Girl) {
peopleArray[i] = GIRL;
System.out.print(GIRL);
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
//you might need a for-loop or smth here. I'll just draw a boy in this example.
g.setColor(map.get(BOY));
int x = 10;
int y = 10;
g.drawString(BOY, x, y);
}
}
提示:
BOY
和GIRL
所做的那样) paintComponent
代替paint
,因为paint
也会绘制边框等,这通常是您不需要的 - 您只需要组件。