Turning your Graphics/Graphics2D Drawings into an ImageIcon

I was recently tasked with an assignment that required me to draw several randomly generated colored circles and a target to a playing field. The user can choose the circle that he/she thinks will hit the target first and then bet on it. To make the choice as simple as possible I wanted a way to add my colored circles to a JComboBox. However the default ListCellRenderer of JComoBox only renders text or Image objects, so I needed a way to convert each of my circles into an Image. After some searching I found that java.awt.image.BufferedImage had a method called getGraphics() that returns a Graphics object. Actually, it returns a Graphics2D object cast as a Graphics, so you have to cast to get a Graphics2D. You can use this Graphics object to draw directly to this BufferedImage and then Create an ImageIcon from there.

// Create BufferedImage that is 31 x 31 (pixels) BufferedImage img = new BufferedImage( 31, 31, BufferedImage.TYPE_INT_RGB );   // Get a Graphics object Graphics g = img.getGraphics();   // Create white background g.setColor( Color.WHITE ); g.fillRect( 0, 0, 31, 31 );   // Draw a slightly larger black circle // first to give the impression of a // dark border g.setColor( Color.BLACK ); g.fillOval( 2, 2, 27, 27 );   //Draw a red circle g.setColor( Color.RED ); g.fillOval( 3, 3, 25, 25 );   // Create imageIcon from BufferedImage ImageIcon icon = new ImageIcon( img );

Once you have your ImageIcon you can add it to a JComboBox. This process can be automated by creating a list of objects that extend Ellipse2D or some other Shape (each having its own color) and then – in a loop – passing each of them to the Graphics2D fill() method and then passing each new ImageIcon to the JComboBox. The sky is the limit, really.

Scroll to Top