Monday, July 30, 2007

Create a Colour Chooser Window with Java

Here a simple piece of code on how you can easily create a Colour Chooser window. The program uses JColorChooser method which is part of the java.swing packet. The code is:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

class ColorChooser extends JFrame {
private JButton changeColor;
private Color color = Color.lightGray;
private Container c;

public ColorChooser()
{
super( "Using JColorChooser" );

c = getContentPane();
c.setLayout( new FlowLayout() );

changeColor = new JButton( "Change Color" );
changeColor.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e )
{
color =
JColorChooser.showDialog( ColorChooser.this,
"Choose a colour", color );

if ( color == null )
color = Color.blue;

c.setBackground( color );
c.repaint();
}
}
);
c.add( changeColor );

setSize( 400, 130 );
show();
}

public static void main( String args[] )
{
ColorChooser app = new ColorChooser();

app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}

User is able to choose colors using RGB, HSB or Swatch modes.

3 comments:

Unknown said...

Usefull and fast!

Freddie L Sirmans, Sr. said...

Just browsing the internet, you have a very, very interesting blog.

Nikos Psy2k said...

@freddie: Thanks a lot :)