• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Swing

Java Swing Timer class Example

By Dinesh Thakur

A timer is an object of Timer class which is the subclass of Object class present in java.lang package. A timer fires one or more action events after regular interval of time (in milliseconds) called delay.

 

The amount of delay is specified at the time of creation of timer. A timer is used in a program by creating a timer object and invoking start () method. When the timer is started, an event of ActionEvent type is fired and the code enclosed in actionPerformed () of the corresponding listener class is executed. The corresponding class must implement the ActionListener interface. The timer can also be made to fire an event only once by setting its method setRepeats () to false. The methods stop () and restart () can be called to stop or restart the timer, respectively.

The Timer can be created using the following constructor.

Timer(int delay, ActionListener listener)

where,

delay is the time, in milliseconds, between the action events

listener is the action listener

Consider Example. Here, a countdown of 10 seconds is printed. After 10 seconds, the program exits.

Example: A program to demonstrate the use of timer

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

class TimerExample implements ActionListener

{

   int second = 1;

   public static void main(String str[])

   {

     new TimerExample();

     while(true);

   }

    public TimerExample()

    {

       Timer second= new Timer(1000,this);

       second.start();

    }

    public void actionPerformed(ActionEvent e)

    {

       System.out.print(” “+second);

       second++;

       if (second == 11)

         {

                System.out.print(” “);

                System.out.print(“Exit out”);

                System.exit(0);

         }

    }

}

 The output of the program is as shown in Figure

         java swing timer class example

JWindow class in Java Swing Example

By Dinesh Thakur

The JWindow class is used to create a window which does not have any toolbar, border or window management buttons. This type of window is usually used to display messages like welcome messages, Copyright information, etc. The commonly used of constructor of JWindow class is as follows.

JWindow ()

Example: A program to demonstrate the use of JWindow class

import java.awt.*;

import javax.swing.*;

class Message

{

     public static void displayMessage(int timeDuration)

     {

        JWindow msg =new JWindow();

        JPanel panel= (JPanel)msg.getContentPane();

        int width = 350, height = 150;

        int x = 50, y = 50;

        msg.setBounds(x, y, width, height);

        JLabel welcome= new JLabel(“Welcome! to Java Programming”,JLabel. CENTER);

        welcome.setFont(new Font(“Times New Roman”, Font.BOLD, 20));

        panel.add(welcome, BorderLayout.CENTER);

        panel.setBorder(BorderFactory.createLineBorder(Color.green, 5));

        msg.setVisible(true);

        try

          {

             Thread.sleep(timeDuration);

          }

          catch(Exception e) {}

          msg.setVisible(false);

     }

      public static void main(String args[])

      {

          displayMessage(8000);

          System.exit(0);

      }

}

The output of the program is shown in Figure

                      JWindow class in Java Swing Example

GridBagLayout in Java Swing Example

By Dinesh Thakur

The grid bag layout manager is the most advanced and yet easy to use layout manager. A GridBagLayout arranges the component in a grid of rows and columns. It allows different sized components to span multiple rows or columns. Also, each row in the grid can have different number of columns. Grid bag layout specifies a grid of cells with the container determines the component’s size and then positions each component in one or more cell accordingly.

The grid bag layout manager can be created by using the following constructor.

GridBagLayout ()

Information such as, size and location of each component in a grid bag is determined by a set of constraints contained in an object of type GridBagConstraints. The variables in the class GridBagConstrain ts that represent these constraints are given below:

• gridx and gridy: gridx and gridy specify the x and y coordinates to position the component. gridx and grid y represent the number of cells at the left of the component and the number of cells at the top of the component, respectively. By default, the value of both gridx and gridy is relative. It places the component at position next to the component added last in a row or a column.

• gridwidth and gridheight: gridwidth and gridheight specify the number of columns and rows, respectively occupied by the components. The default value for both gridwidth and gridheight is 1. The value REMAINDER can be assigned to gridwidth and gridheight to indicate that the component should be the last one in a row or a column. Ifwe want the component to be the next to last one in a row or a column, the value RELATIVE is used.

• fill: fill specifies how the component should expand within its display area if the area is larger than the component. Any one of the following values can be assigned to fill.

NONE: To specify that the size of the component remains unchanged. It is the default value.

VERTICAL: To specify that the component can expand only vertically.

HORIZONTAL: To specify that the component can expand only horizontally.

BOTH: To specify that the component can expand vertically as well as horizontally.

• ipadx and ipady: ipadx and ipady specify extra width and height of the component, respectively. The default value is 0. Negative values can also be used to tighten the spacing between the components.

• insets: It specifies the amount of space to leave between the borders of the component and the edges of display area. The Insets class specifies the separate values of top, left, bottom, and right. The default value is (0,0,0,0).

• anchor : It specifies where the component should be placed within the display area if it is smaller than its display area. The location of the component is usually given as a compass direction. Any one of the following values can be assigned to anchor.

CENTER(default), NORTH, SOUTH, NORTHEAST, SOUTHWEST, EAST, WEST, SOUTHEAST,NORTHWEST

• weightx and weighty: weightx and weighty specify how the extra horizontal and vertical spaces be adjusted while resizing the container. The component will occupy extra space in the specific direction according to the weight assigned to it.

Consider Example. In this example, grid bag layout is set as the layout for the frame. Five buttons are created and their grid bag constraints are specified. Then the buttons are added to the frame.

Example: A Program to demonstrate the use of GridBaglayout

import java.awt.*;

import javax.swing.*;

class myGridBag extends JApplet

{

    final static boolean shouldWeightX = true;

    final static boolean RIGHT_TO_LEFT = false;

    public static void addComponentsToPane(Container pane)

     {

        if (RIGHT_TO_LEFT)

           {

               pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

           }

               JButton button;

               pane.setLayout(new GridBagLayout());

               GridBagConstraints gb =new GridBagConstraints();

               button= new JButton(“Button 1”);

               if (shouldWeightX)

                  {

                     gb.weightx = 0.5;

                  }

               gb.fill = GridBagConstraints.HORIZONTAL;

               gb.gridx = 0;

               gb.gridy = 0;

               pane.add(button, gb);

               button= new JButton(“Button 2”);

               gb.fill = GridBagConstraints.HORIZONTAL;

               gb.weightx = 1;

               gb.gridx = 1;

               gb.gridwidth = 2;

               gb.gridy = 0;

               pane.add(button, gb);

               button= new JButton(“Button 3”);

               gb.fill = GridBagConstraints.VERTICAL;

               gb.ipady = 30;

               gb.weightx = 2;

               gb.gridwidth = 4;

               gb.gridx = 0;

               gb.gridy = 1;

               pane.add(button, gb);

               button= new JButton(“Button 4”);

               gb.fill = GridBagConstraints.VERTICAL;

               gb.ipady = 0; //reset to default

               gb.weighty = 1.0;

               gb.anchor = GridBagConstraints.PAGE_END;

               //bottom of space

               gb.insets =new Insets(10,0,0,0); //top padding

               gb.gridx = 1;

               gb.gridwidth = 2;

               gb.gridy = 2; //third row

               pane.add(button, gb);

               button= new JButton(“Button 5”);

               gb.fill = GridBagConstraints.HORIZONTAL;

               gb.weighty = 1.0;

               gb.anchor = GridBagConstraints.PAGE_END;

               gb.insets =new Insets(10,0,5,0);

               gb.gridx = 0;

               gb.gridwidth = 2;

               gb.gridy = 3; //fourth row

               pane.add(button, gb);

     }

