Swing And Its Operations In Java

SWING :

INTRODUCTION TO JFC (JAVA FOUNDATION CLASSES)

The earlier versions of java were released with some simple libraries. JDK1.2 was introduced with a new set of packages – the java foundation classes, or JFC – that includes an improved user interface called the swing components.

The JFC were developed, to address the shortcomings of AWT(Abstract Windowing Toolkit). The development of JFC was unique. JFC 1.2 is an extension of the AWT, not a replacement for it. The JFC visual components extend the AWT container class. The methods contained in the component and container classes that AWT programmers are familiar with are still valid for JFC visual classes.

The AWT user interface classes are now superseded by classes provided by the JFC. The support classes play an important role in JFC applications. AWT support classes , those that do not create a native window are not replaced by JFC classes.

SWING :

Swing components facilitate efficient graphical user interface (GUI) development. These components are a collection of lightweight visual components. Swing components contain a replacement for the heavyweight AWT components as well as complex user-interface components such as trees and tables.

Swing components contain a pluggable look and feel(PL&F). This allows all applications to run with the native look and feel on different platforms. PL&F allows applications to have the same behavior on various platforms. JFC contains operating systems neutral look and feel. Swing components do not contain peers. Swing components allow mixing AWT heavyweight and swing lightweight components in an application. The major difference between lightweight and heavyweight components is that lightweight components can have transparent pixels while heavyweight components are always opaque. Lightweight components can be non-regular while heavyweight components are always rectangular.

Swing components are JavaBean compliant. This allows components to be used easily in a Bean aware applications building program. The root of the majority of the swing hierarchy is the Jcomponent class. The class is an extension of the AWT container class.

Swing AWT
Swing component does not need any native code to implement. AWT component can be implementing with code.
Swing lets you specify which look and feel your programs GUI uses. AWT components always have the look and feel of the native platform.
Swing components don’t have to be rectangular. For ex. Buttons can be rounded. AWT components are always rectangular.

The swing architecture is shown in the figure given below.

swing architecture

Swing components comprises of a large percentage of the JFC release. The swing component toolkit consists of over 250 pure java classes and 75 interfaces contained in about 10 packages. They are used to build lightweight user interface. Swing consists of user interface(UI) classes and non user interface classes. The non-UI classes provide services and other operations for the UI classes.

Swing packages :

Some of the Swing packages are given below.

  • Javax.swing.plaf.basic : Contains classes that define the default look and feel of swing components.
  • Javax.swing.border : Contains border interface and their related interfaces.
  • Javax.swing. event : Define events specific to swing components.
  • Javax.swing.plaf.multi : Consist of multiplexing UI classes
  • Javax.swing.plaf : Consist of classes that provide swing components with pluggable look and feel capabilities.
  • Javax.swing.table : Contains classes and interfaces specific to the swing table components
  • Javax.swing.text : Contains classes and interfaces for text manipulation components contained in swing toolkit.
  • Javax.swing.tree : Contains classes that are used with the swing tree component
  • Javax.swing.undo : contains interfaces and classes required to implement the undo functionality.

SWING FEATURES :

  • MVC Architecture : The user can provide his own datamodel for a component by subclassing the Model class or by implementing the appropriate interface. The Model-View- Controller (MVC) architecture is used consistently throughout the swing component set. The view and controller parts of the architecture are combined in the component.
  • Nested Containers : Swing was designed to manage nested containers gracefully. The main heavyweight containers(JWindow, JFrame etc.) as well as the major ‘lightweight’ containers(JInternalFrame and JComponent) all delegate their operations to a JRootPane. This commonly produces high degree of regularity in container nesting. In particular since the fundamental component class(JComponent) contains a JRootPane, virtually any component can be nested within another.
  • Keystroke Handling : A user can register interest in a particular combination of keystrokes by creating a keystroke object and registering it with the component. When the keystroke combination is registered along with its association action, certain conditions have to be specified. These determine the time of initiation of the action.
  • Action Objects : action interface objects provide a single point of control for program actions. An example of this would be a toolbar icon and a menu item referencing thesame Action objects. When action object disabled, the GUI items that reference it are automatically disabled.
  • Virtual Desktops : The JdesktopPane and JInternalFrame classes can be used to create a virtual desktop or multiple document interface. A JInternalFrame can be specified as cognizable, expandable or closable, while the JDesktopPane Provides real estate for them to operate in.
  • Pluggable look and feel : The user can select a look and feel and this can be plugged in. An interface made of Swing components can look like a Win32 app, a Motif app. It can use the new Metal look and feel.
  • Wide variety of components : Class names that starts with J are the components that are added to and application. Forex. JButton, JList, JPanel.

