It's all about Java: Core java and Swing
Showing posts with label Core java and Swing. Show all posts
Showing posts with label Core java and Swing. Show all posts

Wednesday, 6 January 2021

Java - Swing custom components - Rounded JButton

Unlike AWT, Java Swing tool kit provides feasibilty to create custom components and containers.

To understand Java GUI toolkits more clearly, please read my other articles on Swing and AWT. 

In this article I focus more on building custom components.

Let us see how to create simple Rounded JButton. The below program demonstrates How rounded JButton can be created and added to a JFrame.

 

Program:


import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class RoundedJButton extends JButton {

/**
*/
private static final long serialVersionUID = 1L;

public RoundedJButton(String title) {
super(title);
Dimension size = getPreferredSize();
size.width = size.height = Math.max(size.width, size.height);
setPreferredSize(size);

setContentAreaFilled(false);
}

@Override
protected void paintComponent(Graphics g) {
if (getModel().isArmed()) {
g.setColor(Color.lightGray);
} else {
g.setColor(getBackground());
}
g.fillOval(0, 0, getSize().width - 1, getSize().height - 1);

super.paintComponent(g);
}

@Override
protected void paintBorder(Graphics g) {
g.setColor(getForeground());
g.drawOval(0, 0, getSize().width - 1, getSize().height - 1);
}

Shape shape;

@Override
public boolean contains(int x, int y) {
if (shape == null || !shape.getBounds().equals(getBounds())) {
shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
}
return shape.contains(x, y);
}

public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {

JFrame frame = new JFrame();
frame.setTitle("It's all about Java...");
frame.setSize(150, 150);
GridLayout layout = new GridLayout();
layout.setRows(1);
layout.setHgap(10);
layout.setVgap(10);
frame.setLayout(layout);

JTextField field1 = new JTextField();
field1.setText("This is a textfield!");
frame.getContentPane().add(field1);

RoundedJButton button = new RoundedJButton("Browse");
button.setBackground(Color.gray);
button.setForeground(Color.GREEN);
frame.getContentPane().add(button);

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
frame.pack();
frame.setVisible(true);
}
});
}
}

There are two parts in the program. First part creates RoundedJButton component by extending JButton. and second part creates JFrame and appends two components. 1. RoundedJButton and 2. JTextField

First Part:


RoundedJButton overrides paintComponent(Graphics g) and paintBorder(Graphics g) to get the circled shape to the Button. 

Second Part:

Second part contains main method which creates JFrame object and adds 2 components to JFrame dialog.

Also applies System look and feel by using following

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

I will explain clearly about pluggable look and feels also known as PLAF in future articles.

That's all for now!

Happy coding... :) 

Monday, 29 January 2018

Swing JLabel demo with example

This article is continuation of previous post JFrame usage demo. Please read it before continuing.

This post uses the same example code shown in JFrame usage demo with JLabel changes and introduces layout manager BorderLayout.

Layout Manager:

Layout manager is responsible to arrange components on containers. Usually every swing container is created with a default layout manager but can be changed with setLayout() api. For example JFrame uses BorderLayout as default layout amanger.

Java program for JLabel


2   import java.awt.BorderLayout;
3   import java.awt.Color;
4   import java.awt.Font;

6   import javax.swing.JFrame;
7   import javax.swing.JLabel;
8   import javax.swing.SwingUtilities;

