Showing posts with label Swing Components. Show all posts
Showing posts with label Swing Components. Show all posts

Saturday, 28 December 2013

Exhaustive Java Swing Tutorial for Beginners

swing tutorial for beginners
Here is a kickstarter Java Swing tutorial for Beginners that takes you into the ocean of swing slowly and help you reach the other end of the sea without pain and with a very little effort. Well, is it that easy? Yes, it is. Swing is a big topic, I agree but that doesn't mean it's harder, rather you find it more interesting as you move on.

This blog contains of over 100+ articles just on the Swing topic.

Well, this topic is going to be quite big, just take a look at right side (in your browser), You can see the scroll bar is a million miles far away from your bottom-right corner. But wait. Don't worry. If you want to learn Swing, you any ways have to load dozens of pages, I did it one page and great! you already completed loading this page and everything you need is here. This post is interesting, I promise, and by the time it ends, I'm sure you'll thank me!

In a poll, I have conducted on my facebook fan page, I saw 80% of people answering that Swing is their favorite topic in Java. Is it so for you? Discuss in the comments, why you love swing.

“By all means let's be open-minded, but not so open-minded that our brains drop out.” - Richard Dawkins

Now, when we talk of Swing, we need to talk about the basics of GUI which were already discussed in the AWT tutorial. If you aren't familiar with the AWT, I suggest you to learn it or atleast have an idea of it to understand the Swing effortlessly.

Now that you know, what are the advantages of AWT, when there was no thing called GUI, people faced a lot of problems working with commands. Later GUI was introduced and incorporated into many programming languages including our Java. But that was limited and not advanced. It contained only the core components and even violated the Java paradigm as discussed in the awt tutorial. But do you know? AWT is small, isn't it? Yes, it is when compared to that of the Swing. Swing is relatively a larger toolkit with dozens of components you need to explore.

Is Swing easy for an AWT master?

Yeah! it is easy. But you don't really need to be an AWT master. The only thing, the major difference you can learn between the classes in Swing and the AWT are that in Swing you can see an additional J prefix before any component name. For example, in AWT it is Button, in swing it is JButton, TextField is JTextField in Swing. Also swing incorporates AWT Event handling into it.

But isn't there a difference except the prefix? There is!! A big difference is that all Swing components except the top-level containers (JFrame, JDialog) etc are written in pure Java code. While those in the AWT aren't.

“I don't know, I don't care, and it doesn't make any difference!” - Albert Einstein

The problem with AWT components is that they are written in native code (C/C++). So, to create any component they must depend upon the operating system and so the OS look and feel is incorporated into those components. And as the Operating system changes, the visual appearance (a.k.a. look and feel) of the components changes. Is it a problem? Yes, why not?

The javax.swing package

All the swing is tightly packed into a single package called javax.swing. But why is it given a name javax? Well, javax stands for Java's Extended Technology. I call it the Grandson generation of Java because it is advanced. And Oh no!! Are we into an advanced topic? Yes, swing is an advanced topic but you don't need to get frightened of the word because advanced isn't a synonym for harder.

“There are no secrets to success. It is the result of preparation, hard work, and learning from failure.” - Colin Powell

A sub package the javax.swing.event contains event listeners and event classes associated with several swing components. To understand this, you must go through what is event handling. Swing itself uses AWT event handling as said previously for many of its components, so we can conform that Swing doesn't override the AWT.

Disadvantages of AWT

1. Limited set of components. No sliders, progress bars, spinners..
2. Written in native code, looks different on different operating systems.
3. Not highly customizable
4. OS dependent, for each component creation, the JVM has to make calls to the Operating system.
5. AWT components take up more resources, they are slow because they need interaction with the OS.

“Every advantage has its disadvantage” - Proverb

Note: Even the top-level containers in Swing (JFrame, JDialog etc) must depend on the OS because a window (a top-level container) cannot be created without the permission of OS.

Introduction to Swing

Every topic has an introduction so does the Swing. The introduction of swing is a little big, frankly, but not too big to get frightened, I promise. After including this here, I thought it would be better if I write it as another post. So here is the post that teaches Introduction to swing and contains almost everything you need to know.

Model-View-Controller Architecture

Swing supports MVC architecture (Model-View-Controller) based architecture for its components. Here is a kickstart guide on mvc architecture in swing

Swing Components

You need to have a basic understand of the swing components and containment hierarchy before you penetrate into the examples. After going through above post, just continue reading the rest of this post.

Examples on each Swing Component

JFrame

JFrame is a top-level container which is nothing more than a window with a title bar and an optional menu bar.