J COMPONENT :

The JComponent class is the root of the visual component class hierarchy in the JFC. The visual components are known as the “J” classes. The functionality contained in the JComponent class is available to all the visual components contained in the JFC. The JComponent class is repository of functionality for all visual components.

The JComponent class is at the top of the hierarchy of all visual components contained in the JFC. The hierarchy is shown in the following figure.

JComponent

JAPPLET :

The JApplet class is an extended version of the AWT applet class that adds support for root panes and other panes.. This class is the preferred entry point when creating applets that contain JFC components. The components are added to the ContentPane.

The constructor that can be used to create a JApplet are listed below :

  • JApplet() : It creates a swing applet instance

Some of the methods that can be used in conjunction with the JApplet is given below :

  • createRootPane( ) : Called by the constructor methods to create the default root pane.
  • getContentPane( ) : Returns the content pane object for the applet
  • getGlassPane( ) : Returns the glass pane object for the applet
  • getJMenuBar( ) : Returns the menu bar set on the applet
  • setContentPane( ) : sets the content pane properly
  • setGlassPane( ) : sets the glass pane properly
  • setLayout(LayoutManagermanager) : By default the layout of this component may not be set, the layout of its contentPane should be set instead.

J FRAME :

Frame windows : A frame is a top-level window that contains a title, border, minimize and maximize buttons. JFC provides the JFrame class. This is used as a top-level-frame.

JFrame : A Swing frame is represented by the class Jframe, is an extension of the AWT Frame classes. It is the part of javax.swing package. A Swing frame is a container that functions as the main window for programs that use Swing components. An instance of the JFrame Class is a heavyweight component.

The JFrame can be created using the constructors mentioned below :

  • JFrame() : Constructs a new frame that is initially invisible.
  • JFrame(String title) : Constructs a new frame, initially invisible with the specified title.

Some of the methods that may be used in conjunction with the JFrame() are listed below :

  • createRootPane() : Called by the constructor methods to create the default root pane
  • frameInit() : Called by the constructor to init the JFrame properly.
  • getContentPane() : Returns the content pane object for this frame
  • getGlassPane() : Returns the glass pane object for this frame
  • getJMenuBar() : Returns the menu bar set on this frame
  • getLayeredPane() : Returns the layered pane for this frame
  • setContentPane() : Sets the content pane property
  • setGlassPane() : Sets the glass pane property
  • setJMenuBar() : Sets the menu bar for the frame
  • setLayout(LayoutManager manager) : By default the layout of this component may not be set, the layout of its contentPane should be set instead.

J PANNEL :

JPanel is a Swing lightweight container that is often used for grouping components within one of an applet or a frame. It can also be used to group other panels. The primary purpose of the class is to provide a concrete container for the JFC. The JPanel class is provided to gibve a concrete container class. Being an extennsion of the Jcpmponent class, JPanel is a container and inherits the features contained in that class.

The various constructros that can be used to create a JPanel are as given below.

  • JPanel() : Create a new JPanel with a double buffer and a flow layout.
  • JPanel(Boolean is DoubleBuffered) : Create a new JPanel with FlowLayout and the specified buffering stratergy.
  • JPanel (LayoutManager layout) : create a buffered JPanel with the specified layout manager.
  • JPanel(LayoutManager layout, boolean is DoubleBuffered) : Creates a new JPanel with the specified layout manager and buffering stratergy.

The methods supported by this class includes :

  • getAccessibleContext() : Gets the AccessibleContext associated with this JComponent.
  • getUIClassID() : Returns a string that specifies the name of the L&F clss tht renders theis component.
  • paramString() : Returns a string representation of the corresponding JPanel.
  • update() : Notification fro the UIFactory that the L&F has changed.

JBUTTONS :

