-2

I was wondering if you could add JRadioButtons to a HashMap as a key and Color as value such as:

Map <"JRadioButton, Color"> store =  new HashMap <"JRadioButton, Color">    
store.add(new JRadioButton("FF0000"), Color.red);

Then add an action listener to change panel.setBackground(store.get(e));

Or would just using an ArrayList to hold strings and create [] of radio buttons be better? I'm having trouble figuring out how to have the buttons associated with the color value.

Alexis C.
  • 91,686
  • 21
  • 171
  • 177

2 Answers2

0

Any object can be stored on a Map, either as a key or as value. However, probably Color would make a better key than JRadioButton, but it depends on your problem.

Andres
  • 10,561
  • 4
  • 45
  • 63
0

An enum could work nicely here, without need to use a Map or ArrayList, if so desired....

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.*;

import javax.swing.*;

public class ColorBtns extends JPanel {
   public ColorBtns() {
      setLayout(new GridLayout(0, 1));
      ButtonGroup btnGroup = new ButtonGroup();
      ActionListener actnListener = new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent evt) {
            String colorStr = evt.getActionCommand().toUpperCase();
            MyColor myColor = MyColor.valueOf(colorStr);
            setBackground(myColor.getColor());
         }
      };
      for (MyColor myColor : MyColor.values()) {
         JRadioButton radioBtn = new JRadioButton(myColor.getText());
         radioBtn.setOpaque(false);
         radioBtn.setActionCommand(myColor.getText());
         radioBtn.addActionListener(actnListener);
         btnGroup.add(radioBtn);
         add(radioBtn);
      }
   }

   private static void createAndShowGui() {
      ColorBtns mainPanel = new ColorBtns();

      JFrame frame = new JFrame("ColorBtns");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

enum MyColor {
   RED(Color.red, "Red"), ORANGE(Color.orange, "Orange"), YELLOW(Color.yellow,
         "Yellow"), GREEN(Color.green, "Green"), BLUE(Color.blue, "Blue");
   private Color color;
   private String text;

   private MyColor(Color color, String text) {
      this.color = color;
      this.text = text;
   }

   public Color getColor() {
      return color;
   }

   public String getText() {
      return text;
   }

}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373