10  /**
11   *
12   * Simple class to demonstrate JLabel of swing toolkit
13   *
14   * @author Nagasharath
15   *
16   */
17  public class LabelDemo extends JFrame {
18
19  private final String title = "It's all abt java!...  ";
20
21  private JLabel label;
22
23  /**
24  * set properties of the main window. Title, size of frame and position/location
25  */
26  public LabelDemo() {
27  this.setTitle(title);
28  this.setSize(300, 200);
29  this.setLocationRelativeTo(null);
30  initComponents();
31  }
32
33  /**
34  * instantiates controls controls.
35  *
36  */
37  private void initComponents() {
38  BorderLayout layout = new BorderLayout(20, 10);
39  this.setLayout(layout);
40
41  label = new JLabel("java-gui.blogspot.com");
42  label.setForeground(Color.RED);
43  label.setFont(new Font(Font.MONOSPACED, Font.BOLD, 25));
44  this.getContentPane().add(label, BorderLayout.CENTER);
45  }
46
47  public static void main(String[] args) {
48
49  Runnable r = () -> {
50  LabelDemo demo = new LabelDemo();
51  demo.setVisible(true);
52  };
53  SwingUtilities.invokeLater(r);
54  }
55  }
56


Line 21: Introduced new variable of type JLabel

Line 38 and Line 39: Used BorderLayout as layout manager to arrange label component on JFrame container

Line 41: Instantiated label with a text of String type.

Line 42 and Line 43:  label properties like foreground color, font style, size, type and background etc are specified

Line 44:  Finally added this label to the JFrame using add().

Output:


JFrme with JLabel

Swing: JFrame usage demo

This post helps in understanding usage of JFrame class with an example


Swing toolkit categorizes components into 2 types. They are:

  • Containers
  • Controls

Containers allows Controls to be arranged on them. JPanel, JFrame and JDialog are few which are frequently used.

Controls are components like Buttons, labels, tables etc. These controls are arranged on containers using different layout managers.

All Swing class names starts with J stands for Java which symbolizes swing is pure java! 

Layout Managers:

Layout manager is responsible for laying out controls on containers according to the business requirement. Example layout managers are BorderLayout, GridLayout, GridBagLayout and FlowLayout.

Few points about JFrame:
  • JFrame is considered as a main window of the application.for almost all swing based applications
  • All other controls and containers are created as child components of JFrame
  • JFrama holds special components like  Menu bar, Tool bar etc  

Example program

1 import javax.swing.JFrame;
2 import javax.swing.SwingUtilities;
3
4 /**
5  *
6  * Simple class to demonstrate JFrame container of swing toolkit
7  *
8  * @author Nagasharath
9  *
10 */
11public class FrameDemo extends JFrame {
12
13 private final String title = "It's all abt java!...  ";
14
15 /**
16 * set properties of the main window. Title, size of frame and position/location
17 */
18 public FrameDemo() {
19 this.setTitle(title);
20 this.setSize(300, 200);
21 this.setLocationRelativeTo(null);
22 initComponents();
23 }
24
25 /**
26 * It is used in future articles for instantiating controls like buttons etc.
27 * left empty for now.
28 */
29 private void initComponents() {
30 }
31
32 public static void main(String[] args) {
33
34 Runnable r = () -> {
35 FrameDemo demo = new FrameDemo();
36 demo.setVisible(true);
37 };
38 SwingUtilities.invokeLater(r);
39 }
40}
41


Line 1: Our class FrameDemo extends JFrame hence gets all benefits that JFrame possess    

Line 20: Sets the width 300 and height 200. How ever frame is re sizable at run time

Line 21:  Puts the frame at the center of the desktop monitor

Line 36: Unless call to setVisible(true), frame can not be seen at all.

Line 38: It is always good practice to call setVisible(true) in invokeLater().

Output on Win 10:

The look and feel we see below  is default which is same on all platforms 

This Look and feel can be changed using UIManager class. We see it in coming posts.  

      
JFrame with title


Wednesday, 24 January 2018

Every Java programmer must read books

Every Java programmer must read and understand the following books.


1. Effective Java

2. Concurrency in practice

Effective Java:


This book is authored by Joshua Bloch. He took the major role in authoring the java.util package which is [collection framework] one of the java core libraries.

He explains the best practices that every programmer should consider while writing java programs.

Some of them are:


  • Contract between hashcode() and equals() of Object class when programmer overrides one of these methods in their classes
  • Exceptions
  • concurrency: Inter thread communication, synchronization etc
  • Immutable Objects
The above points are few among others.