JButton : JButtons behaves In a way that is similar to Button. It can be added to JPanel and its actions can be monitored via the ActionListener. The JButton has to be pushed to make something happen. It consist of label and /or an icon that describes its function, an empty area around the text/icon and a border. By default, the border is a special border that reflects the status of the button.

A JButton can be constructed by any of the constructors mentioned below:

  • JButtons() : Creates a button with no text or icon
  • JButton(Icon icon) : Creates a button with icon.
  • JButton(String text) : Creates a button with text
  • JButton(String text, Icon icon) : Creates a button with text and icon

Some methods can be used in conjuctoin with a JButton are listed below:Creating our own UI for JButton

  • isDefaultButton() : Returns whether or not the corresponding button is the default button on the RootPane.
  • isDefaultCapable() : Returns whether or not the corresponding button is capable of being the default button on the RootPane.
  • setDefaultCapable(booleandefaultCapable) : Sets whether or not the corresponding button is capable of being the default button on the RootPane.

Right-clicks on a Button :

The default action of a JButton is to receive a left mouse click. The button could be programmed to receive a right mouse click also. There are ways in which this can be achived.

  • Creating our own UI for JButton
  • Overlay the button with an invisible component that would intercept all events and pass through all except right clicks.
  • Subclass JButton and override the process MouseEvent() method

CHECK BOXES (JCheckBox) :

JCheckBox : A JCheckBox is a control that may be turned on and off by the user to designate some kind of property being selected or not selected. It consist of a background rectangle, and a text string and/or icon. The JCheckBox normally shows its current state visually. This is done by placing a check mark in a box, or by changing the icon.

A JCheckbox generates item events when its state changes. The checkbox can be created by using any one of the constructors mentioned below:

  • JCheckBox() : Creates an initially unchecked checkbox with no text or icon.
  • JCheckBox(Icon icon) : Creates an initially unchecked checkbox with an icon.
  • JCheckBox(Icon icon, Boolean selected) : Creates a checkbox with an icon and specifies whether or not it is initially selected
  • JCheckBox(String text) : Creates an initially unchecked checkbox with the specified text.
  • JCheckBox(String text, Boolean selected) : Creates a checkbox with the specified text and specifies whether or not it is initially selected.
  • JCheckBox(String text, Icon icon) : Creates an initially unselected checkbox with the text and icon specified.
  • JCheckBox(String text, Icon icon, Boolean selected) : Creates a checkbox with icon and text and specifies whether or not it is initially selected.

RADIOBUTTONS (JRadioButtons) :

JRadioButtons : This is normally used as one of a group of radio buttons of which only one may be selected at a time. These are grouped using a ButtonGroup and are usually used to select from a set of mutually exclusive options. It consists of a background rectangle and text and/or an icon. If it includes an icon, the icon is used to visually reflect the current state of the radio button.

Using the constructors listed below , radio buttons can be created:

  • JRadioButton() : Creates an initially unselected radio button with no set text.
  • JRadioButton(Icon icon) : Creates an initially unselected radio button with the specified image but no text.
  • JRadioButton(Icon icon, Boolean selected) : Creates a radio button with the specified image and selection state, but no text.
  • JRadioButton(String text) : Creates an initially unselected radio button with the specified text.
  • JRadioButton(String text, boolean selected) : Creates a radio button with specified text and selection state.
  • JRadioButton(String text, Icon icon) : Creates a radio button that has the specified text and image, and that is initially unselected.
  • JRadioButton(String text, Icon icon, boolean selected) : Creates a radio button that has the specified text, image, and selection state.

//Programs : Followig is the programm to display an Applet. import java.awt.event.*; import java.awt.*; import javax.swing.*; /* */ public class Applets extends JApplet { JButton B1; public void init() { JPanel contentpane = (JPanel)getContentPane(); B1= new JButton("My First Applet"); contentpane.add(B1); } }

  • Save the file as Applets.Java
  • Compile the file using javac Applet.java
  • On successful compilation, execute the file using appletviewer Applets.java

The output appers as shown in following figure :

applet using swing in java

The following program is an example of Jframe/JButton

