[英]Could someone tell me why my actionListener for-loop is not working?
我有一个程序,它接受一个输入文件,从中拉出一个颜色字+十六进制值(例如,红色0xFF0000)。 我的代码工作得很完美,除了我试图用HashMap替换我的2个数组列表......这就是事情出错的地方。 我将我的代码恢复到我之前认为的状态,除非现在按下单选按钮时不会改变颜色。 有人想偷看吗?
public HashMapTests() {
JPanel p1 = new JPanel();
this.getContentPane().setLayout(new GridLayout(5,4));
ButtonGroup group = new ButtonGroup();
for (int i = 0; i < colorCollection.size(); i++) {
jrbColor[i] = new JRadioButton(colorCollection.get(i));
jrbColor[i].setText(colorCollection.get(i));
group.add(jrbColor[i]);
p1.add(jrbColor[i]);
}
for(int i = 0; i < colorCollection.size(); i++){
jrbColor[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
for (int j = 0; j < colorCollection.size(); j++){
String hexColor = hexCollection.get(j);
if(hexCollection.get(j).equals(((JRadioButton)e.getSource()).getText())){
getContentPane().setBackground(Color.decode(hexColor));
repaint();
}
}
}
});
}
add(p1);
}
第一次调查:
while (colorCollection.size() < 10)
应改为
if (colorCollection.size() < 10)
第二个观察:
jrbColor[i] = new JRadioButton(colorCollection.get(i));
jrbColor[i].setText(colorCollection.get(i));
第二行是无用的,请参阅构造函数的javadoc。
第三:
附加侦听器的第二个循环是无用的,您可以将此代码放在创建按钮的第一个循环中。
最后:
if (hexCollection.get(j).equals(((JRadioButton) e.getSource()).getText())) {
您可以在此处将hexCollection的内容与单选按钮文本进行比较,但该按钮具有来自colorCollection的标签。 我无法查看您的文件,但我认为这将是问题所在。
地图方案:
初始化
String name = fileInput.next();
String hexValue = fileInput.next();
colors.put(name, hexValue);
纽扣
int i = 0;
for (String s : colors.keySet()) {
jrbColor[i] = new JRadioButton(s);
group.add(jrbColor[i]);
p1.add(jrbColor[i]);
jrbColor[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String hexColor = colors.get(((JRadioButton) e.getSource()).getText());
getContentPane().setBackground(Color.decode(hexColor));
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.