我正在使用Swing代碼,它有一堆單選按鈕與它們的十六進制值的散列圖關聯。然後,它將顯示(在顯示區域中)顏色(在背景中)以及該顏色的十六進制值的一些文本。引用hashMap值
我想通過引用存儲在我的hashMap中的值並相應地填充這些字段來完成此操作,但不知道如何執行此操作。我可以對單個ActionListeners進行硬編碼(總共20個),但如果您必須以一切困難的方式完成所有工作,那麼編碼的意義何在?
下面是我的ActionListener &在我的hashMap中的幾個條目。提前致謝!
//---- Action Listener
jrbRed.addActionListener(new ActionListener() {//<---Reference whichever button is selected instead of just 'jrbRed'
@Override
public void actionPerformed(ActionEvent e) {
jlblMessage.setForeground(Color.decode("#000000"));
jlblMessage.setText("FF0000");//<---Reference hashmap value
getContentPane().setBackground(Color.red);//<---Reference hashmap value
}
});
// ...my color map of hex values for referencing...
hashMap.put("Blue", "#0000FF");
hashMap.put("Purplish", "#DF01D7");
hashMap.put("Red", "#FF0000");
// ...etc...
好的,所以我稍微修改了一下,以反映你們建議的一些變化。這是一種混合,但我能夠得到jlblMessage.setText&.getContentPane的工作,但有ActionListener的麻煩。我只能通過直接將它指向'jrbRed'或單獨的任何一個JRadioButton來實現它。我試圖讓它聽所有JRadioButtons,但是當我放入JRadioButton時,它會給我一個錯誤,而不是'jrbRed'或其他。 – 2013-05-07 17:24:54