CODE/PROGRAM/EXAMPLE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Button1 extends JFrame implements ActionListener
{
JButton mtextbtn1;
JButton mtextbtn2;
public Button1()
{
setTitle("Button Example");
JPanel contentpane = (JPanel)getContentPane();
contentpane.setLayout(new GridLayout(2,2));
mtextbtn1= new JButton("Enabled");
mtextbtn1.setMnemonic("E");
mtextbtn1.addActionListener(this);
contentpane.add(mtextbtn1);
mtextbtn2 = new JButton("Disabled");
mtextbtn2.setMnemonic("D");
mtextbtn2.addActionListener(this);
contentpane.add(mtextbtn2);
mtextbtn1.setEnabled(true);
myadapter myapp = new myadapter();
addWindowListener(myapp);
}
class myadapter extends WindowAdapter
{
public void windowclosing(WindowEvent e)
{
System.exit(0);
}
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == mtextbtn1)
{
setTitle("First button clicked");
}
else if ( e.getSource() == mtextbtn2)
{
setTitle("Second button clicked");
}
}
public static void main(String args[])
{
Button1 b = new Button1();
b.setSize(100,100);
b.setVisible(true);
}
}
  • Save the file as Button1.java
  • Compile the program using javac Button1.java
  • Execute the program using java Button1

The output appears as shown in following figure.

 button enable - disable in swing

Example program for JCheckBoxes/JFrame.

CODE/PROGRAM/EXAMPLE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class checkbox1 extends JFrame implements ItemListener
{
JCheckBox checkbox;
public checkbox1()
{
setTitle("Check box Example");
JPanel contentpane = (JPanel)getContentPane();
contentpane.setLayout(new GridLayout(2,2));
checkbox = new JCheckBox("Toggle");
checkbox.addItemListener(this);
contentpane.add(checkbox);
myadapter myapp = new myadapter();
addWindowListener(myapp);
}
class myadapter extends WindowAdapter
{
public void windowclosing(WindowEvent e)
{
System.exit(0);
}
}
public void itemStateChanged(ItemEvent e)
{
if (e.getStateChange() == ItemEvent.SELECTED)
{
setTitle("Checkbox selected");
}
else
{
setTitle("Checkbox unselected");
}
}
public static void main(String args[])
{
checkbox1 c = new checkbox1();
c.setSize(250,250);
c.setVisible(true);
}
}
  • Save the file as checkbox1.java
  • Compile the file using javac checkbox1.java
  • Execute the file using java checkbox

The output appears as shown in the follwing figure;

checkbox in java using swing

Example program for JRadioButtons

CODE/PROGRAM/EXAMPLE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Radiobuttons extends JFrame implements ItemListener
{
JRadioButton rb1, rb2;
ButtonGroup grp = new ButtonGroup();
public Radiobuttons()
{
setTitle("Radio Buttons Example");
JPanel contentpane = (JPanel)getContentPane();
contentpane.setLayout(new FlowLayout());
rb1 = new JRadioButton("Enabled");
rb1.addItemListener(this);
rb1.setEnabled(true);
contentpane.add(rb1);
rb2 = new JRadioButton("Disabled");
rb2.addItemListener(this); //rb2.setActionCommand("Two
Activated");
contentpane.add(rb2);
rb2.setEnabled(false);
grp.add(rb1);
grp.add(rb2);
myadapter myapp = new myadapter();
addWindowListener(myapp);
}
class myadapter extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
public void itemStateChanged(ItemEvent e)
{
if (e.getSource()==rb1)
{
setTitle("First radio button enabled");
rb1.setEnabled(false);
rb2.setEnabled(true);
}
else if(e.getSource()==rb2)
{
setTitle("Second radio button enabled");
rb1.setEnabled(true);
rb2.setEnabled(false);
}
}
public static void main(String args[])
{
Radiobuttons rb = new Radiobuttons();
rb.setSize(300,300);
rb.setVisible(true);
}
}
  • Save the file as Radiobuttons.java
  • Compile the file using javac Radiobuttons.java
  • On successful compilation execute the file using java Radiobuttons

The output appears as shown in the following figure :

Radiobuttons in java using swing
#swing_in_java #swing_in_java_programming #introduction_to_jfc #Swing_packages_in_java #swing_features #j_components #japplet_in_java #j_frame_in_java #j_panel #jbuttons_in_java #JCheckBox_using_swing #JRadioButtons_using_swing #JCheckBoxes_using_swing #JRadioButtons _using_swing

(New page will open, for Comment)

Not yet commented...