JPanel

JPanel is a container which is a sub class of JComponent that stores other components in it. This can be added to any top-level container like JFrame and JDialog to group components.


JLabel

JLabel is a light-weight component that describes other components. Users may not know what a component is for, so we use JLabels to tell that information.


JButton

JButton is a nothing more than a push-button which you might already have gone through many times. User can click on it to get anything done.


JToggleButton

A JToggleButton is another component much similar to a JButton. But the difference is a JToggleButton goes into pressed state when mouse is pressed on it. To get that back into normal state, we need to press again. This component is mostly used when there is an on/off situation. You'll get a better idea of what it is when you see it in practical.


JCheckBox

A JCheckBox lies on a single principle, checked/unchecked. This component is mostly used in when we are checking multiple items, for example in Job search site, you might have undergone this where you select multiple skills, a check box is mostly used.


JRadioButton

JRadioButton is also based on the same principle as that of the JCheckBox. But the difference is that a JRadioButton is typically used when the user has to choose only one among the many items in a group. For instance, you can use it for Male/Female, the user has to select either of it, but not both. In AWT, you don't have specified class for JRadioButton as here.

Note: JButton, JToggleButton, JCheckBox and JRadioButton are all sub-classes of AbstractButton.


JComboBox

JComboBox lets the user choose a single item from multiple items. It only displays single item to the user. You can see it in many sites, where they ask you to choose your country.


JList

JList is another light-weight component similar to a JComboBox but with two major differences. The first is that JList shows multiple items (rows) to the user and also it gives an option to let the user select multiple items.


JTextField

JTextField, as you know, is a component used to write a single line of text. A text field can be seen at this blog's side bar, the subscribe field, where you type your email address.


JPasswordField

JPasswordField is much similar to a JTextField but it allows user to type passwords rather than simple text. You know, your text is visible as it is when you type in your email id, but in the case of password, some round black filled circles are displayed which are used to mask your password, but what you type is the same. This class also gives the option to morph the text with the type of character you want, if you don't like that black spot.


JFormattedTextField

This is a different type of JTextField. This allows user to enter a particular type of data. For example, you can restrict the user to enter only date in it, or a number, or a decimal value ranging between 0.0 and 1.0 etc. Anything else that the user types, will not be accepted. You can better understand this, if you look at the example.


JTextArea

JTextArea is allows you to write multiple lines of text. There are a lot of methods in this that you need to explore.


JMenu

A JMenu holds menu items and even other components. You might have already seen this in Notepad, they are named File, Edit etc. When you click them, you see menu items.


JMenuItem

A JMenuItem as said previously, is an item included in a menu where the user can click on it or invoke it by a shortcut. You can see this in Notepad, New, Open, Save etc. are called menu items. You can invoke them either by click on them or selecting them and hitting enter or via a shortcut.


Menu Button [Custom Component]*

This is a custom component. A menu button can be defined as menu that looks like a button (not like a JButton), when you click on it, the menu is displayed. You can see this type of component in My computer toolbar where you will set the view as Thumbnails or icons etc.


JCheckBoxMenuItem

This is a JMenuItem with JCheckBox in it. You might have seen this in Notepad > Format > Wordwrap.


JRadioButtonMenuItem

This is a JMenuItem with a JRadioButton in it. You can better know it and its uses if you take a look at the example.


JProgressBar

A JProgressBar is used to display progress of a process. You might have seen it a thousand times, at least. Most commonly, you have seen it in software install wizards and download managers. They show how much process was done.


JSlider

JSlider is used to let the user slide among values. You have seen it in Youtube, while playing a video, you can seek the video where ever you want, the one that you click on to do this is an example of slider.


Volume Component [Custom]*

A volume component is a slider with a JMenu. As said previously, you can also add custom components to JMenu apart from JMenuItems. Here a JSlider is added.


JSpinner

A JSpinner is used to spin between values. You might have seen it in setting RGB values of a color in many software. It contains a text field like editor in which you can type a value or it contains two small up and down buttons which allows you to change the values in the editor.


JTable

Who doesn't know what is a table? With the help of this class you can create JTable with column headers, insert custom type of data, components and what not, everything you can insert in a table. But for some things we need to hack.


JTree

A JTree is like a tree that contains several branches, even some branches contain sub branches. More about it clearly, with a diagram is explained in this example, I'm sure you'll understand it.


JToolBar

A JToolBar is used to create tool bars. A tool bar contains multiple components in it. You might have seen a toolbar many times, one such place is your book marks bar in your browser, which is a toolbar.


JTabbedPane

JTabbedPane is used to create tabs. Tabs lessen the space in a container by displaying only one group of data at a time. The best example, is your browser tabs where you open a new tab every time you want to open a new page.


JDialog

JDialog is a top-level container that doesn't contain minimize and maximize buttons, but still it is resizable. A JDialog typically takes a JFrame as a parent.


JFileChooser

A JFileChooser is used to let the user browse for files. You have seen it in Notepad, when you click on Open or Save. That specific dialog is called as a file chooser.


JColorChooser

A JColorChooser is a dialog that comes with several components that help user to choose from a large variety of colors.


Thursday, 14 November 2013

Getting Started with JList and JComboBox

The following tutorial illustrates getting started with two major swing components, the JList and JComboBox. The examples below provide you a basic understanding of what they are.

JComboBox lets the user choose a single item from multiple items. It only displays single item to the user. You can see it in many sites, where they ask you to choose your country.
JList is another light-weight component similar to a JComboBox but with two major differences. The first is that JList shows multiple items (rows) to the user and also it gives an option to let the user select multiple items.

4 JCheckBox and JRadioButton Examples for a Kickstart

These four examples on JCheckBox and JRadioButton which cover almost all of their methods and constructors gives you a deeper understanding of them.
A JCheckBox lies on a single principle, checked/unchecked. This component is mostly used in when we are checking multiple items, for example in Job search site, you might have undergone this where you select multiple skills, a check box is mostly used.
  1. JCheckBox Kickstart Example for Starters
  2. How to give JCheckBox a Button feel?
  3. How to add JCheckBox to JButton?
JRadioButton is also based on the same principle as that of the JCheckBox. But the difference is that a JRadioButton is typically used when the user has to choose only one among the many items in a group. For instance, you can use it for Male/Female, the user has to select either of it, but not both. In AWT, you don't have specified class for JRadioButton as here.
  1. JRadioButton Kickstart* Example for Starters
Note: JButton, JToggleButton, JCheckBox and JRadioButton are all sub-classes of AbstractButton.

3 JButton and JToggleButton Examples To Get Started

Here are 3 examples, two on JButton and one on JToggleButton which gives you an effortless start. These examples cover almost all of the methods and constructors in these classes.
JButton is a nothing more than a push-button which you might already have gone through many times. User can click on it to get anything done.
  1. Creating Buttons in Swing
  2. Complete JButton Example for Beginners
A JToggleButton is another component much similar to a JButton. But the difference is that a JToggleButton goes into pressed state when mouse is pressed on it. To get that back into normal state, we need to press again. This component is mostly used when there is an on/off situation. You'll get a better idea of what it is when you see it in practical.

2 JPanel Examples Everyone Must Learn

Here are 2 JPanel examples that every beginner must learn.
JPanel is a container which is a sub class of JComponent that stores other components in it. This can be added to any top-level container like JFrame and JDialog to group components. Like others this too can be customized.
  1. JPanel Example for Beginners
    This example gives you a kickstart by convering the core methods of JPanel, that are the minimum basic.
  2. Creating transparent JPanel easily
    This tiny example lets you create semi transparent JPanel in swing.

Wednesday, 13 November 2013

8 JFrame Examples You Should Know - Swing

JFrame is a top-level container which is nothing more than a window with a title bar and an optional menu bar.
  1. Creating a JFrame in Swing Example - A Kickstart
    This example introduces the most common methods of JFrame class.
  2. Set background color in JFrame
    You cannot set the background for a JFrame just by using the setBackground() method. This example contains the single thing you need to set the background.
  3. Set background image in JFrame
    This example shows you how to set a background image in JFrame in three ways.
  4. 3 Ways to Set Icon image for JFrame
    An icon image is the one that appears in the top-left corner of a title bar. The example will teach you three simple ways to set icon.
  5. How to create a transparent JFrame in Swing
    Opaque frames are boring. Aren't they? This example shows how to create semi-transparent JFrame easily using a simple method.
  6. Create shaped transparent JFrame in Swing
    You can also set custom shape to a JFrame but it should be undecorated. This example contains JFrames of different shapes.
  7. Using setDefaultLookAndFeelDecorated() in JFrame
    This example contains how to set the default look and feel decorated so that the titlebar's appearance changes.
  8. Double titlebar for JFrame in Swing
    Creating a double titlebar is weird but can be done in a single line!
Well, I couldn't guarantee that these 8 JFrame examples are everything that you should know, but these cover about 95% of JFrame and give you a kickstart. There are a lot of other examples on JFrame in this blog, but as they are involved with event handling, and this is a written in an order, they aren't included.

Using MaskFormatter in JFormattedTextField

The following example illustrates using MaskFormatter in JFormattedTextField to restrict the user to type a phone number. The advantage with a MaskFormatter is that the user cannot even type against the format specified in it. For example, in the following program, the user will only be able to enter numbers but and that to only 12. He cannot type more than that, and if he types less than that and hits enter. In this example, you'll learn..
  1. How to create a mask formatter?
  2. How to use it with JFormattedTextField?
  3. What is setPlaceholderCharacter() and how to use it?

import javax.swing.*;
import java.awt.*;
import javax.swing.text.*;
class MaskFormatterExample1 extends JFrame
{
JFormattedTextField t;
MaskFormatter m;

    public MaskFormatterExample1()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Mask formatter Example");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
       
        // A phone number formatter
        // (country code)-(area code)-(number)
        try
        {
        m=new MaskFormatter("##-###-#######");
        m.setPlaceholderCharacter('#');
        t=new JFormattedTextField(m);
        t.setColumns(12);
        add(t);
        }catch(Exception e){}
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new MaskFormatterExample1();
    }
}

new MaskFormatter("##-###-#######"); This creates a MaskFormatter object where # represents a number and hyphen here separates country, area codes and phone number.
setPlaceholderCharacter(): This method sets the place holder character that appears in the place of digits that aren't entered. You will understand when you see it in practical.

MaskFormatter with JFormattedTextField
 
“Do not go where the path may lead; go instead where there is no path and leave a trail” - Ralph Waldo Emerson

Using setDefaultLookAndFeelDecorated() in JFrame

The following illustrates setting a default look and feel deocrated in JFrame. I think, I have done it once, got the desired output. But later, I forgot so I didn't share it in my blog. I know the method, but the ridiculous thing I am doing is that I recklessly forgot the static keyword in front of the setDefaultLookAndFeelDecorated() method. I've created a JFrame object, made it visible and then I am trying to set the default look and feel decorated. How funny that I forgot such a simple point, I'll have to confess. When the frame is visible, the such changes to it doesn't occur. Just like in the JFileChooser, where you cannot set the accessory after the JFileChooser is shown, we can't do this too.

But what is default look and feel decorated? Well, I can't describe it in words, just see the output window, you'll understand what it really is?

A window with default look and feel (metal) decorated


import javax.swing.*;
import java.awt.*;
class LookAndFeelDecorated extends JFrame
{
JButton b;

    public LookAndFeelDecorated()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Look And Feel Decorated");
        setLayout(new FlowLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        b=new JButton("Button");
        add(b);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        // Do it here, before creating object for the
        // JFrame!, Mandatory!
        JFrame.setDefaultLookAndFeelDecorated(true);
        new LookAndFeelDecorated();
    }
}

The method setDefaultLookAndFeelDecorated() works only in MetalLookAndFeel as far as I am concerned because it didn't in others in my practice.

Also see double titlebar for JFrame

The greatest compliment you can give to me is sharing this post. I sincerely appreciate it :)

“When you are afraid to act for fear of being wrong, then you have ignored the chance of doing right.” - AK

A Tiny JPopupMenu Example - Swing

Here is a tiny example illustrating JPopupMenu on JButton in Swing.

import javax.swing.*;
import java.awt.*;
class JPopupMenuExample extends JFrame
{
JButton b;
JPopupMenu p;
JMenuItem m1,m2,m3,m4;

    public JPopupMenuExample()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("JPopupMenu Example");
        setLayout(new FlowLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        b=new JButton("Right click me");
        add(b);
       
        p=new JPopupMenu();
        m1=new JMenuItem("Item 1");
        m2=new JMenuItem("Item 2");
        m3=new JMenuItem("Item 3");
        m4=new JMenuItem("Item 4");
       
        b.setComponentPopupMenu(p);
       
        p.add(m1);
        p.add(m2);
        p.add(m3);
        p.add(m4);
       
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new JPopupMenuExample();
    }
}
setComponentPopupMenu(): This method is present in the JComponent class, so inherited to all light-weight swing components. This method takes JPopupMenu object. Using the add() we can add JMenuItems to the popup menu.
I would be grateful, if you share this post.

“Simplicity is the ultimate sophistication.” - Leonardo da Vinci

How to set frame icon in JInternalFrame?

The following example illustrates how to set frame icon for JInternalFrame using setFrameIcon() method.

import javax.swing.*;
import java.awt.*;
class SetIconJInternalFrame extends JFrame
{
JInternalFrame f;
JDesktopPane p;