              private static void displayGUI()

              {

                  JFrame frame= new JFrame(“GridBagLayoutDemo”);

                  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                  addComponentsToPane(frame.getContentPane());

                  frame.setSize(500, 300);

                  frame.setVisible(true);

              }

                public static void main(String[] args)

                {

                     javax.swing.SwingUtilities.invokeLater(new Runnable()

                     {

                        public void run()

                        {

                           displayGUI ();

                        }

                     }) ;

                }

}

The output of the program is shown in Figure

               GridBagLayout in Java Swing Example

JLayeredPane Java Swing Example

By Dinesh Thakur

A layered pane is a Swing container which is used to hold the various components using the concept of layers. The components present in the upper layer overlaps the components present in the lower layer. The layered pane is created using the JLayeredPane class. the only constructor of this class is JLayeredPane ().

Example: A program to demonstrate the use of JLayeredPane class.

import java.awt.*;

import javax.swing.*;

class LayerExample extends JApplet

{

    JFrame jf ;

    JLayeredPane LPane;

    JButton first, second, third;

    LayerExample ()

    {

         jf =new JFrame(“Layered Pane Example”);

         LPane =new JLayeredPane();

         jf.getContentPane() .add(LPane);

         first= new JButton(“First”);

         first.setBackground(Color.red);

         first.setBounds(50,30,100,100);

         second= new JButton(“Second”);

         second.setBackground(Color.yellow);

         second.setBounds(140,60,100,100);

         third= new JButton(“Third”);

         third.setBackground(Color.green);

         third.setBounds(230,90,100,100);

         LPane.add(first, new Integer(3));

         LPane.add(second, new Integer(2));

         LPane.add(third, new Integer(1));

         jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);

         jf.setSize (400,300) ;

         jf.setVisible(true);

     }

         public static void main(String args[])

        {

            LayerExample le= new LayerExample();

        }

}

The output of the program is shown in Figure

              Layered Panes Java Swing Example

Swing JScrollBar Class Example

By Dinesh Thakur

Scroll bars are horizontally or vertically oriented bars which allow the user to select items between a specified minimum and maximum values. Each end of the scroll bar has an arrow which can be clicked to change the current value of the scroll bar. The slider box indicates the current value of the scroll bar which can be dragged by the user to a new position. Scrollbar is an object of ScrollBar class.

Some of the constructors defined by ScrollBar class are as follows.

JScrollBar() //first

JScrollBar(int orientation) //second

JScrollBar(int orientation, int initial_value, int visible units, int min, int max) //third

The first constructor creates a vertical scroll bar. The second constructor creates a scrollbar in which orientation specifies the orientation of the scroll bar which can take one of the following values JScrollBar.HORIZONTAL or JScrollBar.VERTICAL. The third constructor creates a scroll bar in which orientation specifies the orientation of the scroll bar, initial_value represents the initial value of the scrollbar, visible_units represents the number of visible items of a scroll bar at a time and min and max represents the minimum and maximum values for the scroll bar.

Consider the Example. Here, two scrollbars (one horizontal and one vertical) are added

Example An applet to demonstrate the use of Scrollbar class

import javax.swing.*;

public class ScrollBarExample extends JApplet

{

   ScrollBarExample()

   {

       JFrame jf;

       jf=new JFrame(“ScrollBar”);

       JPanel jp=new JPanel();

       JLabel j11=new JLabel(“Scrollbar:”);

       JScrollBar jsv=new JScrollBar();

       JScrollBar jsh=new JScrollBar(JScrollBar.HORIZONTAL);

       jp.add(j11);

       jp.add(jsv);

       jp.add (jsh);

       jf.add (jp);

       jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);

       jf.setSize(300,200);

       jf.setVisible(true);

    }

       public static void main(String[] args)

        {

            ScrollBarExample japp= new ScrollBarExample();

        }

}

The output of the above code is Figure

                 Scrollbar Example

Swing Containers

By Dinesh Thakur

Swing component is an independent control, such as button, label, text field, etc. They need. a container to display themselves. Swing components are derived from JComponent class. JComponent provides the functionality common for all components. JComponent inherits the AWT class Container and Component. Thus, a Swing component and AWT component are compatible with each other.

There are two types of containers namely, top-level containers and lightweight containers

Top-Level Containers

A top-level container, as the name suggests, lies at the top of the containment hierarchy. The top-level containers are JFrame, JApplet, and JDialog. These containers do not inherit JComponent class but inherit the AWT classes’ Component and Container. These containers are heavyweight components. The most commonly used containers are JFrame and JApplet.

Each top-level container defines a set of panes. JRootPane is a special container which extends JComponent and manages the appearance of JApplet and JFrame objects. It contains a fixed set of panes, namely, glass pane, content pane, and layered pane.

• Glass pane: A glass pane is a top-level pane which covers all other panes. By default, it is a transparent instance of JPanel class. It is used to handle the mouse events affecting the entire container.

• Layered pane: A layered pane is an instance of JLayeredPane class. It holds a container called the content pane and an optional menu bar.

• Content pane: A content pane is a pane which is used to hold the components. All the visual components like buttons, labels are added to content pane. By default, it is an opaque instance of JPanel class and uses border layout. The content pane is accessed via getContentPane () method of JApplet and JFrame classes.

Lightweight Containers

Lightweight containers lie next to the top-level containers in the containment hierarchy. They inherit. JComponent. One of the examples of lightweight container is JPanel. As lightweight container can be contained within another container, they can be used to organize and manage groups of related components.

What are Features of java swing?

By Dinesh Thakur

Swing, a part of Java Federation Classes (JFC) is the next generation GUI toolkit that allows us to develop large scale enterprise applications in Java. It is a set of classes which provides many powerful and flexible components for creating graphical user interface. Earlier, the concept of Swing did not exist in Java and the user interfaces were built by using the Java’s original GUI system, AWT. Because of the limitations of the AWT, Swing was introduced in 1997 by the Sun Microsystems. It provides new and improved components that enhance the look and functionality of GUIs. [Read more…] about What are Features of java swing?

MVC Design Pattern

By Dinesh Thakur

• The (Model View Controller) MVC design pattern separates a software component into three distinct pieces: a view, a model  and a controller.

