2013-05-06 59 views
0

我正在使用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... 
+0

好的,所以我稍微修改了一下,以反映你們建議的一些變化。這是一種混合,但我能夠得到jlblMessage.setText&.getContentPane的工作,但有ActionListener的麻煩。我只能通過直接將它指向'jrbRed'或單獨的任何一個JRadioButton來實現它。我試圖讓它聽所有JRadioButtons,但是當我放入JRadioButton時,它會給我一個錯誤,而不是'jrbRed'或其他。 – 2013-05-07 17:24:54

回答

0

如果你的地圖看起來像這樣?

JButton blueButton = new JButton("Blue"); 
hashMap.put(blueButton, "#0000FF"); 

MyActionListener listener = new MyActionListener(); 

for(JButton button : hashMap.keySet()) { 
    button.addActionListener(listener); 
} 

然後得到的值取決於按鈕在你的聽衆:

jbliMessage.setText(hashMap.get((JButton)e.getSource()); 
0

你可以繼承你的單選按鈕有前景,背景和文本Color變量,並在ActionListener引用它們:

private class ColorSettingListener implements ActionListener { 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     ColorRadioButton crb = (ColorRadioButton) e.getSource(); 
     jlblMessage.setForeground(crb.getForegroundColor()); 
     jlblMessage.setText(crb.getColortext()); 
     getContentPanel().setBackground(crb.getBackgroundColor()); 
    } 
} 

如果你認爲這是過於突兀,您可以使用JComponent.getClientProperty(Object)JComponent.setClientProperty(Object, Object)做T他同樣的事情。那麼你不必子類。