Random Panel Color in Java

6/16/2012 code-examplejavajava-swing

# Summary

Colors in computers are generally made up using RGB mode i.e. Red, Green, Blue.

So in java if we generate random color values for RGB from 0 to 255 each we can make a whole new color out of it by passing this RGB to the color object.

To show the demo Swings have been used where the components are JFrame, JPanel & JButton placed using BorderLayout onto center & south.

The ActionListener for the button does the job of changing the background color of the panel.

# Screenshot

Random Panel Color in Java screenshot

# Code

package com.rohansakhale.randomcolorpaneldemo;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author Rohan Sakhale
 */
public class RandomColorPanelDemo {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        JFrame jf = new JFrame("Random Color Demo by rohansakhale");
        JButton jb = new JButton("Change Color");
        final JPanel jp = new JPanel();
 
        jf.add(jp);
        jf.add(BorderLayout.SOUTH, jb);
 
        jb.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                int red, green, blue;
                red = (int) (Math.random() * 255);
                green = (int) (Math.random() * 255);
                blue = (int) (Math.random() * 255);
                Color c = new Color(red, green, blue);
                jp.setBackground(c);
            }
        });
 
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setSize(400, 300);
        jf.setVisible(true);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45