• The model stores the content. It manages the state and conducts all transformations on that state. The MVC model has no specific knowledge of either its controllers or its views. The Link is maintain by system between model and views and notifies the views when the state change occurs. For example – For the button component model will hold the information about the state of button such as whether the button is pushed or not.

• The view displays the contents. It manages the visual display of the state represented by the model. Thus  model view can be represented graphically to the user. For example – For example: For the button component the color, the size of the button will be decided by the view.

                                    MVC Design Pattern

 

• The controller is for managing the user interaction with the model. It is basically for handling the user input. The controller takes care of mouse and keyboard events. For example – For the button component the reaction of events on the button press will be decided by the controller.

• The MVC architecture of swing specifies how these three objects(Model, View and Controller) interact.

• For the text field the model is nothing but the contents of the text field. The model must implement the method to change the contents and to discover the contents. For example text model had methods to add to remove the characters. One important thing to note is that the model is completely non visual.

• For a single model there can be more than one views. Each view can show different aspect of the content. For example: A particular web page can be viewed in its WYSIWYC(What-You-See-Is-What-You-Get)) form or in the raw tagged form. But there are some components like button for which it is not possible to have multiple views for the same model.

• The controller handles the user-input events such as mouse clicks and keyboard strokes. On receiving the events the controller decides whether to translate it into corresponding model or in views.

• If user presses the button then the controller calls the event handling methods in order to handle the button press. The controller tells the view to update itself and to display the desired result. For displaying the desired result the view reads the content from the model. Thus model-view and controller works together in order to accomplish the certain task.

What are the differences between AWT and Swing?

By Dinesh Thakur

Java graphics programming is possible using AWT i.e. Abstract Window Toolkit and swing components. Swing is a set of classes. These classes provide the components that are more powerful and flexible than AWT.

The difference between AWT and Swing is as given below –

 

AWT

Swing

The Abstract Window ToolKit is a heavy weight component because every graphical unit will invoke the native methods.

The Swing is a light weight component because it’s the responsibility of JVM to invoke the native methods

The look and feel of AWT depends upon platform.

As Swing is based on Model View Controller pattern, the look and feel of swing components in independent of hardware and the operating system.

AWT occupies more memory space.

Swing occupies less memory space.

AWT is less powerful than Swing.

Swing is extension to AWT and many drawbacks of AWT are removed in Swing.

 

JPopupMenu in Java Swing Example

By Dinesh Thakur

