Java JColorChooser using Eclipse IDE

in #utopian-io7 years ago (edited)

What Will I Learn?

  • The user will learn the concept of JColorChooser
  • The user will learn how to use JColorChooser to select custom colors.

Requirements

  • A computer System is required for this tutorial.
  • Java Software Development Kit(JDK) must be installed on your computer.
  • An Integrated Development Environment(IDE) such as Eclipse or NetBeans is required to be installed on your computer.

Get JDK here

Get Eclipse here

Get NetBeans here

Difficulty

The codes in this tutorial are around the same level as other tutorials so difficulty level will be same as others - Intermediate.

Tutorial Contents

In the previous tutorials, we have learnt about a lot of Swing Components; this tutorial is done in assumption that the user followed other tutorial. Following previous tutorials, we learn more about Swing Components.

JColorChooser

The JColorChooser class is used to create a color chooser dialog box so that user can select any color. It inherits JComponent class.

JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color. This class provides three levels of API:

  • A static convenience method which shows a modal color-chooser dialog and returns the color selected by the user.

  • A static convenience method for creating a color-chooser dialog where ActionListeners can be specified to be invoked when the user presses one of the dialog buttons.

  • The ability to create instances of JColorChooser panes directly (within any container). PropertyChange listeners can be added to detect when the current "color" property changes.

This tutorial creates a JPanel and a JButton object. When the user clicks on the button, the JColorChooser dialog box will pop up enabling the user to select a random custom color.

1.png

2.png

CODE BLOCK

colorChooser Class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class colorChooser extends JFrame {
    private JPanel panel;
    private JButton button;
    private Color color = Color.BLACK;
    public colorChooser() {
        super("JColorChooser Demo");
        panel = new JPanel();
        panel.setBackground(color);
        add(panel, BorderLayout.CENTER);
        button = new JButton("Click to select Color");
        button.setBackground(Color.YELLOW);
        button.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        color = JColorChooser.showDialog(null, "Select Color", color);
                        if (color == null)
                            color = Color.BLACK;
                        panel.setBackground(color);
                    }
                }
                );
        add(button, BorderLayout.SOUTH);
    }
}
colorMain Class
import javax.swing.JFrame;
public class colorMain {
    public static void main (String args []) {
        colorChooser chooser = new colorChooser();
        chooser.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        chooser.setSize(500, 300);
        chooser.setVisible(true);
    }
}

colorChooser Class

panel = new JPanel();
panel.setBackground(color);
add(panel, BorderLayout.CENTER);

A new JPanel object called “panel” is created.

The background of the panel is changed using the color variable which was set to “Black” earlier in the program.

The panel is then added to the center of the screen using the ``` BorderLayout `` method.

button = new JButton("Click to select Color");
button.setBackground(Color.YELLOW);

A new JButton object called “button” is created

The background of the Button is set to Yellow.

button.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
color = JColorChooser.showDialog(null, "Select Color", color);
if (color == null)
color = Color.BLACK;
panel.setBackground(color);
}
}
);
add(button, BorderLayout.SOUTH);

An ActionListener interface is added to the button to pass instructions to the button when it is clicked.

The actionPerformed method which a method under the ActionListener interface is overwritten. The method holds an event.

Once the button is clicked, the JColorChooser dialog box is opened and the user can select any custom color the user wishes. This was done by initializing the “color” variable using

color = JColorChooser.showDialog(null, "Select Color", color);

A conditional statement sets the color to Black if the user decides to close the dialog box.

The background of the panel is then set to the final color selected by the user and the button is added to the bottom of the panel s=using the BorderLayout method.

colorMain CLASS

import javax.swing.JFrame;

This is an import statement. This statement is used specifically to import the JFrame class from Application Program Interface (API). This allows the user to use all methods contained in it.

public class colorMain {

This is just like creating a new file or document and saving it with a name. This is the name of the new class created.

public static void main (String args []) {

The Java main method. Every program must contain this method in order to execute. It is the point from which the program begins execution.
A program without this method will not execute.

colorChooser chooser = new colorChooser();

An Object of the colorChooser class is created. This enables the user to call in built GUI methods that will help to properly display the JPanel and JButton components to the screen.

chooser.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

This inbuilt method needs to be called before the program is run . This method states the default behavior of the windows when the “close”(x) button is clicked.
Here, it tells the window to close.

chooser.setSize(500, 300);

This is to set the size of the object to the specified width and height. In this case, the specified dimensions are (500, 300).

Values of width and height are non-negative integers. The constructors that allow you to create a dimension do not prevent you from setting a negative value for these properties. If the value of width or height is negative, the behavior of some methods defined by other objects is undefined.

chooser.setVisible(true);

This simply determines whether a component is displayed on the screen. It has two states. True and false.

With setVisible( false ), if the Component is not already marked invisible, setVisible calls invalidate() which invalidates the Container’s layout and the chain of parents since there is now more screen real estate in the Container and the positions of the siblings must be adjusted to flow into the freed space.

With setVisible( true ), if the Component is not already marked visible,setVisible calls invalidate() which invalidates the Container’s layout and the chain of parents since there is now less screen real estate in the Container and the positions of the siblings must be adjusted to squeeze in this new Component.

3.png

The program is run and the button is displayed at the bottom of the panel.

4.png

When the user clicks on the button, the JColorChooser dialog box opens and the user can select a custom color.

5.png

When the user selects a color, the background changes to that color.

6.png

7.png

If the user closes the dialog box, the background color goes back to Black.

8.png

9.png

Source Codes from GitHub Account.

You can get the codes here if you want to try it on your own.

REFERENCES

Curriculum

Similar posts already posted on Utopian are:



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Hey @will-ugo I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

For general programming tutorials, you should use a proper repository for that language, in this case its JDK, here:
https://github.com/dmlloyd/openjdk

I can approve your contribution after you change your repository into this one.

Thanks, the change has been implemented.

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

This post has received a 1.04 % upvote from @drotto thanks to: @banjo.

Congratulations! This post has been upvoted from the communal account, @minnowsupport, by will-ugo from the Minnow Support Project. It's a witness project run by aggroed, ausbitbank, teamsteem, theprophet0, someguy123, neoxian, followbtcnews, and netuoso. The goal is to help Steemit grow by supporting Minnows. Please find us at the Peace, Abundance, and Liberty Network (PALnet) Discord Channel. It's a completely public and open space to all members of the Steemit community who voluntarily choose to be there.

If you would like to delegate to the Minnow Support Project you can do so by clicking on the following links: 50SP, 100SP, 250SP, 500SP, 1000SP, 5000SP.
Be sure to leave at least 50SP undelegated on your account.