    public SetIconJInternalFrame()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Set icon for JInternalFrame");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        p=new JDesktopPane();
        p.setBackground(Color.GRAY);
       
        // title, resizable, closable, maximizable, iconifiable
        f=new JInternalFrame("Title",true,true,true,true);
        f.setSize(250,250);
        f.setVisible(true);
       
        // Set icon
        f.setFrameIcon(new ImageIcon("imageicon.png"));
       
        p.add(f);
       
        add(p);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new SetIconJInternalFrame();
    }
}

In this way we can set icon using the setFrameIcon() method. I would be grateful to you, if you share this.
“What would life be if we had no courage to attempt anything?” - Vincent Van Gogh

6 Ways to Create a JInternalFrame - Example

The following example illustrates 6 ways to create a JInternalFrame easily using its six constructors.

import javax.swing.*;
import java.awt.*;
class JInternalFrameExample extends JFrame
{
JInternalFrame f1,f2,f3,f4,f5,f6;
JDesktopPane pane;

    public JInternalFrameExample()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("JInternalFrame Example");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
      
        pane=new JDesktopPane();
        pane.setBackground(Color.GRAY);
      
        // No title,not resizable,not iconifiable,not maximizable, not closable, no icon
        f1=new JInternalFrame();
      
        // Only title, others same as above
        f2=new JInternalFrame("Internal Frame 2");
      
        // title and resizable
        f3=new JInternalFrame("Internal Frame 3",true);
      
        // title, resizable, closable
        f4=new JInternalFrame("Internal Frame 4",true,true);
      
        // title, resizable, closable, maximizable
        f5=new JInternalFrame("Internal Frame 5",true,true,true);
      
        // title, resizable, closable, maximizable, iconifiable
        f6=new JInternalFrame("Internal Frame 6",true,true,true,true);
      
        // Set title for f4
        f4.setTitle("Internal Frame 1");
      
        // Set sizes
        f1.setSize(150,150);
        f2.setSize(150,150);
        f3.setSize(150,150);
        f4.setSize(150,150);
        f5.setSize(150,150);
        f6.setSize(150,150);
      
        // Make all visible
        f1.setVisible(true);
        f2.setVisible(true);
        f3.setVisible(true);
        f4.setVisible(true);
        f5.setVisible(true);
        f6.setVisible(true);
      
        f1.setLocation(20,20);
        f2.setLocation(40,40);
        f3.setLocation(60,60);
        f4.setLocation(80,80);
        f5.setLocation(100,100);
        f6.setLocation(120,120);
      
        // Add all!
        pane.add(f1);
        pane.add(f2);
        pane.add(f3);
        pane.add(f4);
        pane.add(f5);
        pane.add(f6);
      
        add(pane);
      
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new JInternalFrameExample();
    }
}

JInternalFrame(String title, boolean resizable, boolean closeable, boolean maximizable, boolean iconifiable): This is the sixth constructor, If you can understand this, you'll understand all the remaining constructors. title represents the title of the internal frame, next is resizable whether the frame can be resized, whether the frame can be closed, whether it can be maximized and iconified. The default values of these is false and there will be no title initially. If any of the parameter is not specified in the constructor, the boolean value is false. We need not add JInternalFrame to JDesktopPane but we generally do it. In this way, we can easily create six JInternalFrames using its constructors.

Three things cannot be long hidden: the sun, the moon, and the truth. - Buddha

Tuesday, 12 November 2013

4 Ways to Show JOptionPane Confirm Dialog

Screenshot of confirm dialog
The following example illustrates 4 ways to show confirm dialog in JOptionPane.


import javax.swing.*;
import java.awt.*;
class ConfirmDialogExample extends JFrame
{

    public ConfirmDialogExample()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("JSplitPane Example");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        // These display one after the other is closed
        JOptionPane.showConfirmDialog(this,"This is message - 1");
        JOptionPane.showConfirmDialog(this,"This is message - 2 - with yes_no","This is title",JOptionPane.YES_NO_OPTION);
        JOptionPane.showConfirmDialog(this,"This is message - 3 - with message type and ok_cancel","This is title",JOptionPane.OK_CANCEL_OPTION,JOptionPane.WARNING_MESSAGE);
        JOptionPane.showConfirmDialog(this,"This is message - 4 - with icon","This is title",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE,new ImageIcon("imageicon.png"));
       
       
        setSize(400,400);
        setVisible(true);   
    }
   
    public static void main(String args[])
    {
    SwingUtilities.invokeLater(new Runnable(){
            public void run()
            {
            new ConfirmDialogExample();
            }
        });
    }
}