Using the JPopupMenu class, context-sensitive pop-up menus can be created, which are provided in most of today’s computer applications. These menus are used to provide options specific to the component for which the pop-up trigger event was generated. The pop-up trigger events occur when the right mouse button is either pressed or released. Program demonstrates how such a pop-up menu can be created.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class PopupTest extends JFrame implements MouseListener
{
                 public JRadioButtonMenuItem items[];
                 String fonts[]={"Bold", "Italic", "Bold Italic"};
                 public String displaytext="This is a demonstrating popup menus,"+
                                                     "Please right click the mouse";
                 final JPopupMenu popupMenu;
                 public int index;
                 public PopupTest()
                 {
                         super("PopupMenu Example");
                         popupMenu=new JPopupMenu();
                         ItemHandler handler=new ItemHandler();
                         index=3;
                         ButtonGroup fontsGroup=new ButtonGroup();
                         items=new JRadioButtonMenuItem[3];
                         for(int i=0;i<items.length;i++)
                             {
                                  items[i] =new JRadioButtonMenuItem(fonts[i]);
                                  fontsGroup.add (items[i]);
                                  popupMenu.add(items[i]);
                                  items[i].addActionListener(handler);
                             }
                        getContentPane().setBackground(Color.white);
                        getContentPane().addMouseListener(this);
                        setSize(300,200);
                        show();
                }
                public void mousePressed(MouseEvent e)
                  {
                        checkForTriggerEvent(e);
                  }
                public void mouseReleased(MouseEvent e)
                 {
                        checkForTriggerEvent(e);
                 }
                 public void mouseMoved(MouseEvent e)
                 { }
                 public void mouseClicked(MouseEvent e)
                 { }
                 public void mouseEntered(MouseEvent e)
                 { }
                 public void mouseExited(MouseEvent e)
                 { }
                 private void checkForTriggerEvent(MouseEvent e)
                 {
                     if(popupMenu.isPopupTrigger(e))
                       {
                             popupMenu.show(e.getComponent(),e.getX() ,e.getY());
                       }
                 }
                 public void paint(Graphics g)
                 {
                       super.paint(g);
                       String fontname="Arial";
                       int type=Font.PLAIN;
                       int size=12;
                       Font font;
                       FontMetrics fm;
                       switch(index)
                               {
                                      case 0: type=type|Font.BOLD;
                                                 break;
                                      case 1: type=type|Font.ITALIC;
                                                 break;
                                      case 2: type=type|Font.BOLD|Font.ITALIC;
                                                 break;
                                      default:type=Font.PLAIN;
                                                 break;
                               }
                        font=new Font(fontname,type,size);
                        g.setFont(font);
                        fm=getFontMetrics(font);
                        int xloc=(getSize().width-fm.stringWidth (displaytext))/2;
                        int yloc=(getSize().height-fm.getHeight())/2;
                        g.drawString(displaytext,xloc,yloc);
                  }
                     public static void main(String args[])
                      {
                             PopupTest app=new PopupTest();
                             app.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                      }
                     private class ItemHandler implements ActionListener
                     {
                                  public void actionPerformed(ActionEvent e)
                                  {
                                        for(int i=0;i<items.length;i++)
                                            {
                                                  if(e.getSource() ==items[i])
                                                    {
                                                            index=i;
                                                            repaint();
                                                            return;
                                                    }
                                            }
                                   }
                       }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Before any of the radio button menu items are selected the text is displayed in plain font. If the Bold Italic menu item is selected, then the text displayed will be as follows:

                      JPopupMenu in Java Swing Example

When the user clicks the right mouse button on the Popup Test window, a JPopupMenu of fonts is displayed. If the user clicks one of the menu items that represent a font (that is, JRadioButtonMenultem) then the action Performed method of the class ItemHandler changes the font of the text displayed to the appropriate font. The constructor for the class Pop-up test defines the JPopupMenu.

                        final JPopupMenu popupMenu = new JPopupMenu();

In Program, the class Popup Test extends the class JFrame and implements the interface MouseListener. In this class, there is an inner class which implements the Item Listener interface to listen to the menu button-clicks. The methods mousePressed and mouseReleased are overridden to check for the pop-up-trigger event. Each method calls the private method checkForTriggerEvent to determine if the popup-trigger event occurs. The method isPopup Trigger returns the value true if the pop-up-trigger event has occurred. In that case, the show() method of JPopupMenu is invoked to display the pop-up menu. The first argument of the show() method specifies the origin component, whose position helps us determine where the pop-up menu will appear on the screen. The last two arguments are the x and y coordinates from the origin-component’s upper-left comer at which the pop-up menu should appear.

When a menu item is selected from the pop-up menu, the method actionPerformed() of the private inner class ItemHandler determines which object of JRadioButtonMenultem was selected : by the user and accordingly displays the text appropriate on the window.

Other than the ones listed above, the JPopupMenu class contains methods to set the invoker, label and size of the pop-up menu.

                    Constructors and methods in the jpopupMenu class.

 

Constructors and Methods

Description

JPopupMenu()

Constructs a new JPopupMenu object.

JPopupMenu(String str)

Constructs a new JPopupMenu object with the title specified by the parameter.

JMenultem add(Action action)

Appends a menu item that initiates the specified action to the end of the pop-up menu.

JMenultem add(Menultem menuitem)

Appends the specified menu item to the end of the pop-up menu.

void addPopupMenuListener(Popup MenuListener listener)

Adds a listener of PopupMenu class to the pop-up menu.

void addSeparator()

Adds or appends a new separator to the end of this menu.

Component getComponent()

Returns the name of the component of JPopupMenu.

Component getComponentAtlndex(int index)

Returns the jpopupMenu Component at the specified index.

int getComponentlndex(Component c)

Returns the index of the specified component in the JPopupMenu.

Component getinvoker()

Returns the component that invokes this pop-up menu.

String getLabel()

Returns the po-pup menu’s title.

void insert(Component component, int index)

Inserts or adds the specified component at the specified index for this pop-up menu.

void pack()

Lays out the container such that it uses the minimum space to display its contents.

void remove(Component component)

Removes the specified component from the pop-up menu

void remove(int index)

Remove the component at the specified index from the pop-up menu.

void show(Component component, int x, int y)

Displays the pop-up menu on the window.

The Swing Packages

By Dinesh Thakur

Some of the packages of swing components that are used most are the following:

• Javax.swing

• javax.swing.event

• javax.swing.plaf.basic

• javax.swing.table

• javax.swing.border

• javax.swing.tree

 

The largest of the swing packages, javax.swing, contains most of the user-interface classes (these are J classes, the classes having the prefix J). JTableHeader and JTextComponent are the exceptional classes implemented in the packages javax.swing.table and javax.swing.text, respectively. javax.swing.text contains two sub-packages known as javax.swing.text.html and javax.swing.text.rtf used for HTMLcontent and for Rich Text Format content, respectively.

To define the look and feel of the swing component, the javax.swing.plaf.basic package is used. javax.swing.border contains an interface called Border which is implemented by all the border classes. These classes cannot be instantiated directly. They are instantiated using the factory method (BorderFactory) defined in the javax.swing package. The javax.swing.event package contains all the classes that are used for event handling. The javax.swing.tree package includes classes and interfaces that are specific to the JTree component.

There are totally 16 packages in the swings packages and javax.swing is one of them. A brief description of all the packages in swing is given below.

Packages

Description

javax.swing

Provides a set of “lightweight” (all-Java language) components to the maximum degree possible, work the same on all platforms.

javax.swing.border

Provides classes and interface for drawing specialized borders around a Swing component.

javax.swi ng.colorchooser

Contains classes and interfaces used by the JcolorChooser component.

javax.swing.event

Provides for events fired by Swing components

javax.swing.filechooser

Contains classes and interfaces used by the JfileChooser component.

javax.swing.plaf

Provides one interface and many abstract classes that Swing uses to provide its pluggable look-and-feel capabilities.

javax.swing.plaf.basic

Provides user interface objects built according to the Basic look and feel.

javax.swing.plaf.metal

Provides user interface objects built according to the Java look and feel (once condenamed Metal), which is the default look and feel.

javax.swi ng.plaf.mult

Provides user interface objects that combine two or more look and feels.

javax.swing.table

Provides classes and interfaces for dealing with javax.swing.jtable

javax.swing.text

Provides classes and interfaces that deal with editable and noneditable text components

javax.swing.text.html

Provides the class HTML Editor Kit and supporting classes for creating HTML text editors.

javax.swing.text.html.parser

Provides the default HTML parser, along with support classes.

javax.swing.text.rtf

Provides a class RTF Editor Kit for creating Rich- Text-Format text editors.

javax.swing.tree

Provides classes and interfaces for dealing with javax.swing.jtree

javax.swing.undo

Allows developers to provide support for undo/redo in applications such as text editors.

 

Java Example showOptionDialog

By Dinesh Thakur

A dialog box (“dialog” for short) is any box, or window, on the screen that you have a dialog with. You can decide to pop up some dialog boxes j to enter information in, or make choices about how a program works. “Other dialogs appear automatically to give you simple messages (such as “Your disk is full”) and ask you what you want to do about it.

 

Some people make a distinction between dialog boxes and alert boxes (where the computer warns you about something) or message boxes (where the computer just tells you about something), but that really only matters if you’re a programmer. Everyone will understand what you mean if you call them all dialog boxes.

import java.awt.*; 
import java.awt.event.*;
import javax.swing.*;
public class JavaExampleOptionPane
        {
            public static void main( String aa[] )
                  {
                    Object[] Btns = {"One", "Two", "Three", "Four" };
                     int Rspns =JOptionPane.showOptionDialog( null, "Message", "Option Pane In
Java",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE, null,Btns, "One" );
                     String Typ = "Undefined";
                     if( Rspns == JOptionPane.YES_OPTION ) { Typ = "Yes"; }
                     if( Rspns == JOptionPane.NO_OPTION ) { Typ = "No"; }
                     if( Rspns == JOptionPane.CANCEL_OPTION ) { Typ = "Cancel"; }
                     System.out.println( Typ + ": " + Rspns );
                  }
       }

showOptionDialog Java Example

JColorChooser Panel Java Example

By Dinesh Thakur

[Read more…] about JColorChooser Panel Java Example

JColorChooser Java Example

By Dinesh Thakur

[Read more…] about JColorChooser Java Example

JTabbedPane Java Example

By Dinesh Thakur

Sometimes a situation may arise when there are lots of components that cannot be accommodated in a single screen. In that case, tabbed pane is used to create tabs where each tab contains group of related components. When a particular tab is clicked, the components of that tab are displayed in the forefront. Tabbed pane is very common feature of GUI interfaces. It is commonly used in dialog boxes containing lots of commands. A tabbed pane is an object of JTabbedPane class.

Some of the constructors defined by JTabbedPane class are as follows:

JTabbedPane ()

JTabbedPane(int tabPlacement)

where,

tabPlacement specifies the position of tabs-can have one of the four values: TOP, BOTTOM, LEFT or RIGHT

[Read more…] about JTabbedPane Java Example

showConfirmDialog Java Example

By Dinesh Thakur

A confirmation dialog box is meant for asking a confirmation question and allows the user to give a yes/no/cancel response. It is created by using the static method showConfirmDialog() of JOptionPane. The general form of showConfirmDialog()method is

public static int showConfirmDialog(Component parentComponent,

Object message)

where,

parentComponent is the frame to which the dialog box is attached

message is the message to be displayed

[Read more…] about showConfirmDialog Java Example

JInternalFrame Example in Java Swing

By Dinesh Thakur

An internal frame is similar to a regular frame which can be displayed within another window. It is a lightweight component which can be resized, closed, maximized or minimized depending upon the properties being set. It can also hold a title and a menu bar. An internal frame is an object of JinternalFrame class.

Some of the constructors defined by JinternalFrame class are as follows:

JinternalFrame()

JinternalFrame(String title)

JinternalFrame(String title, boolean resizable)

JinternalFrame(String title, boolean resizable, closable, boolean maximizable, boolean iconifiable)

where,

title specifies the title of the frame

resizable can have one of the two values: true, if the internal frame is resizable; otherwise false (default value)

closable can have one of the two values: true, if the internal frame is closeable, otherwise false (default value)

maximizable can have one of the two values: true, if the internal frame is maximizable, otherwise false (default value)

iconifiable can have one of the two values: true, if the internal frame is minimizable, otherwise false (default value)

The internal frame requires desktop pane which is capable of handling it. The purpose of desktop pane is to hold and manage the working of internal frames. A desktop pane is an object of JDesktopPane class and can be created by using its only constructor JDesktopPane ().

import javax.swing.*; 
public class JInternalFrameJavaExample extends JFrame
{
     public JInternalFrameJavaExample()
    {
       super();
    }
    public static void main(java.lang.String[] args)
    {
        JInternalFrameJavaExample InternalFrame = new JInternalFrameJavaExample();
        InternalFrame.pack();
        InternalFrame.setSize(500, 200);
        JInternalFrame IFrame = new JInternalFrame();
        IFrame.setVisible(true);
        IFrame.setTitle("JInternalFrame Example");
        InternalFrame.getContentPane().add(IFrame);
        InternalFrame.setTitle("JInternalFrame Example in Java Swing");
        InternalFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        InternalFrame.setVisible(true);
    }
}

JInternalFrame Example in Java Swing

Java Clipboard in Swing Example

By Dinesh Thakur

The following example is a simple demonstration of cut, copy, and paste String data type with a JTextArea. One thing you will notice is that the keyboard sequences normally used to cut, copy and paste also work. But if you look at any JTextField or JTextArea in any other program, you will find that these also support keyboard sequences clipboard automatically. this example simply adds programmatic control of the clipboard, and You can use these techniques if you want to capture text from the clipboard into something else than a JTextComponent.

Creating and added menu and JTextArea should by now seem a prosaic activity. What is different is the creation of the field Cboard Clipboard, which is done through Toolkit.

All actions take place in the listeners. The Copy and listeners Cut are the same except for the last line Cut, erasing the line has been copied. The two special lines are creating an object StringSelection the String and the call to setContents () with this StringSelection. All that is there is to put a String to the clipboard.

Paste, the data is removed from the clipboard using getContents (). What comes back is a fairly anonymous Transferable object, and it is uncertain actually it contains. One way to know is to call getTransferFlavors (), which returns an array of DataFlavor objects indicating that flavors are supported by this particular object. It You can also ask directly isDataFlavorSupported () passing the taste in which we are interested. Here, however, a bold strategy is used: getTransferData () is called assuming content supports the flavor of String, and if it does the problem is solved in the exception handler.

import javax.swing.*; 
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
public class ClipboardJavaExample extends JFrame
{
       JMenuBar MenuBar = new JMenuBar();
       JMenu File = new JMenu("File");
       JMenu edit = new JMenu("Edit");
       JMenuItem cut = new JMenuItem("Cut"),
                        copy = new JMenuItem("Copy"),
                        paste = new JMenuItem("Paste");
       JTextArea TextArea = new JTextArea(20, 20);
       Clipboard Cboard = getToolkit().getSystemClipboard();
       public ClipboardJavaExample()
      {
             cut.addActionListener(new Cut());
             copy.addActionListener(new Copy());
             paste.addActionListener(new Paste());
             edit.add(cut);
             edit.add(copy);
             edit.add(paste);
             MenuBar.add(File);
             MenuBar.add(edit);
             setJMenuBar(MenuBar);
             getContentPane().add(TextArea);
       }
       class Copy implements ActionListener
      {
            public void actionPerformed(ActionEvent e)
           {
               String selection = TextArea.getSelectedText();
               if (selection == null)
                  return;
                 StringSelection clipString =new StringSelection(selection);
                 Cboard.setContents(clipString,clipString);
            }
      }
            class Cut implements ActionListener
           {
                      public void actionPerformed(ActionEvent e)
                     {
                            String selection = TextArea.getSelectedText();
                            if (selection == null)
                                 return;
                                 StringSelection clipString = new StringSelection(selection);
                                 Cboard.setContents(clipString, clipString);
                                 TextArea.replaceRange("", TextArea.getSelectionStart(), TextArea.getSelectionEnd());
                      }
            }
           class Paste implements ActionListener
          {
                  public void actionPerformed(ActionEvent e)
                 {
                    Transferable clipData = Cboard.getContents(ClipboardJavaExample.this);
                     try
                    {
                         String clipString = (String)clipData.getTransferData(DataFlavor.stringFlavor);
                         TextArea.replaceRange(clipString,TextArea.getSelectionStart(),TextArea.getSelectionEnd());
                    }   catch(Exception ex)
                              {
                                   System.err.println("Not Working");
                              }
               }
          }
                public static void main(String[] args)
               {
                    JFrame frame = new ClipboardJavaExample();
                    frame.setTitle("Clipboard in Java Swing Example");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setSize(320, 200);
                    frame.setVisible(true);
                   
               }
}

Clipboard in Java Swing Example

Sliders and Progress bars Java Example

By Dinesh Thakur

A slider allows the user to enter a point moving data back and forth, which is intuitive in some situations (volume control, for example). a progress bar displays data in a relative form of “full” to “empty” so the user gets a perspective.

The key to hooking the two components together is to share your model in the line:
ProgressBar.setModel(Slider.getModel());
The JProgressBar is fairly straightforward, but the JSlider has a lot of options, such as orientation and major and minor brands.
Here is the example of Sliders and Progress bars

/* <applet code= Progress.class width=320 height=200> </applet> */ import javax.swing.*; 
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class Progress extends JApplet
{
           JProgressBar ProgressBar = new JProgressBar();
           JSlider Slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 60);
           public void init()
          {
                Frame frm = (Frame)this.getParent().getParent();
                frm.setTitle("Sliders and Progress bars");
                Container container = getContentPane();
                container.setLayout(new GridLayout(2,1));
                container.add(ProgressBar);
                Slider.setValue(0);
                Slider.setPaintTicks(true);
                Slider.setMajorTickSpacing(20);
                Slider.setMinorTickSpacing(5);
                Slider.setBorder(new TitledBorder("Slide Bar (JSlider)"));
                ProgressBar.setModel(Slider.getModel());
                container.add(Slider);
          }
}

Sliders and Progress bars

HTML text on Swing Components Java Example

By Dinesh Thakur

Any component that can take text can also make HTML text , which will be formatted according to HTML rules. this means you can easily add text decorated in a Swing component. [Read more…] about HTML text on Swing Components Java Example

TextListener Java Swing Example

By Dinesh Thakur

The java.awt.event.TextListener interface allows to react to changes the text contained in components of type TextField and TextArea. The addTextListener () method enables a text component to generate user events. the method TextValueChanged () receives events.

Its interface requires that the method be implemented textValueChanged whose associated event, java.awt.event.TextEvent, has a specific method interest listed below:

Method

Description

toString()

Returns the string associated with the event.

 

import java.awt.*; 
import java.awt.event.*;
class JavaExampleTextEvent extends Frame implements TextListener
{
  TextField Txt;
  public JavaExampleTextEvent()
    {
      createAndShowGUI();
    }
      private void createAndShowGUI()
        {
          setTitle("Example of Text Listener");
          setLayout(new FlowLayout());
          Txt=new TextField(20);
          Txt.addTextListener(this);
          add(Txt);
          setSize(400,400);
          setVisible(true);
        }
          public void textValueChanged(TextEvent Evnt)
          {
             setTitle(Txt.getText());
          }
             public static void main(String aa[])
             {
                new JavaExampleTextEvent();
             }
 }

TextListener

JSpinner Java Swing Example

By Dinesh Thakur

JSpinner: Selects a value from a range of possible options to Like the drop-down lists, but show no such list. values changed by pressing the scroll buttons. You can also enter a  value directly.

import java.awt.BorderLayout; 
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class JavaExampleSpinner extends JFrame implements ChangeListener
  {
    JLabel LblQty;
    JLabel LblDt;
    JSpinner Spnr;
    JSpinner DateSpnr;
    JavaExampleSpinner(String Tytl)
     {
       setTitle(Tytl);
       setSize(500,200);
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       Container Cntnr=getContentPane();
       Cntnr.setLayout(new GridLayout(2,1));
       JPanel Pnl=new JPanel();
       Pnl.setLayout(new GridLayout(2,2));
       Pnl.setBorder(BorderFactory.createTitledBorder("Sale Entry"));
       SpinnerNumberModel SpnrNmbrMdl=new SpinnerNumberModel(10,1,100,1);
       Spnr=new JSpinner(SpnrNmbrMdl);
       Spnr.addChangeListener(this);
       Pnl.add(new JLabel("Select Quantity to Be Sold:"));
       Pnl.add(Spnr);
       Date Dt=new Date();
       SpinnerDateModel SpnrDtMdl=new SpinnerDateModel(Dt,null,null,Calendar.DATE);
       DateSpnr=new JSpinner(SpnrDtMdl);
       DateSpnr.setEditor(new JSpinner.DateEditor(DateSpnr,"dd:MM:yyyy"));
       DateSpnr.addChangeListener(this);
       Pnl.add(new JLabel("Select Sale Date:"));
       Pnl.add(DateSpnr);
       Cntnr.add(Pnl,BorderLayout.CENTER);
       JPanel Panl=new JPanel();
       Panl.setLayout(new FlowLayout());
       LblQty=new JLabel();
       LblQty.setForeground(Color.GREEN);
       LblDt=new JLabel();
       LblDt.setForeground(Color.RED);
       Panl.add(LblQty);
       Panl.add(LblDt);
       Panl.setBorder(BorderFactory.createTitledBorder("Information"));
       Cntnr.add(Panl); 
       setVisible(true);
     }
       public void stateChanged(ChangeEvent ee)
        {
           JSpinner JSpnr=(JSpinner)ee.getSource();
           try
            {
               JSpnr.commitEdit();
            }
              catch(ParseException PrsEx){}
              if(JSpnr==Spnr)
              LblQty.setText("Quantity:"+JSpnr.getValue().toString());
              else if(JSpnr==DateSpnr)
              LblDt.setText("Date:"+JSpnr.getValue().toString());
        }
              public static void main(String[] aa)
            {
                   new JavaExampleSpinner("Example Date Spinner In Java");
                }
 }

JSpinner

JSlider in Java Example

By Dinesh Thakur

Slider in Swing is similar to scroll bar which allows the user to select a numeric value from a specified range of integer values. It has a knob which can slide on a range of values and can be used to select a particular value. For example, sliders are used in media players, to adjust volume, to set channel frequency, etc. Like scroll bars, they can also be horizontal or vertical. A slider is an object of class JSlider which is direct subclass of JComponent. The class JSlider also implements the interface SwingConstants.

      Constructors and methods of the JSlider class

 

Constructors and Methods

Description

JSlider()

Constructs a horizontal slider with the range 0 to 100with the initial value set to 50.

JSlider(BoundedRangeModelbrm)

Constructs a horizontal slider with the specified bounded range model.

JSlider(int orientation)

Constructs a slider with the range 0 to 100. and the initial value is set to 50, with the specified orientation.

JSlider(int min, int max)

Constructs a horizontal slider having the range whose minimum value is specified by the first parameter and maximum value is specified by the second parameter, and

the initial value is set to 50.

JSlider(int min, int max, int value)

Constructs a horizontal slider having the range whose minimum value is specified by the first parameter, maximum value specified by the second parameter and whose initial value is set according to the last parameter.

JSlider(int orientation, int min, int max, int value)

Constructs a slider with the specified orientation having the range whose minimum and maximum values are specified by the second and third parameters, and the initial value is set accordingly depending on last parameter.

Void addChangeListener(ChangeListener I)

Adds a change listener to this slider.

int getMaximum()

Returns the maximum value the slider supports.

int getMinimum()

Returns the minimum value the slider supports.

int getOrientation()

Returns the slider’s horizontal or vertical orientation.

int getValue()

Returns the slider’s current value.

Void setValue(int value)

Sets the slider’s current value to the value specified by the parameter.

 

The creation and display of the JSlider control is explained in Program.

import javax.swing.*; 
import javax.swing.event.*;
import java.awt.*;
public class JavaExampleDynamicIcon
  {
    public static void main(String[] as)
      {
          final JSlider Wdth = new JSlider(JSlider.HORIZONTAL, 1, 150, 75);
          final JSlider Hght = new JSlider(JSlider.VERTICAL, 1, 150, 75);
          class DynamicIcon implements Icon
            {
                public int getIconWidth()
              {
                  return Wdth.getValue();
              }
                     public int getIconHeight()
                   {
                       return Hght.getValue();
                   }
                          public void paintIcon(Component Cmpnt, Graphics gr, int a, int b)
                       {
                              gr.fill3DRect(a, b, getIconWidth(), getIconHeight(), true);
                           }
            };
                  Icon Icn = new DynamicIcon();
                 final JLabel LblDynmc = new JLabel(Icn);
                 class Updater implements ChangeListener
                {
                        public void stateChanged(ChangeEvent Evnt)
                      {
                              LblDynmc.repaint();
                          }
                    };
                             Updater Updtr = new Updater();
                             Wdth.addChangeListener(Updtr);
                             Hght.addChangeListener(Updtr);
                             JFrame Frm = new JFrame();
                             Container Cntnr = Frm.getContentPane();
                             Cntnr.setLayout(new BorderLayout());
                             Cntnr.add(Wdth, BorderLayout.NORTH);
                             Cntnr.add(Hght, BorderLayout.WEST);
                             Cntnr.add(LblDynmc, BorderLayout.CENTER);
                             Frm.setSize(210,210);
                             Frm.setVisible(true);
        }
  }

JSlider

KeyEvent Java Example

By Dinesh Thakur

The java.awt.event.KeyListener interface, present in virtually all AWT component is used to respond to events triggered by  keystrokes when the focus is on the component. Allows the preprocessing  the input provided by the user and other sophisticated actions. its  interface requires the keyPressed, keyReleased method are implemented and  keyTyped. The associated event, java.awt.event.KeyEvent has the following methods  of particular interest are listed below:

 

Method

Description

getKeyChar()

Returns the characterassociated with thekeythat originated theevent.

getKeyCode()

Returns thekey codeassociated withthatkeyoriginated the event.

getKeyModifiersText(int)

Returnsa string describingthe modifier keys“Shift”, “Ctrl” ortheir combination.

getKeyText(int)

Returnsa string describingthe keyas“Home“, “F1″ or “A”.

isActionKey()

Determines whetheror notthe associated keyis akeyaction.

setKeyChar(char)

Replaces the characterassociated with thekeythat originated theevent.

 

import javax.swing.*; 
import java.awt.*;
import java.awt.event.*;
public class JavaExampleKeyEvent extends JFrame implements KeyListener
  {
    private JLabel LblPrmpt = new JLabel("Press keys as Desired Below:");
    private JLabel LblOutPt = new JLabel("Key Typed is:");
    private JTextField Txt = new JTextField(10);
    public JavaExampleKeyEvent()
     {
       setTitle("Java Example of Key Event");
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       setLayout(new BorderLayout());
       add(LblPrmpt,BorderLayout.NORTH);
       add(Txt, BorderLayout.CENTER);
       add(LblOutPt,BorderLayout.SOUTH);
       addKeyListener(this);
       Txt.addKeyListener(this);
     }
       public void keyTyped(KeyEvent Evnt)
        {
          char s = Evnt.getKeyChar();
          LblOutPt.setText("Last key Pressed:" + s);
        }
          public void keyPressed(KeyEvent Evnt)
           {
           }
             public void keyReleased(KeyEvent Evnt)
             {
             }
               public static void main(String[] ar)
                {
                  JavaExampleKeyEvent Frm = new JavaExampleKeyEvent();
                  final int WIDTH = 250;
                  final int HEIGHT = 100;
                  Frm.setSize(300,300);
                  Frm.setVisible(true);
                }
  }

KeyEvent

ItemListener Java Example

By Dinesh Thakur

The java.awt.event.ItemListener interface is responsible for processing events  java.awt.event.ItemEvent action generated by the activation of checkboxes (Checkbox), option buttons (CheckboxGroup) and items in menus option type  (CheckboxMenuItem). Its implementation requires the inclusion of the method  itemStateChanged these classes.

Method

Description

getItem()

Returns the itemthat triggered theevent.

getStateChange()

Returns thetype ofstate changeoccurred.

import java.awt.*; 
import javax.swing.*;
import java.awt.event.*;
public class JavaExampleCheckBox extends JFrame implements ItemListener
{
    FlowLayout Flw = new FlowLayout();
    JLabel LblChc = new JLabel("What would you like to Choose?");
    JCheckBox Cappuccino = new JCheckBox("Coffee", false);
    JCheckBox SoftDrink = new JCheckBox("Pepsi", false);
    JCheckBox Mlk = new JCheckBox("Milk", false);
    JCheckBox Wtr = new JCheckBox("Water", false);
    String Outpt,InsChsn;
    public JavaExampleCheckBox()
     {
       super("Java Example Of Check Box Function");
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       setLayout(new FlowLayout());
       LblChc.setFont(new Font("Times New Roman", Font.ITALIC, 22));
       Cappuccino.addItemListener(this);
       SoftDrink.addItemListener(this);
       Mlk.addItemListener(this);
       Wtr.addItemListener(this);
       add(LblChc);
       add(Cappuccino);
       add(SoftDrink);
       add(Mlk);
       add(Wtr);
     }
           public void itemStateChanged(ItemEvent Chk){}
            public static void main(String[] aa)
            {
              final int FRAME_WIDTH = 330;
              final int FRAME_HEIGHT = 110;
              JavaExampleCheckBox Frm =new JavaExampleCheckBox();
              Frm.setSize(FRAME_WIDTH, FRAME_HEIGHT);
              Frm.setVisible(true);
            }
}

ItemListener

java.awt.event.ActionListener Java Example

By Dinesh Thakur

The java.awt.event.ActionListener interface is responsible for processing events java.awt.event.ActionEvent action generated by the drive buttons (Button), selection items (MenuItem) in suspended (drop-down) or independent menus (popup) at Pressing the “Enter” in inboxes (TextField) and double-click boxes list (List). Its implementation requires the inclusion of the actionPerformed method in these classes.

As a complement, the ActionEvent event has the following specific methods associated with:

 

Method

Description

getActionCommand()

Returns the string associated with this component

getModifiers()

Obtain the modifiers used in the instant the generation of this event.

 

import javax.swing.*; 
import java.awt.*;
import java.awt.event.*;
public class JavaExampleHello2JApplet extends JApplet implements ActionListener
 {
   JLabel LblGrtng = new JLabel("Hi Welcome...!Who are you?");
   Font FntOne = new Font("Times New Roman", Font.BOLD, 36);
   Font FntTwo = new Font("Times New Roman", Font.ITALIC, 48);
   JTextField TxtAns = new JTextField(10);
   JButton BtnClck = new JButton("Click Here");
   JLabel LblPrsnlGrtng = new JLabel(" ");
   Container Cntnr = getContentPane();
   public void init()
    {
      LblGrtng.setFont(FntOne);
      LblPrsnlGrtng.setFont(FntTwo);
      Cntnr.add(LblGrtng);
      Cntnr.add(TxtAns);
      Cntnr.add(BtnClck);
      Cntnr.setLayout(new FlowLayout());
      Cntnr.setBackground(Color.CYAN);
      BtnClck.addActionListener(this);
      TxtAns.addActionListener(this);
    }
      public void actionPerformed(ActionEvent ee)
      {
        String Nme = TxtAns.getText();
        Cntnr.remove(LblGrtng);
        Cntnr.remove(BtnClck);
        Cntnr.remove(TxtAns);
        LblPrsnlGrtng.setText("Hello, " + Nme + "! ");
        Cntnr.add(LblPrsnlGrtng);
        Cntnr.setBackground(Color.WHITE);
        validate();
      }
}
/*<applet code= JavaExampleHello2JApplet.class Height=300 width=240></applet>*/

java.awt.event.ActionListener

JoptionPane Java Example

By Dinesh Thakur

JOptionPane is a subclass of JComponent which includes static methods for creating and customizing modal dialog boxes using a simple code. Previously, you have seen that creating a dialog box using JDialog makes the code cumbersome. So JOptionPane is used instead of JDialog to minimize the complexity of the code. JOptionPane displays the dialog boxes with one of the four standard icons (question, information, warning, and error) or the custom icons specified by the user.

Some of the constructors defined by the JOptionPane class are as follows.

JOptionPane ()

JOptionPane(Object message)

JOptionPane(Object message, int messageType)

JOptionPane(Object message, int messageType, int optionType)

JOPtionPane (Object message, int messageType, int optionType, Icon icon)

JOPtionPane (Object message, int messageType, int optionType, Icon icon, Object[] options)

JOPtionPane (Object message, int messageType, int optionType, Icon icon, Object[] options, Object initialValue)

where,

message is the message to be displayed in the dialog box

messageType specifies the type of the message to be displayed. It has various values which are represented as: ERROR_MESSAGE, INFORMATION_MESSAGE,WARNING_MESSAGE, QUESTION_MESSAGE or PLAIN_MESSAGE

optionType is used to specify the options. It can have various values which are represented as: DEFAULT_OPTION, YES_NO_OPTION, YES_NO_CANCEL_OPTION or OK_CANCEL_OPTION icon specifies the icon to be displayed

options is an array of options to be displayed in the dialog box with none of them selected

initialValue specifies the default option selected from the list provided in options

JOptionPane class is used to display four types of dialog boxes namely, 

● MessageDialog – dialog box that displays a message making it possible to add icons to alert the user.
● ConfirmDialog – dialog box that besides sending a message, enables the user to answer a question.
● InputDialog – dialog box that besides sending a message, allows entry of a text.
● OptionDialog – dialog box that covers the three previous types.

import javax.swing.JOptionPane; 
public class JavaExampleOptionPaneSalaryDialog
  {
    public static void main(String[] aa)
     {
       String StrngWg, StrngDpndnt;
       double Salary,WklyPay;
       int Dpndnts;
       final double HOURS_IN_WEEK = 37.5;
       StrngWg = JOptionPane.showInputDialog(null,"Enter Worker's Hourly Wage", "First Salary Dialog",JOptionPane.INFORMATION_MESSAGE);
       WklyPay = Double.parseDouble(StrngWg) *HOURS_IN_WEEK;StrngDpndnt = JOptionPane.showInputDialog(null,"How many Dependents?", "Second Salary Dialog
",JOptionPane.QUESTION_MESSAGE);
       Dpndnts = Integer.parseInt(StrngDpndnt);
       JOptionPane.showMessageDialog(null,"Weekly Pay is $" +WklyPay+ "\nDeductions will be made for :" +Dpndnts+ "Dependents");
     }
  }

JoptionPane

showOptionDialog Java Example

By Dinesh Thakur

The option dialog box provides the feature of all the above three discussed dialog boxes. It is created by using the static method showOptionDialog () of JOptionPane. The general form of showOptionDialog () method is

public static int showOptionDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon, Object[] options, Object initialValue))