Concurrency in practice:


This book gives complete explanation about how efficient concurrency is achieved in java programs using concurrency utility classes which were introduced in Java 5 version.

This book is authored by:

  • Brian Goetz
  • Tim peierls
  • Joshua Bloch
  • Joseph Bowbeer
  • David Holmes and
  • Doug Lea


You can get them from amazon in form of hard copy or soft copy or both. Get them soon. :)
  

Sunday, 21 January 2018

Internals of JVM

Internals of Java Virtual Machine are explained very clearly in the below blog by James Blooms. 


Internals of JVM by James Blooms

CHEAT SHEET for java List interface, LinkedList and ArrayList

Consider Below points before choosing List concrete implementations for your use case: 

  • ArrayList is a linear data structure and  re-sizable/dynamic array
 
  • Initial size can be given. and if not given the default size is 10
 
  • It is always good practice to give initial size and advised not to give very large number as size
 
  • Good programmers prefer ArrayList to LinkedList if retrieval operations is done more frequently than insertion and deletions of elements.
 
  • Better choose LinkedList if insertion and deletion operations are done frequently compared to retrieval operations.
 
  • Lists are not sorted. if required use Collections.sort() to sort
 
  • Collections.sort() uses optimized merge sort [tim sort] on ArrayList
 
  • However legacy merge sort also can be used using a switch. But it is going to be deprecated  in near future 

  • The major difference between ArrayList and LinkedList is RandomAccess behavior 

  • ArrayLists uses Random access indexing where as LinkedLists uses
          Sequential access indexing
 
  • LinkedList carries extra overhead in the form of reference to the next and previous elements other than element's data itself

  • LinkedList uses Doubly LinkedList data structure internally

  • Deque is the java DoubleLinkedList data structure implementation

  • Before choosing List implementation ask yourself below questions 
                    a. Are you aware of initial size? 
                    b. Which operations are used more frequently? [insertion, deletion,
                       retrieval, search, sort are few among others]

  • Search Algorithm: 
                  a. Collections class uses binary search if List is ArrayList
                  b. Collections class uses linear search if List is of type LinkedList


  • ArrayList and LinkedList both uses fast fail iterations.

  • If another thread tries to modify list while iterating, java runtime throws ConcurrentModificationException. This can be considered as fast fail behavior  

Saturday, 30 December 2017

Simple program which demonstrates Swing/AWT Grid layout

Simple program which demonstrates Swing/AWT Grid layout:


This post is intended to the beginners of swing/awt.

This below program creates a JFrame with 2 labels, 2 textfields and 2 buttons.


import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

/**
 * @author Nagasharath Kopalle
 *
 * Simple program to demontrate Gridlayout
 *
 */
public class GridLayoutDemo extends JFrame {

private JLabel labelName = null;

private JTextField textFieldName = null;

private JLabel labelPassword = null;

private JPasswordField passwordFieldPassword = null;

private JButton buttonSubmit = null;

private JButton buttonCancel = null;

/**
*
*/
public GridLayoutDemo() {
initComponents();
}

/**
* instantiates components and adds properties.
*/
void initComponents() {

this.setTitle("Grid Layout Demo");
this.setSize(300, 200);
GridLayout layout = new GridLayout(3, 2);
layout.setHgap(10);
layout.setVgap(5);
labelName = new JLabel("User Name: ");
textFieldName = new JTextField();

labelPassword = new JLabel("Password: ");
passwordFieldPassword = new JPasswordField();

buttonSubmit = new JButton("Submit");
buttonCancel = new JButton("Cancel");

this.setLayout(layout);
this.getContentPane().add(labelName);
this.getContentPane().add(textFieldName);

this.getContentPane().add(labelPassword);
this.getContentPane().add(passwordFieldPassword);

this.getContentPane().add(buttonSubmit);
this.getContentPane().add(buttonCancel);
}

public static void main(String[] args) {

GridLayoutDemo demo = new GridLayoutDemo();
demo.setVisible(true);
}
}