showConfirmDialog(): This method takes in several parameters. If you were able to understand the last one, you'll understand all the remaining. The first parameter is the parent component, next is the message to be displayed, followed by title of JOptionPane, the type of option, type of message and custom icon image.

By default, title will be Select an Option, option type will be YES_NO_CANCEL_OPTION, type of message will be QUESTION_MESSAGE

3 Ways to Show JOptionPane Message Dialog

Screenshot of 2nd message dialog
The following dead simple program illustrates 3 ways to show message dialog in JOptionPane.


import javax.swing.*;
import java.awt.*;
class MessageDialogExample extends JFrame
{

    public MessageDialogExample()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("JSplitPane Example");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        // These display one after the other is closed
        JOptionPane.showMessageDialog(this,"This is message - 1");
        JOptionPane.showMessageDialog(this,"This is message - 2","This is title",JOptionPane.WARNING_MESSAGE);
        JOptionPane.showMessageDialog(this,"This is message - 3","This is title",JOptionPane.WARNING_MESSAGE,new ImageIcon("imageicon.png"));
       
       
        setSize(400,400);
        setVisible(true);   
    }
   
    public static void main(String args[])
    {
    SwingUtilities.invokeLater(new Runnable(){
            public void run()
            {
            new MessageDialogExample();
            }
        });
    }
}

showMessageDialog(): The three overloaded versions of these methods take in the parent component represented as this followed by the message to be displayed in the JOptionPane, it's title, type of message (warning or error or information etc) and image icon to be displayed.

Using setDividerSize() and setResizeWeight() in JSplitPane

The following example illustrates setting divider size and resize weight that allows you to position split pane at center or where ever you want. Here are prototypes of the methods..

// Set divider size

public void setDividerSize(int size)



// Throws IllegalArgumentException if weight doesn't conform to below rule

public void setResizeWeight(double weight) // 0<=weight<=1


import javax.swing.*;
import java.awt.*;
class JSplitPaneExample extends JFrame
{
JSplitPane js;
JPanel p1,p2;

    public JSplitPaneExample()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("JSplitPane Example");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        // Create panels
        p1=new JPanel();
        p1.setBackground(Color.GRAY);
       
        p2=new JPanel();
        p2.setBackground(Color.BLACK);
       
        // Add JSplitPane
        js=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,p1,p2);
       
        // Add divider size, weight
        js.setDividerSize(20);
        js.setResizeWeight(0.5);
       
        add(js);
       
        setSize(400,400);
        setVisible(true);   
    }
   
    public static void main(String args[])
    {
    SwingUtilities.invokeLater(new Runnable(){
            public void run()
            {
            new JSplitPaneExample();
            }
        });
    }
}


The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)

Using JFormattedTextField with strict SimpleDateFormat

Hello, here I'm going to show you how to use JFormattedTextField with a strict SimpleDateFormat in a tiny program.




import javax.swing.*;


import java.awt.*;


import java.text.*;


class JFormattedFieldExample extends JFrame


{


JFormattedTextField t;





public JFormattedFieldExample()


{


createAndShowGUI();


}




private void createAndShowGUI()


{


setTitle("JFormattedField Example");


setDefaultCloseOperation(EXIT_ON_CLOSE);


setLayout(new FlowLayout());




SimpleDateFormat s=new SimpleDateFormat("dd/MM/yyyy");




// Make it strict, so that it doesn't allow


// some conditions like, if month > 12


// day > 31 etc.


s.setLenient(false);




t=new JFormattedTextField(s);


t.setColumns(20);




try


{


t.setValue(s.parse("01/01/1996"));


}catch(Exception e){}




add(t);




pack();


setLocationRelativeTo(null);


setVisible(true);


}




public static void main(String args[])


{


new JFormattedFieldExample();


}


}

The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)


“Try and fail, but don't fail to try.” - Stephen Kaggwa

Monday, 11 November 2013

Using GlassPane to block input in JFrame

Using GlassPane to block input in JFrame
Since time, I have been stumped of how to use glass pane even when seeing the tutorial. Now, here is an example on how to use GlassPane to block input in JFrame by creating a transparent black background for that GlassPane with a busy symbol as if some data is being processed. When the user clicks any where on the JFrame when processing the data then a beep sound is played.



import javax.swing.*;


import java.awt.*;


import java.awt.event.*;


class BlockInput extends JFrame