where,

parentComponent is the frame in which the dialog box is displayed

message is the message to be displayed

title is a string of text to be displayed in the title bar of the dialog box

optionType specifies options available on the dialog box such as YES_NO_OPTION or YES_NO_CANCEL_OPTION

messageType specifies the type of message such as error message, information message, warning message, question message or plain message

icon specifies the icon on the dialog box

options allows the user to use components other than buttons

initialValue determines the initial choice

import java.util.*; 
import javax.swing.*;
public class JavaExampleAgeCalculator
  {
    public static void main(String[] as)
     {      
               GregorianCalendar Current = new GregorianCalendar();
       int CrntYear;
       int YearofBrth;
       int YrsOld;
       YearofBrth = Integer.parseInt(JOptionPane.showInputDialog(null,"In Which year You Were born?"));
       CrntYear = Current.get(GregorianCalendar.YEAR);
       YrsOld = CrntYear - YearofBrth;JOptionPane.showMessageDialog(null,"At Present year you become " + YrsOld +" Years Old");
     }
  }

showOptionDialog

JViewport in Java Swing Example

By Dinesh Thakur

[Read more…] about JViewport in Java Swing Example

JTree Events Example in Java

By Dinesh Thakur

Using a JTree is as simple as saying:

add(new JTree( new Object[] {“One”, “Two”, “Three”}));
This displays a primitive tree. The API is huge tree without But, certainly one of the longest of Swing. It seems that you can do everything with trees, but the most sophisticated tasks may require quite a bit of research and experimentation.