Output:


Sunday, 29 October 2017

Eclipse Java Editor Shortcuts

Eclipse Oxygen Java editor Shortcuts helps in editing source code more comfortably. Frequently used default shortcuts are listed below. 




Description
Shortcut
Delete Line
CTRL + D
Copy Line
CTRL + ALT + Down Arrow
Add method level, class level, member level Comments
SHIFT + ALT + J
Format Java Source code
CTRL + SHIFT + F
Make line commented
CTRL + /
Make multiple lines [block] commented  
CTRL + SHIFT + /
Search selected similar word within the source document
CTRL + K
Select line from beginning to end
SHIFT + End key
Select line from end to beginning
SHIFT + Home key
Select Word by word in same line
CTRL + SHIFT + Right Arrow
Move line above
ALT + Up Arrow
Move line below
ALT + Down Arrow

Shortcuts can be customized and new shortcuts can be created through Keys Page in Preferences wizard.


  1.  Window menu > Go To Preferences 
  2.  Type Keys as the "filter text"
  3.  Please find the image below for reference.


Example:
Add new Shortcut for cut whole line command.

  1.  In Keys page type filter text -- Cut line
  2.  Type your convenient key. In my case I added SHIFT + X
  3.  Finally, Click Apply and Click Apply and Close.
  4.  That's it. Now Test your new Shortcut. 

Happy Coding :)

Saturday, 21 October 2017

Launch Swing GUI always in a dedicated Thread



1. Since Swing is not thread safe, it is not at all a good practice to launch a UI Container like JFrame, JDialog etc in main Thread.
2. Doing so leads to incorrect behavior of java GUI.
3. To avoid this, Swing toolkit has predefined API as part of JFC.
4.    a. SwingUtilities.invokeAndWait(Runnable r);
       b. SwingUtilities.invokeLater(Runnable r);

5. Which part of the code must be in UI Thread?
        a. setVisible(true);
        b. show(); [deprecated]
 and c. pack();
     

6. Call to these methods mentioned in 5(a), 5(b), and 5(c) must happen in one of the methods mentioned in point 4(a) and point 4(b). That's enough. :)
         Example :
             
         public static void main(String[] args){
                         
         JFrame frame = new JFrame();
         frame.setSize(100, 200);
         SwingUtilities.invokeAndWait(new Runnable(){
             public void run(){
                     frame.setVisible(true);
                     frame.pack();
             }//run
        });//
       }//main

  7. Difference between invokeAndWait() and invokeLater():
          a. invokeLater() is non blocking and asynchronous, where as invokeAndWait() is blocking and synchronous.
          b. Since invokeLater() is asynchronous, It is more flexible.
                                 
                                   

Friday, 6 October 2017

File Manager/File Explorer with Swing JTree Component

This post is intended to beginners of java swing toolkit programmers.
It is a simple java program which demonstrates the swing based File explorer GUI.





import java.awt.GridLayout;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

/**
 * @author NagasharathK
 *
 */
public class FileExplorer extends JFrame {

private JTree fileManagerTree = null;

public FileExplorer() {
initComponents();
}

/**
* Initializes components
*/
private void initComponents() {
this.getContentPane().add(new JScrollPane(createFileManagerTree()));
this.setSize(500, 500);
this.setResizable(true);
this.setTitle("File Manager..");
}

/**
* @return JPanel object which contains other comp...
*/
private JPanel createFileManagerTree() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout());

fileManagerTree = new JTree();
fileManagerTree.setModel(new FilesContentProvider("C:\\"));
panel.add(fileManagerTree);
return panel;
}

