Skip to main content

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);
}
}

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

Post a Comment

Popular posts from this blog

DesignGridLayout: Simple, yet powerful Layoutmanager for arranging swing components

Swing toolkit comes with few standard Layout Managers where none of them serves the need of arranging components in a way that usually developers require. some of them does, but it takes lot of coding time to achieve it. GridBagLayout is the most flexible layout manager available in swing toolkit but their are so many variables that developer has to look after. DesignGridLayout can be a useful LayoutManager to arrange components in less time with very small snippet of code and can still get proper alignment. Layouting with DesignGridLayout is as easy as coding with various GUI Builder tools available in varoius IDEs. Simple program which demonstrates DesignGridLayout: import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import net.java.dev.designgr...

JForm: Fill the form with style

After understanding and using swing toolkit, I understood that there is a allot of scope to develop Custom components easily. I have developed a component called JForm which basically a button and its selection pops up a window if it is not visible. Technically the JForm component is a combination of 2 components they are: 1. JButton 2. Window JButton is a API of swing toolkit where as Window is a API of AWT. Behaviour of JForm: JForm is a usual button like JButton. but it is glued to a Window component. this Window takes a JPanel class as an arguments. In the given example has 2 components they are 1. JTextArea  2. JButton [Submit] which are appended to a JPanel.. The below image shows the effect before selecting the JForm: This image shown is the effect after selecting the JForm:                                       the below code is an example which i...

File Manager/File Explorer with Swing JTree Component

This post is intended to beginners of java swing toolkit programmers. It is a simple java program which demonstrates the swing based File explorer GUI. import java.awt.GridLayout; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.List; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.event.TreeModelListener; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; /**  * @author NagasharathK  *  */ public class FileExplorer extends JFrame { private JTree fileManagerTree = null; public FileExplorer() { initComponents(); } /** * Initializes components */ private void initComponents() { this.getContentPane().add(new JScrollPane(createFileManagerTree(...

Evolution of Java Programming Language

Evolution of Java: First of all, The Java programming language and it's tools that we currenly using is not what actually expected. This language started as a project to give solutions for embedded devices, mobile phones and other portable peripherals.  Initially, the Java was called Oak.  Why it is Oak first..? and Why it transformed to Java..? The team of five technocrats including Dr. James Gosling and also known as Dr. Java, together working on a project, which expected to give solutions on embedded devices, portable smart devices and TV Set top Boxes etc. at Sun Micro Systems.  In the process of achieving this solution, at their breaktime, team used to relax with a coffee by having a glimpse on a scenery of Oak tree next to their facility.  Once the project has come to conclusion and in the process of giving a title to it, they noticed the Oak trees [Always observing them in their break time], they named this programming language as Oak. Oak Logo Why it transfor...

Romain guy's blog

If you are interested in designing GUIs and building custom components with Swing toolkit, definitely Romain guy's blog  can be good reference for you, he writes about his work on swing components, custom components, tips and tricks on designing and using components. and you can download the demos of his work. You find more swing articles in 2005, 2006 archives. His URL: http://www.curious-creature.org/

JavaFX: arranging components on GridPane

JavaFX provides different layout panes for arranging components on them. for example GridPane, BorderPane etc. This article describes about arranging components on GridPane. GridPane layout manager allows arranging components/controls using overloaded method. ie add.                         1. add(controlinstance, colindex, rowindex)                       EX:  GridPane pane = new GridPane();                                pane.add(new Separator(), 0, 0); the above example code puts the separator on 0th row and 0th column of a gridPane.                       2. add(Node controlinstance,int colIndex,int rowIndex,int colSpan,int rowSpan)                          ...

Demonstration of Java NullPointerException

NullPointerException causes and reasons Since Java is object oriented programming language, every thing is considered to be an object. and there is always a scope of an object to be null or "No value".  Since Java supports primitive data types, Java is not considered to be pure Java object oriented programming language.   Few Notable points about NullPointerException NullPointerExceptions is unchecked exception Please read post  Exception handling and java keywords before reading this article Usually if program tries to fetch the value from reference and finds nothing as value, then program throws NullPointerException 'Zero' is not null And empty String is not considered to be null It is not the subclass of RuntimeException class Demo code that throws NullPointerException  package com.allabtjava.blog; public class DemoNullPointerException { class BeanDemo { String name; Integer ID; public String getName() { return name; } public void s...

Java programming language and IDEs

IDE: Integrated Development Environment Integrated development environment, in short IDE is a convenient environment to write, execute and  debug the code or programs on a single platform. IDEs support not only writing code smoothly but also provides a provision to write scripts, XML files, simple text files and build scripts like Ant, Maven are few among others. In short IDEs are development environments to execute complete development activities using one application. IDEs and Editors IDEs and Editors fulfills the same purpose. That is writing code. But IDEs are glued or closely works with respective programming language's compilers, runtime environments, profilers and other language specific tools to put developer in a comfortable zone.  Some of the features of IDE: Auto completion Syntax Highlighting Code debugger Profilers Multipage editors Auto completion: Auto completion feature suggests APIs [methods, classes and interfaces] and keywords etc as we start typing in the e...

Agile Methodology with SCRUM Framework Basics

Software development activities can be managed and taken care with different life cycle models. These life cycle models has became legacy since few years. Few of the available Software Development Life Cycle Models in short SDLC are Win-Win Model and Waterfall Model etc. These traditional models has different phases of development.           1. Requirements            2. Analysis            3. Design            4. Implementation            5. Test           6. Documentation  and 7. Maintenance  In SDLC, the above stages are freezed one after the other. If developer is in Design phase and realized that there could be a possibility of change in requirements, then it is not possible to go back one phase and fix in Requirement phase.  These scenarios and use cases has brough...