{


JButton b;





public BlockInput()


{


createAndShowGUI();


}




private void createAndShowGUI()


{


setTitle("Block input");


setLayout(new FlowLayout());


setDefaultCloseOperation(EXIT_ON_CLOSE);




// Create JButton


b=new JButton("Block input");


add(b);




b.addActionListener(new ActionListener(){


public void actionPerformed(ActionEvent ae)


{


// Create a JPanel with semi-transparent


// black background


// This will be glass pane


JPanel p=new JPanel(){


public void paintComponent(Graphics g)


{


g.setColor(new Color(0,0,0,140));


g.fillRect(0,0,getWidth(),getHeight());


}


};




// Set it non-opaque


p.setOpaque(false);




// Set layout to JPanel


p.setLayout(new GridBagLayout());




// Add the jlabel with the image icon


p.add(new JLabel(new ImageIcon("loading.gif")));




// Take glass pane


setGlassPane(p);




// Add MouseListener


p.addMouseListener(new MouseAdapter(){


public void mousePressed(MouseEvent me)


{


// Consume the event, now the input is blocked


me.consume();




// Create beep sound, when mouse is pressed


Toolkit.getDefaultToolkit().beep();


}


});




// Make it visible, it isn't by default because


// it is set as glass pane


p.setVisible(true);


}


});




setSize(400,400);


setVisible(true);


setLocationRelativeTo(null);


}




public static void main(String args[])


{


new BlockInput();


}


}

The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)


“Genius is 1% inspiration 99% perspiration” - Thomas Alva Edison

Sunday, 10 November 2013

3 Dead Simple Ways to Create a JTree

Screenshot of JTable Example
JTree, a funny, advanced and a terrific component. But why is it funny? It looks like that for me, for you? Advanced? Yes, because I didn't see it in the AWT. Terrific? Hmm, the name isn't but there is a minister DefaultMutableTreeNode at its back without which JTree would be nothing more than a seed that is. OMG!! See how the name is?? What is mutable? What is node? What's all this? Feel like skimming down to program! Stop, especially if you are a starter! Don't even close the tab!! Haha!

First of all, a DefaultMutableTreeNode is a class. Consider it as a cell in a JTree, otherwise consider it is a branch of a tree. A branch may nor may not have sub-branches. Similarly, a node may nor may not have sub-nodes (a.k.a. children). See the below, diagram. I'm sure, everything will be clear.

Explaining DefaultMutableTreeNode - Root, Parents, Leaves

Consider an analogy, ROOT is the oldest one in the family say your Grandfather who has three children called colors, sports and food. You are Mr. Blue (say for example) and your siblings are violet, red and yellow. sports and food are your uncles and they have their own children. Neither you nor your siblings nor your cousins (basketball,soccer,hotdogs....) have children. So you are called leaves. But your father and his brothers have, so they are parents of leaves, but they ultimately have one father, the oldest one in the family is the root.


 import javax.swing.*;
import java.awt.*;
import javax.swing.tree.*;
class JTreeExample extends JFrame
{
JTree jt1,jt2,jt3;
String[] data={"Item 1","Item 2","Item 3","Item 4","Item 5"};
DefaultMutableTreeNode parent,i1,i2,i3,i4,i5;
JScrollPane js1,js2,js3;

    public JTreeExample()
    {
        createAndShowGUI();
    }
  
    private void createAndShowGUI()
    {
        setTitle("JTree Example");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new GridLayout(2,3));
      
        jt1=new JTree();
      
        js1=new JScrollPane(jt1);
      
        add(js1);
      
        // Without any root but given data
        jt2=new JTree(data);
      
        // Create JScrollPane for jt2
        js2=new JScrollPane(jt2);
      
        // add js2
        add(js2);
      
        // The parent node contains children (aka sub-nodes)
        parent=new DefaultMutableTreeNode("Parent node");
      
        // These are good, they love children but they
        // haven't
        // They are just leaves, they don't have sub-nodes (a.k.a children)
        i1=new DefaultMutableTreeNode("Item 1!");
        i2=new DefaultMutableTreeNode("Item 2!");
        i3=new DefaultMutableTreeNode("Item 3!");
        i4=new DefaultMutableTreeNode("Item 4!");
      
        // If false, i5 doesn't allow children, may be
        // it did family planning operation!! ;)
        // default is true
        i5=new DefaultMutableTreeNode("Final Item",false);
      
        // Add a sub item to i1
        i1.add(new DefaultMutableTreeNode("Sub item 1"));
      
        // Add children to parents
        parent.add(i1);
        parent.add(i2);
        parent.add(i3);
        parent.add(i4);
        parent.add(i5);
      
        // A jtree with parent
        // Here parent is only one, he is root too!!
        jt3=new JTree(parent);
      
        js3=new JScrollPane(jt3);
      
        add(js3);
      
        setSize(400,400);
        setVisible(true);
    }
  
    public static void main(String args[])
    {
        new JTreeExample();
    }
}

The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)


“Always do what you are afraid to do.” - Ralph Waldo Emerson

Creating a JTable in Swing Effortlessly - Example

Screenshot of JTable created without effort
Here is a 3-line code that creates the type of JTable you might just be expecting as a starter. JTable class is quite terrific because it looks big, Lab Dab!! The first time I saw it, I was frightened, did you? However, the great thing is some of the constructors especially the one that takes rows and columns and row data and column data are quite simple to learn.

As this is a starter program, I didn't discuss any of the methods of the JTable rather I focused on creating a JTable using the simple row-data and column data constructor and displaying that data. This program, though not exhaustive will give you a kickstart that will remove the entire fear (if you have) about JTable and help you recognize that learning JTable is as easy as eating a cheese burger.


import javax.swing.*;
import java.awt.*;
class JTableExample extends JFrame
{
JTable t;
JScrollPane js;
String[][] rowData=    {
                    {"101","Rama","10000"},
                    {"102","Soma","20000"},
                    {"103","Raju","30000"},
                    {"104","Moju","40000"},
                    {"105","Kotu","50000"},
                    {"106","Potu","60000"}
                    };
String[] colNames=    {"ID Number","Name","Salary"};

    public JTableExample()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("JTable Example in Swing");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
      
        t=new JTable(rowData,colNames);
      
        js=new JScrollPane(t);
      
      
        setSize(400,400);
        setLocationRelativeTo(null);
        setVisible(true);
        add(js);
    }
   
    public static void main(String args[])
    {
        SwingUtilities.invokeLater(new Runnable(){
            public void run()
            {
            new JTableExample();
            }
        });
    }
}

The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)


“Obstacles only delay success; they don't stop it.” - Gowtham Gutha

Why should we write setVisible() at last?

In many posts, I have been mentioning to push down the setVisible() to last, Did I? But why? I think, I have not mentioned a reason before. Now, I decided to write this post with enthusiasm. The reason is I'm going to make it a bit funny with an analogy.

You know that setVisible() is used to make a component visible. Mostly we will be using it to show JFrame. Fine, until recently I have been writing setVisible() at the top before adding all the components. Then, I recently started turning the game around.

Why push add() to the top? (The analogy, the fun!)

You can make a JFrame visible before adding the components. Right? But how will it look? Consider a general life situation, say you want to go out for a party.. You get ready before you attend the party, you bath, dress up, makeup. But how will it look when you do after attending/in the party? Just imagine!! Lol!

You'll need to do the complete make up before you make the frame ready to get displayed. Fine.

Also, writing setLocationRelativeTo() before sizing the frame will not give the desired effect because it depends upon the size of the frame. So the frame needs to have a size before it's location is set relative to something. If its size is changed after the location is set, then you got an undesired output. So, be careful. See the following program, you get an undesired output if you execute it.


import javax.swing.*;
class LocationFail
{
    public static void main(String args[])
    {
        JFrame f=new JFrame("My Frame");
        f.setVisible(true);
       
        f.setLocationRelativeTo(null);
       
        // the wrong thing!!
        // doesn't appear at the center
        f.setSize(400,400);
    }
}

Even when you are working with pack() you need to add all the components first, pack the frame and then invoke setLocationRelativeTo() and then setVisible(), now this looks great!

Are there any analogies or counter arguments that you would love to fire on me? Discuss them in comments below.

The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)


“If you can imagine it, you can achieve it; if you can dream it, you can become it.” - William Arthur Ward

Animate Icon Image in JFrame

Screenshot of animated image
Here is how to animate icon image in JFrame using the Timer class. The code written in the actionPerformed() here is executed for every 10 milliseconds so that the icon image keeps changing. The code is simple, just take a look at it.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class AnimateJFrameIconImage extends JFrame
{
Timer t;
int i;

    public AnimateJFrameIconImage()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Animated Icon Image");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
       
        // Create a Timer to do animation
        t=new Timer(10,new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
                // Set icon image for JFrame
                setIconImage(new ImageIcon(getClass().getResource("/icons/busy-icon"+i+".png")).getImage());
                i++;
                // I have only 10 icons!
                if(i==10) i=0;
            }
        });
       
        t.start();
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new AnimateJFrameIconImage();
    }
}

The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)