class FilesContentProvider implements TreeModel {

private File node;

public FilesContentProvider(String path) {
node = new File(path);

}

@Override
public void addTreeModelListener(TreeModelListener l) {

}

@Override
public Object getChild(Object parent, int index) {
if (parent == null)
return null;
return ((File) parent).listFiles()[index];
}

@Override
public int getChildCount(Object parent) {
if (parent == null)
return 0;
return (((File) parent).listFiles() != null) ? ((File) parent).listFiles().length : 0;
}

@Override
public int getIndexOfChild(Object parent, Object child) {
List<File> list = Arrays.asList(((File) parent).listFiles());
return list.indexOf(child);
}

@Override
public Object getRoot() {
return node;
}

@Override
public boolean isLeaf(Object node) {
return ((File) node).isFile();
}

@Override
public void removeTreeModelListener(TreeModelListener l) {

}

@Override
public void valueForPathChanged(TreePath path, Object newValue) {

}

}

/**
* @param args
* @throws InvocationTargetException
* @throws InterruptedException
* @throws UnsupportedLookAndFeelException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws InvocationTargetException, InterruptedException,
ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
FileExplorer explorerUI = new FileExplorer();
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
explorerUI.setVisible(true);
}
});
}
}
 

The above program has one inner class [FilesContentProvider] which serves as a model to the JTree.

The UI has 4 Components: JFrame, JScrollPane, JPanel and JTree.

To Do:

  1. Add Context menu to node based upon the file type
  2. Add Cell renderer to give proper names to the Nodes
  3. Option to Expand whole tree or selected node etc..  


Friday, 6 January 2017

GridLayout: fill the form with gridlayout

Swing controls are of two types they are Containers and components. components are arranged on a containers. example components are JLabel, JButton etc and example containers are JPanel, JFrame and JDialog etc.
these components are arranged on a container with the help of layout managers. Few layout managers available in swing toolkit are

1. FlowLayout [Jframe's Default layout manager]
2. GridLayout
3. BorderLayout [JPanel's Default layout manager]
4. GridBagLayout.
5. Custom Layout manager

The custom layout amanger is useful to design programmer's own layout manager. Usually this is useful when any of the available layout managers does not give the needy result.
apart of these above all layout managers, few third party libraries are also available they are

1. DesignGridLayout
2. Mig Layout etc

Design grid Layout


Gridlayout is one of the most simple and flexible layout managers. layout manager is used to arrange the components on a container with proper margins, gap etc.

Gridlayout is suitable when the number of components are even numbered in each row of the container.


Swing program without any layout manager:


import java.awt.GridLayout;
import java.lang.reflect.InvocationTargetException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class GridLayoutExample extends JFrame {

private JLabel label1 = null;
    private JLabel label2 = null;
    private JLabel label3 = null;
    private JTextField tf1 = null;
    private JTextField tf2 = null;
    private JTextField tf3 = null;
    private JButton button1 = null;
    private JButton button2 = null;

    public GridLayoutExample() {
        initComponents();
    }

    private void initComponents() {

        label1 = new JLabel("Name: ");
        add(label1);
        tf1 = new JTextField();
        add(tf1);

        label2 = new JLabel("Qualification: ");
        add(label2);

        tf2 = new JTextField();
        add(tf2);
        label3 = new JLabel("Profile: ");
        add(label3);

        tf3 = new JTextField();
        add(tf3);

        button1 = new JButton("Submit");
        add(button1);
        button2 = new JButton("Cancel");
        add(button2);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
    }


    public static void main(String[] args) throws InvocationTargetException, InterruptedException {

        GridLayoutExample ex = new GridLayoutExample();

        ex.setSize(300, 200);
        ex.setLocationRelativeTo(null);
        
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                ex.setVisible(true);
            }
        });

    }
}

  Output:





Shown below is a Swing program after adding a GridLayout. 

Replace the initComponents() of the above program with the below method


   private void initComponents() {
    GridLayout gl = new GridLayout();
    gl.setColumns(2);
    gl.setRows(4);
    gl.setHgap(15);
    gl.setVgap(15);

    this.setLayout(gl);

    label1 = new JLabel("Name: ");
    add(label1);
    tf1 = new JTextField();
    add(tf1);

    label2 = new JLabel("Qualification: ");
    add(label2);

    tf2 = new JTextField();
    add(tf2);
    label3 = new JLabel("Profile: ");
    add(label3);

    tf3 = new JTextField();
    add(tf3);

    button1 = new JButton("Submit");
    add(button1);
    button2 = new JButton("Cancel");
    add(button2);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
}



the output after applying layout manager.....







Saturday, 23 July 2011

JForm: Fill the form with style

After understanding and using swing toolkit, I understood that there is a allot of scope to develop Custom components easily.
I have developed a component called JForm which basically a button and its selection pops up a window if it is not visible.

Technically the JForm component is a combination of 2 components they are:

1. JButton
2. Window

JButton is a API of swing toolkit where as Window is a API of AWT.

Behaviour of JForm:

JForm is a usual button like JButton. but it is glued to a Window component. this Window takes a JPanel class as an arguments.

In the given example has 2 components they are 1. JTextArea  2. JButton [Submit] which are appended to a JPanel..

The below image shows the effect before selecting the JForm:






This image shown is the effect after selecting the JForm:

                                     



the below code is an example which includes code for JForm custom component and main() includes usage of JForm.


import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class JForm extends JButton {

Point location;
int X = 0;
int Y = 0;
int W = 0;
int H = 0;
JFrame frame;
MyWindow window;

public JForm(JFrame frame, JPanel panel) {

this.frame = frame;
this.setBackground(Color.gray);
this.setText("click me!...");
JForm.this.window = new MyWindow();
JForm.this.window.add(panel);
this.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {

if (window.isVisible() == false) {
JForm.this.window.setSize(10, 20);
location = getLocationOnScreen();
X = location.x;
Y = location.y;
JForm.this.window.setLocation(X - 5, Y + JForm.this.getHeight());
window.pack();
window.setVisible(true);
}else{
window.setVisible(false);
}
}
});
}

class MyWindow extends Window {
public MyWindow() {
super(JForm.this.frame);
frame.addComponentListener(new ComponentListener() {
public void componentResized(ComponentEvent evt) {
if (JForm.this.isShowing() == true) {
location = JForm.this.getLocationOnScreen();
X = location.x;
Y = location.y;
JForm.this.window.setLocation(X - 5, Y + JForm.this.getHeight());
}
}

@Override
public void componentHidden(ComponentEvent arg0) {
if (JForm.this.isShowing() == true) {
location = JForm.this.getLocationOnScreen();
X = location.x;
Y = location.y;
JForm.this.window.setLocation(X - 5, Y + JForm.this.getHeight());
}
}

@Override
public void componentMoved(ComponentEvent arg0) {
if (JForm.this.isShowing() == true) {
location = JForm.this.getLocationOnScreen();
X = location.x;
Y = location.y;
JForm.this.window.setLocation(X - 5, Y + JForm.this.getHeight());
}
}

@Override
public void componentShown(ComponentEvent arg0) {
if (JForm.this.isShowing() == true) {
location = JForm.this.getLocationOnScreen();
X = location.x;
Y = location.y;
JForm.this.window.setLocation(X - 5, Y + JForm.this.getHeight());
}
}
});
}

}

public static void main(String[] args) {
JFrame frame = new JFrame();

GridBagLayout l = new GridBagLayout();

GridBagConstraints c = new GridBagConstraints();
c.gridwidth = 40;
c.gridheight = 20;
frame.setLayout(l);
JPanel panel = new JPanel();
GridBagLayout pl = new GridBagLayout();
GridBagConstraints pC = new GridBagConstraints();
JTextArea ta = new JTextArea(5, 10);
panel.add(ta, pC);
JButton button = new JButton("Submit");
pC.gridx = 50;
pC.gridy = 40;
panel.add(button, pC);

panel.setBackground(Color.gray);
JForm form = new JForm(frame, panel);
l.setConstraints(form, c);
frame.getContentPane().add(form, c);
frame.setSize(200, 200);
frame.pack();
frame.setVisible(true);
}
}

Next time I will come up with a JForm with different shapes like rounded, rounded corners etc..  

Friday, 22 July 2011

JColorComboBox: JComboBox as Color Chooser

 
Swing toolkit provides a component called JColorChooser to choose colors. It allows users to select color from multiple color combinations. Some times our application may need simple component with an option to select only basic colors/ less number of color options unlike sepearate dialog with too may color options[JColorChooser]. This JColorComboBox may serve the need.

I wanted my color chooser to behave like JComboBox. The popup shows all 12 colors and their names, among all of them one color can be choosen. see the below image.


I created two classes
         1. JColorComboBox
         2. ColorRenderer
JColorComboBox extends the JComboBox and ColorRenderer extends JLabel and implements ListCellRenderer.


import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.swing.*;
/**
*
* @author sharath
*/
public class JColorComboBox extends JComboBox {

static Hashtable<String, Color> colors;

public JColorComboBox() {
super();
DefaultComboBoxModel model = new DefaultComboBoxModel();
Enumeration colorNames = addColors().keys();
while(colorNames.hasMoreElements()){
String temp = colorNames.nextElement().toString();
model.addElement(temp);
System.out.println("colors"+temp);
}
setModel(model);
setRenderer(new ColorRenderer());
this.setOpaque(true);
this.setSelectedIndex(0);
}
@Override
public void setSelectedItem(Object anObject) {
super.setSelectedItem(anObject);

setBackground((Color)colors.get(anObject));
setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
if(anObject.toString().equals("BLACK") || anObject.toString().equals("DARK_GRAY")){
setForeground(Color.white);
}
}
public Color getSelectedColor(){

return this.getBackground();
} 

private Hashtable addColors(){

colors = new <String, Color>Hashtable();

colors.put("WHITE", Color.WHITE);
colors.put("BLUE", Color.BLUE);
colors.put("GREEN", Color.GREEN);
colors.put("YELLOW", Color.YELLOW);
colors.put("ORANGE", Color.ORANGE);
colors.put("CYAN", Color.CYAN);
colors.put("DARK_GRAY", Color.DARK_GRAY);
colors.put("GRAY", Color.GRAY);
colors.put("RED", Color.RED);
colors.put("PINK",Color.PINK);
colors.put("MAGENTA", Color.MAGENTA);
colors.put("BLACK", Color.BLACK);

return colors;
}
 
class ColorRenderer extends JLabel implements javax.swing.ListCellRenderer {
public ColorRenderer() {
this.setOpaque(true);
}
public Component getListCellRendererComponent(JList list, Object key, int index,
boolean isSelected, boolean cellHasFocus) {

Color color = colors.get(key);;
String name = key.toString();

list.setSelectionBackground(null);
list.setSelectionForeground(null);

if(isSelected){
setBorder(BorderFactory.createEtchedBorder());
} else {
setBorder(null);
}
setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
setBackground(color);
setText(name);
setForeground(Color.black);
if(name.equals("BLACK") || name.equals("DARK_GRAY")){
setForeground(Color.white);
}

return this;
}
}
}

Demo Application:
The below code creates a JFrame by adding JColorComboBox to it.

 

/**
*
* @author sharath
*/
import java.awt.GridLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.*;
public class StartGUIApp {
public static void main(String[] args)throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFrame.setDefaultLookAndFeelDecorated(true);

JPanel panel = new JPanel();
JLabel label = new JLabel("Select Color");
JColorComboBox box = new JColorComboBox();
panel.add(box);
panel.add(label);
panel.setLayout(null);
label.setBounds(20,20,60,30);
box.setBounds(100,20,140,30);
panel.setSize(250, 100);

JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.setSize(panel.getWidth(), panel.getHeight());
setFrameProperties(frame);
}
static private void setFrameProperties(JFrame frame) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

Popular posts

Atomicity with Java Programming Language

 Atomicity with Java What is Atomicity Atomicity, in computer science, is considered to be a property [ALL-OR-NOTHING], that the state of a ...