Friday, 19 June 2015

How To Change Background Color Using JColor Chooser In Java

In many cases we need to choose a colour at a run time in our programs.In java we can do this by creating JColor Chooser that allow user to choose a colour from a palette of colours we can easily use it in our GUI program.In this tutorial I have use color chooser for changing the background colour of frame you can use it according to your need.In this program i have use color variable to store color which is selected by user at a run time then later this variable is used to set background colour of a frame by using method setBackground().

JCOLOR CHOOSER CONSTRUCTOR  AND ITS USES:

Color showDialog(Component,String,Color)

As you can see I have used this constructor in our program this constructor creates modal dialog here string specifies the the tittle of color chooser and color specifies the initial color of color chooser.  

JCOLORCHOOSER()
Creates a simple color chooser with initial color of white.

JCOLORCHOOSER(COLOR)
By using this constructor user can specify the initial colour of jcolor chooser.

CODING:

import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
class tab extends JFrame
implements ActionListener 
{
JButton jb;
tab()
{
super();
setTitle("Color Chooser");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);      
jb =new JButton("Click To Choose Background Color");
FlowLayout f=new FlowLayout();
setLayout(f);
add(jb);
jb.addActionListener(this);
jb.setActionCommand("choose");
setSize(250, 300);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
if ("choose".equals(ae.getActionCommand()))
{
Color choose = JColorChooser.showDialog(this, "Choose JButton Background",Color.BLACK);
getContentPane().setBackground(choose);
}

}

}
class colorchooser
{
public static void main(String args[])
{
tab x= new tab();
}

}


OUTPUT:



No comments:

Post a Comment