[英]Could someone tell me why my actionListener for-loop is not working?
I have a program that takes an input file, pulls a color word + hexadecimal value from it (for exaple Red 0xFF0000). 我有一个程序,它接受一个输入文件,从中拉出一个颜色字+十六进制值(例如,红色0xFF0000)。 I had my code working perfectly except I tried to replace my 2 arrayLists with a HashMap... That is where things took a wrong turn.
我的代码工作得很完美,除了我试图用HashMap替换我的2个数组列表......这就是事情出错的地方。 I have my code back to what I believe it was before except now it is NOT changing colors when the radio buttons are pushed.
我将我的代码恢复到我之前认为的状态,除非现在按下单选按钮时不会改变颜色。 Anyone want to take a peek?
有人想偷看吗?
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);
}
First investigation: 第一次调查:
while (colorCollection.size() < 10)
shall be replaced with 应改为
if (colorCollection.size() < 10)
Second observation: 第二个观察:
jrbColor[i] = new JRadioButton(colorCollection.get(i));
jrbColor[i].setText(colorCollection.get(i));
The second line is useless, see constructor's javadoc. 第二行是无用的,请参阅构造函数的javadoc。
Third: 第三:
The second loop where you attach the listener is useless, you can put this code to the first loop where you create a button. 附加侦听器的第二个循环是无用的,您可以将此代码放在创建按钮的第一个循环中。
Finally: 最后:
if (hexCollection.get(j).equals(((JRadioButton) e.getSource()).getText())) {
You compare here content of hexCollection with radio button text, but the button has label from colorCollection. 您可以在此处将hexCollection的内容与单选按钮文本进行比较,但该按钮具有来自colorCollection的标签。 I cannot look to your file but I think that this will be the problem.
我无法查看您的文件,但我认为这将是问题所在。
Map Solution: 地图方案:
Initialization 初始化
String name = fileInput.next();
String hexValue = fileInput.next();
colors.put(name, hexValue);
Buttons 纽扣
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.