import java.awt.*; 
import javax.swing.*;
import java.awt.event.*;
import javax.swing.tree.*;
public class JavaExampleTreeEventInJApplet extends JApplet
  {
    public void init()
     {
        JTree Tree = new JTree();
        getContentPane().add(new JScrollPane(Tree));
        Tree.addMouseListener(new MouseAdapter()
           {
               public void mousePressed(MouseEvent e1)
                  {
                     String OutStrng = null;
                     JTree Tree=(JTree)e1.getSource();
                     int ClckdRow = Tree.getRowForLocation(e1.getX(), e1.getY());
                     if(ClckdRow != -1)
                    {
                            TreePath TreePth = Tree.getPathForRow(ClckdRow);
                            TreeNode TreeNd = (TreeNode)TreePth.getLastPathComponent();
                            OutStrng = "Node " + TreeNd.toString();
                             if(e1.getClickCount() == 1)
                               {
                                   OutStrng += "Clicked Single.";
                               }
                          else
                             {
                                         OutStrng += "Clicked Double.";
                                     }
                                         showStatus(OutStrng);
                         }
                   }
           });
        }
 }
/*<APPLET CODE =JavaExampleTreeEventInJApplet.class WIDTH = 35  HEIGHT = 280 ></APPLET>*/

JTree Events Example in Java

Next Page »

Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW