【发布时间】:2014-03-31 19:15:38
【问题描述】:
我正在设计一个程序,它使用输入文件来存储颜色及其十六进制值(例如,黑色 000000)。目前我有两个数组列表,一个用于颜色,一个用于十六进制值(我知道我可能应该使用地图,但我坚持将输入传输到地图中)。无论如何使用我的 colorCollection 数组的大小来使用 for 循环?我附上了一些代码,看看这是否有助于我想要完成的工作。
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class ReadStoreShow extends JFrame{
private static int number;
private static ArrayList<String> colorCollection = new ArrayList<String>();
private static ArrayList<String> hexCollection = new ArrayList<String>();
private JRadioButton[] jrbColor = new JRadioButton[20];
public ReadStoreShow() {
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(4,5));
for (int i = 0; i < colorCollection.size(); i++) {
jrbColor[i] = new JRadioButton(colorCollection.get(i));
// Is it possible to create buttons based on the size of colorCollection?
jrbColor[i].setText(colorCollection.get(i));
ButtonGroup group = new ButtonGroup();
group.add(jrbColor[i]);
p1.add(jrbColor[]);
}
add(p1, BorderLayout.CENTER);
setContentPane(p1);
for (int j = 0; j < colorCollection.size(); j++){
jrbColor[j].addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
for (int k = 0; k < colorCollection.size(); k++){
final String hexColor = hexCollection.get(k);
getContentPane().setBackground(Color.decode(hexColor));
repaint();
}
}
});
}
}
public static void main(final String[] args) throws IOException {
final ReadStoreShow frame = new ReadStoreShow();
frame.pack();
frame.setLayout(new GridLayout(20, 1));
frame.setSize(400, 300);
frame.setTitle("Color Change");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
try {
final java.io.File colors = new java.io.File("input.txt");
final Scanner input = new Scanner(colors);
while (input.hasNext()) {
colorCollection.add(input.next());
hexCollection.add(input.next());
} // I'm assuming I should have used one Map instead of two arrays...
input.close();
}
catch (final FileNotFoundException a) {
JOptionPane.showMessageDialog(null, "File not found.");
System.exit(0);
}
while (number < 10 || number > 20) {
number = Integer.parseInt(JOptionPane.showInputDialog(null,
"How many colors do you want? Must be between 10 and 20."));
} // while
System.out.println("The colors entered were:");
for (final Iterator<String> itr = colorCollection.iterator(); itr.hasNext();)
System.out.println(itr.next());
System.out.println("The hexidecimal codes entered were:");
for (final Iterator<String> itr = hexCollection.iterator(); itr.hasNext();)
System.out.println(itr.next());
}
}
这是我当前的 input.txt:
Black 0x000000
Red 0xFF0000
Green 0x00FF00
Blue 0x0000FF
Yellow 0xFFFF00
White 0xFFFFFF
Gray 0x707070
Purple 0x990099
Orange 0xFF6600
LightBlue 0x6666FF
【问题讨论】:
-
仅供参考,我知道这不是您提出的问题,但是:您很少需要直接使用迭代器,就像您在程序结束时所做的那样。
for (String s : colorCollection)(Java 的前几个版本中没有)是实现此目的的简单方法。 -
@ajb 感谢您的提示!我在我的程序中更改了它。
标签: java swing for-loop arraylist hashmap