James Gosling: idealism, the Internet and Java, Pt I

Friday 22 July 2011

JColorComboBox: JComboBox as Color Chooser

 
Swing toolkit provides a component called JColorChooser to choose colors. It allows users to select color from multiple color combinations. Some times our application may need simple component with an option to select only basic colors/ less number of color options unlike sepearate dialog with too may color options[JColorChooser]. This JColorComboBox may serve the need.

I wanted my color chooser to behave like JComboBox. The popup shows all 12 colors and their names, among all of them one color can be choosen. see the below image.


I created two classes
         1. JColorComboBox
         2. ColorRenderer
JColorComboBox extends the JComboBox and ColorRenderer extends JLabel and implements ListCellRenderer.


import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.swing.*;
/**
*
* @author sharath
*/
public class JColorComboBox extends JComboBox {

static Hashtable<String, Color> colors;

public JColorComboBox() {
super();
DefaultComboBoxModel model = new DefaultComboBoxModel();
Enumeration colorNames = addColors().keys();
while(colorNames.hasMoreElements()){
String temp = colorNames.nextElement().toString();
model.addElement(temp);
System.out.println("colors"+temp);
}
setModel(model);
setRenderer(new ColorRenderer());
this.setOpaque(true);
this.setSelectedIndex(0);
}
@Override
public void setSelectedItem(Object anObject) {
super.setSelectedItem(anObject);

setBackground((Color)colors.get(anObject));
setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
if(anObject.toString().equals("BLACK") || anObject.toString().equals("DARK_GRAY")){
setForeground(Color.white);
}
}
public Color getSelectedColor(){

return this.getBackground();
} 

private Hashtable addColors(){

colors = new <String, Color>Hashtable();

colors.put("WHITE", Color.WHITE);
colors.put("BLUE", Color.BLUE);
colors.put("GREEN", Color.GREEN);
colors.put("YELLOW", Color.YELLOW);
colors.put("ORANGE", Color.ORANGE);
colors.put("CYAN", Color.CYAN);
colors.put("DARK_GRAY", Color.DARK_GRAY);
colors.put("GRAY", Color.GRAY);
colors.put("RED", Color.RED);
colors.put("PINK",Color.PINK);
colors.put("MAGENTA", Color.MAGENTA);
colors.put("BLACK", Color.BLACK);

return colors;
}
 
class ColorRenderer extends JLabel implements javax.swing.ListCellRenderer {
public ColorRenderer() {
this.setOpaque(true);
}
public Component getListCellRendererComponent(JList list, Object key, int index,
boolean isSelected, boolean cellHasFocus) {

Color color = colors.get(key);;
String name = key.toString();

list.setSelectionBackground(null);
list.setSelectionForeground(null);

if(isSelected){
setBorder(BorderFactory.createEtchedBorder());
} else {
setBorder(null);
}
setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
setBackground(color);
setText(name);
setForeground(Color.black);
if(name.equals("BLACK") || name.equals("DARK_GRAY")){
setForeground(Color.white);
}

return this;
}
}
}

Demo Application:
The below code creates a JFrame by adding JColorComboBox to it.

 

/**
*
* @author sharath
*/
import java.awt.GridLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.*;
public class StartGUIApp {
public static void main(String[] args)throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFrame.setDefaultLookAndFeelDecorated(true);

JPanel panel = new JPanel();
JLabel label = new JLabel("Select Color");
JColorComboBox box = new JColorComboBox();
panel.add(box);
panel.add(label);
panel.setLayout(null);
label.setBounds(20,20,60,30);
box.setBounds(100,20,140,30);
panel.setSize(250, 100);

JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.setSize(panel.getWidth(), panel.getHeight());
setFrameProperties(frame);
}
static private void setFrameProperties(JFrame frame) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

12 comments:

  1. Thanks for the marvelous posting! I quite enjoyed reading it, you can be a great author.
    I will make certain to bookmark your blog and will come back very soon.
    I want to encourage yourself to continue your great posts, have a nice holiday weekend!


    My site ... tv en vivo (http://www.geek97361.com/WARP/tiki-index.php?page=UserPageallienicastrordqkhbm)

    ReplyDelete
  2. Hi, this weekend is pleasant for me, since this time i am reading this wonderful educational
    piece of writing here at my home.

    Look at my site ... homepage

    ReplyDelete
  3. donde puedo obtener el código fuente o ejecutable??

    ReplyDelete
    Replies
    1. Hi!

      Could you please translate it into english....?

      Delete
    2. He/she said "where can I get the source code or executable?"

      Right here, I guess?

      Delete
  4. hi, could you share the source code. thank you

    ReplyDelete
  5. hello, could you share the source code. thank you

    ReplyDelete
  6. Great post! I spent the better part of the day trying to figure out how to do precisely this (with somewhat limited success). I hope you don't mind if I use a version of this in my project (www.seattlephysicstutor.com/anagrams.html)?

    ReplyDelete
    Replies
    1. SharknadO'Connor You can use this code happily... :)

      Delete
    2. This comment has been removed by the author.

      Delete

Popular posts

Demonstration of Java NullPointerException

NullPointerException causes and reasons Since Java is object oriented programming language, every thing is considered to be an object. and t...