【发布时间】:2015-03-08 02:41:32
【问题描述】:
我重温了这篇文章。我已经能够上传文本文件、创建 GUI、使用从文本文件中标记的 JRadioButtons 填充 GUI...
Now, I cannot get the background to change color when the JRadioButton is selected!我知道它与 ActionListener 有关,但我该如何解决呢?颜色需要从十六进制颜色代码实现。
public class FP extends JFrame implements ActionListener {
TreeMap<String, String> buttonMap = new TreeMap <>();
// Constructor
@SuppressWarnings("empty-statement")
public FP() throws IOException {
JPanel panel = new JPanel();
add(panel, BorderLayout.CENTER);
panel.setBorder(new TitledBorder("Pick a Radio Button!"));
JRadioButton[] btnArray = new JRadioButton[20];
ButtonGroup btnGroup = new ButtonGroup();
BufferedReader reader;
reader = new BufferedReader(new FileReader("src/colors.txt"));
String currentLine = reader.readLine();
while (currentLine != null) {
String[] pair = currentLine.split("\\s+");
buttonMap.put(pair[0],pair[1]);
currentLine = reader.readLine();
}
//check retrieving values from the buttonMap
for(Map.Entry<String,String> entry : buttonMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
}
for (int i = 0; i<20; i++){
for(Map.Entry<String, String> entry : buttonMap.entrySet()){
JRadioButton rb = new JRadioButton(entry.getKey() + " " + entry.getValue());
panel.add(rb);
btnGroup.add(rb);
rb.addActionListener(this);
}
}
//private final JRadioButton btnMale = new JRadioButton("Male")
Collection bMapIt = buttonMap.entrySet();
Iterator it = bMapIt.iterator();
System.out.println("Colors and codes");
while(it.hasNext())
System.out.println(it.next());
}
@Override
public void actionPerformed(ActionEvent e) {
setBackground(Color.decode(buttonMap.get(e)));
}
public static void main(String[] args) throws IOException {
FP frame = new FP();
frame.setVisible(true);
frame.setSize(350, 240);
frame.setTitle("Final Project");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
【问题讨论】:
-
buttonMap.get(e)应该做什么?将ActionEvent作为地图的键传递? -
是的,我已经修好了。
标签: user-interface background-color