Swing Controls in Java

Swing Controls in Java with Examples

In this article, I am going to discuss Swing Controls in Java with Examples. Please read our previous article, where we discussed Swings in Java. At the end of this article, you will understand the following swing controls in Java in detail with examples.

  1. JLabel
  2. JRadioButton
  3. ButtonGroup
  4. JCheckBox
  5. JTextField
  6. JTextArea
  7. JButton
  8. Border
  9. JComboBox
  10. JTabbedPane
  11. JPasswordField
  12. Look and Feel Management in Java Swing
JLabel

The object of the JLabel class may be a component for putting text during a container. It’s used to display one line of read-only text. The text is often changed by an application but a user cannot edit it directly. It inherits the JComponent class.

Declaration: public class JLabel extends JComponent implements SwingConstants, Accessible

Syntax: JLabel jl = new JLabel();

JLabel Constructors
  1. JLabel(): It is used to create a JLabel instance with no image and with an empty string for the title.
  2. JLabel(String s): It is used to create a JLabel instance with the specified text.
  3. JLabel(Icon i): It is used to create a JLabel instance with the specified image.
  4. JLabel(String s, Icon I, int horizontalAlignment): It is used to create a JLabel instance with the specified text, image, and horizontal alignment.
Sample Program to understand JLabel Swing Control in Java:
import javax.swing.*;
import java.awt.*;

public class JLabelDemo extends JFrame
{
    JLabel jl;
    JLabelDemo ()
    {
        jl = new JLabel ("Good Morning");
        Container c = this.getContentPane ();
        c.setLayout (new FlowLayout ());
        c.setBackground (Color.blue);
        Font f = new Font ("arial", Font.BOLD, 34);
        jl.setFont (f);
        jl.setBackground (Color.white);
        c.add (jl);
        this.setVisible (true);
        this.setSize (400, 400);
        this.setTitle ("Label");
        this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    }

    public static void main (String[]args)
    {
        new JLabelDemo ();
    }
}

Output

Program to understand JLabel Swing Control in Java

JRadioButton

This component allows the user to select only one item from a group item. By using the JRadioButton component you can choose one option from multiple options.

Declaration: public class JRadioButton extends JToggleButton implements Accessible

Syntax: JRadioButton jrb = new JRadioButton();

JRadioButton Constructors
  1. JRadioButton(): It is used to create an unselected radio button with no text.
  2. JRadioButton(Label): It is used to create an unselected radio button with specified text.
  3. JRadioButton(Label, boolean): It is used to create a radio button with the specified text and selected status.
ButtonGroup

This class is used to place multiple RadioButton into a single group. So the user can select only one value from that group. We can add RadioButtons to the ButtonGroup by using the add method.

Example : add(jrb);

Syntax : ButtonGroup bg = new ButtonGroup();

JCheckBox

This component allows the user to select multiple items from a group of items. It is used to create a CheckBox. It is used to turn an option ON or OFF.

Declaration: public class JCheckBox extends JToggleButton implements Accessible

JCheckBox Constructors
  1. JCheckBox(): It is used to create an initially unselected checkbox button with no text, no icon.
  2. JCheckBox(Label): It is used to create an initially unselected checkbox with text.
  3. JCheckBox(Label, boolean): It is used to create a checkbox with text and specifies whether or not it is initially selected.
  4. JCheckBox(Action a): It is used to create a checkbox where properties are taken from the Action supplied.
JTextField

The JTextField component allows the user to type some text in a single line. It basically inherits the JTextComponent class.

Declaration: public class JTextField extends JTextComponent implements SwingConstants

Syntax: JTextField jtf = new JTextField();

JTextField Constructors
  1. JTextField(): It is used to create a new Text Field.
  2. JTextField(String text): It is used to create a new Text Field initialized with the specified text.
  3. JTextField(String text, int columns): It is used to create a new Text field initialized with the specified text and columns.
  4. JTextField(int columns): It is used to create a new empty TextField with the specified number of columns.
JTextArea

The JTextArea component allows the user to type the text in multiple lines. It also allows the editing of multiple-line text. It basically inherits the JTextComponent class.

Declaration: public class JTextArea extends JTextComponent

Syntax: JTextArea jta = new JTextArea();

JTextArea Constructors
  1. JTextArea(): It is used to create a text area that displays no text initially.
  2. JTextarea(String s): It is used to create a text area that displays specified text initially.
  3. JTextArea(int row, int column): It is used to create a text area with the specified number of rows and columns that display no text initially.
  4. JTextarea(String s, int row, int column): It is used to create a text area with the specified number of rows and columns that display specified text.
Sample Program to understand the above-discussed Swing Controls in Java.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SwingDemo2 extends JFrame implements ActionListener
{
    JRadioButton eng, doc;
    ButtonGroup bg;
    JTextField jtf;
    JCheckBox bcd, ccb, acb;
    JTextArea jta;
    SwingDemo2 ()
    {
        eng = new JRadioButton ("Engineer");
        doc = new JRadioButton ("Doctor");
        bg = new ButtonGroup ();
        bg.add (eng);
        bg.add (doc);
        jtf = new JTextField (20);
        bcd = new JCheckBox ("Bike");
        ccb = new JCheckBox ("Car");
        acb = new JCheckBox ("Aeroplane");
        jta = new JTextArea (3, 20);
        Container c = this.getContentPane ();
        c.setLayout (new FlowLayout ());
        
        // Registering the listeners with the components
        eng.addActionListener (this);
        doc.addActionListener (this);
        bcd.addActionListener (this);
        ccb.addActionListener (this);
        acb.addActionListener (this);
        c.add (eng);
        c.add (doc);
        c.add (jtf);
        c.add (bcd);
        c.add (ccb);
        c.add (acb);
        c.add (jta);
        this.setVisible (true);
        this.setSize (500, 500);
        this.setTitle ("Selection Example");
        this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    }
    public void actionPerformed (ActionEvent ae)
    {
        if (ae.getSource () == eng)
        {
         jtf.setText ("You are an Engineer");
        }
        if (ae.getSource () == doc)
        {
         jtf.setText ("You are an Doctor");
        }
        String str = " ";
        if (bcd.isSelected ())
        {
         str += "Bike\n";
        }
        if (ccb.isSelected ())
        {
         str += "Car\n";
        }
        if (acb.isSelected ())
        {
         str += "Aeroplane\n";
        }
        jta.setText (str);
    }
    public static void main (String[]args)
    {
        new SwingDemo2 ();
    }
}

Output:

Swing Controls in Java

JButton

This component can be used to perform some operations when the user clicks on it. When the button is pushed, the application results in some action. It basically inherits the AbstractButton class.

Declaration: public class JButton extends AbstractButton implements Accessible

Syntax: JButton jb = new JButton();

JButton Constructors
  1. JButton(): It is used to create a button with no text and icon.
  2. JButton(String s): It is used to create a button with the specified text.
  3. JButton(Icon i): It is used to create a button with the specified icon object.
Border

The border is an interface using which we can apply a border to every component. To create the borders we have to use the methods available in BorderFactory class. We can apply the created border to any component by using SetBorder() method.

Component.setBorder(Border);

Methods of Border
  1. Border createLineBorder(Color, int): It is used to create a line border. Here, Color object specifies the color of the line and int specifies the width in pixels of the line.
  2. Border createEtchedBorder(int, Color, Color): It is used to create an etched border. Here, Color arguments specify the highlight and shadow colors to be used. Here, int arguments allow the border methods to be specified as either EtchedBorder.RAISED or EtchedBorder.LOWERED. The methods without the int arguments create a lowered etched border.
  3. Border createBevelBorder(int, Color, Color):  It is used to create a raised or lowered beveled border, specifying the colors to use. Here, the integer argument can be either BevelBorder.RAISED or BevelBorder.LOWERED. Here, Color specifies the highlight and shadow colors.
  4. MatteBorder createMatteBorder(int, int, int, int, Icon): It is used to create a matte border. Here, the integer arguments specify the number of pixels that the border occupies at the top, left, bottom, and right (in that order) of whatever component uses it. Here, the color argument specifies the color which with the border should fill its area. Here, the icon argument specifies the icon which with the border should tile its area.
  5. TitledBorder createTitledBorder(Border, String, int, int, Font, Color): Create a titled border. Here, the string argument specifies the title to be displayed. Here, the optional font and color arguments specify the font and color to be used for the title’s text. Here, the border argument specifies the border that should be displayed along with the title. Here, the integer arguments specify the number of pixels that the border occupies at the top, left, bottom, and right (in that order) of whatever component uses it.
  6. CompoundBorder createCompoundBorder(Border, Border): Combine two borders into one. Here, the first argument specifies the outer border; the second, the inner border.
Sample Program to understand JButton and Border controls in Swing Java:
import javax.swing.*;
import java.awt.*;
public class JButtonDemo extends JFrame
{
    private JButton button[];
    private JPanel panel;
    public JButtonDemo ()
    {
        setTitle ("JButton Borders");
        panel = new JPanel ();
        panel.setLayout (new GridLayout (7, 1));
        button = new JButton[7];
        for (int count = 0; count < button.length; count++)
        {
         button[count] = new JButton ("Button " + (count + 1));
         panel.add (button[count]);
        }
        button[0].setBorder (BorderFactory.createLineBorder (Color.blue));
        button[1].setBorder (BorderFactory.createBevelBorder (0));
        button[2].setBorder (BorderFactory.createBevelBorder (1, Color.red, Color.blue));
        button[3].setBorder (BorderFactory.createBevelBorder (1, Color.green, Color.orange,Color.red, Color.blue));
        button[4].setBorder (BorderFactory.createEmptyBorder (10, 10, 10, 10));
        button[5].setBorder (BorderFactory.createEtchedBorder (0));
        button[6].setBorder (BorderFactory.createTitledBorder ("Titled Border"));

        add (panel, BorderLayout.CENTER);
        setSize (400, 300);
        setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo (null);
        setVisible (true);
    }
    public static void main (String[]args)
    {
        new JButtonDemo ();
    }
}

Output:

Program to understand JButton and Border controls in Swing Java

JComboBox

This component will display a group of items as a drop-down menu from which one item can be selected. At the top of the menu the choice selected by the user is shown. It basically inherits JComponent class. We can add the items to the ComboBox by using the addItem() method.

Example: jcb.addItem(item);

Declaration: public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, ActionListener, Accessible

Syntax: JComboBox jcb = new JComboBox();

JComboBox Constructors
  1. JComboBox(): It is used to create a JComboBox with a default data model.
  2. JComboBox(Object[] items): It is used to create a JComboBox that contains the elements in the specified array.
  3. JComboBox(Vector<?> items): It is used to create a JComboBox that contains the elements in the specified Vector.
Sample Program to understand JComboBox control in Java
import javax.swing.*;
public class JComboBoxDemo
{
    JFrame f;
    JComboBoxDemo ()
    {
        f = new JFrame ("ComboBox Example");
        String country[] ={ "Hyderabad", "Chennai", "Bengaluru", "Mumbai", "Delhi" };
        JComboBox cb = new JComboBox (country);
        cb.setBounds (50, 50, 90, 20);
        f.add (cb);
        f.setLayout (null);
        f.setSize (400, 500);
        f.setVisible (true);
    }
    public static void main (String[]args)
    {
        new JComboBoxDemo ();
    }
}

Output:

Program to understand JComboBox control in Java

JTabbedPane

It is a pane that can contain tabs and each tab can display any component in the same pane. It is used to switch between a group of components by clicking on a tab with a given title or icon. To add the tabs to the JTabbedPane we can use the following methods:

jtp.add(TabName, Components)

jtp.addTab(TabName, Components)

Declaration: public class JTabbedPane extends JComponent implements Serializable, Accessible, SwingConstants

Syntax: JTabbedPane jtp = new JTabbedPane();

JTabbedPane Constructors
  1. JTabbedPane(): It is used to create an empty TabbedPane.
  2. JTabbedPane(int tabPlacement): It is used to create an empty TabbedPane with a specified tab placement.
  3. JTabbedPane(int tabPlacement, int tabLayoutPolicy): It is used to create an empty TabbedPane with a specified tab placement and tab layout policy.
Sample Program to understand JTabbedPane control in Java
import javax.swing.*;
import java.awt.*;
public class JTabbedPaneDemo
{
    public static void main (String args[])
    {
        JFrame frame = new JFrame ("Technologies");
        JTabbedPane tabbedPane = new JTabbedPane ();
        JPanel panel1, panel2, panel3, panel4, panel5;
        panel1 = new JPanel ();
        panel2 = new JPanel ();
        panel3 = new JPanel ();
        panel4 = new JPanel ();
        panel5 = new JPanel ();
        tabbedPane.addTab ("Cricket", panel1);
        tabbedPane.addTab ("Badminton ", panel2);
        tabbedPane.addTab ("Football", panel3);
        tabbedPane.addTab ("Basketball ", panel4);
        tabbedPane.addTab ("Tennis", panel5);
        frame.add (tabbedPane);
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.setSize (550, 350);
        frame.setVisible (true);
    }
}

Output:

Program to understand JTabbedPane control in Java

JPasswordField

It is a text component specialized for password entry. It allows the editing of a single line of text. It basically inherits the JTextField class.

Declaration: public class JPasswordField extends JTextField

Syntax: JPasswordField jpf = new JPasswordField();

JPasswordFiled Constructors
  1. JPasswordField(): It is used to construct a new JPasswordField, with a default document, null starting text string, and column width.
  2. JPasswordField(int columns): It is used to construct a new empty JPasswordField with the specified number of columns.
  3. JPasswordField(String text): It is used to construct a new JPasswordField initialized with the specified text.
  4. JPasswordField(String text, int columns): It is used to construct a new JPasswordField initialized with the specified text and columns.
Sample Program to understand JPasswordFiled Swing control in Java
import javax.swing.*;
public class JPasswordFieldDemo
{
    public static void main (String[]args)
    {
        JFrame f = new JFrame ("Password Field Example");
        JPasswordField value = new JPasswordField ();
        JLabel l1 = new JLabel ("Password:");
        l1.setBounds (20, 100, 80, 30);
        value.setBounds (100, 100, 100, 30);
        f.add (value);
        f.add (l1);
        f.setSize (300, 300);
        f.setLayout (null);
        f.setVisible (true);
    }
}

Output:

Swing Controls in Java with Examples

Look and Feel Management in Java Swing

To manage a look and feel for the UI components swing package provides look and feel managers. In the Swing environment, look and feel are controlled by the UI Manager class.

Look and Feel Managements are shown below:

  1. MetalLookAndFeel
  2. MotifLookAndFeel
  3. NimbusLooAndFeel (added from Java1.6)
  4. WindowsLookAndFeel
  5. WindowsClassicLookAndFeel

The above looks and feels are the predefined classes.

Steps to apply a look and feel:
  1. Decide a look and feel type and inform a UI Manager to set a given look and feel and this will be done using setLookAndFeel().
  2. Once the look and feel are set we can apply to the UI Component or Component tree (whole window).

Note: To update a UI component, we need to call updateUI() to update the look and feel settings to the component. To update a whole component tree we need to call updateComponentTreeUI() from SwingUtilities class.

Sample Program for Look and Feel Management in Java Swing
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LookAndFeelDemo
{
    static JFrame jf;
    public static void main (String[]args)
    {
        jf = new JFrame ();
        jf.setSize (250, 250);
        FlowLayout ob = new FlowLayout ();
        jf.setLayout (ob);
        JButton jb1 = new JButton ("Metal");
        JButton jb2 = new JButton ("Nimbus");
        JButton jb3 = new JButton ("Motif");
        JButton jb4 = new JButton ("Windows");
        MyListener ob1 = new MyListener ();
        jb1.addActionListener (ob1);
        jb2.addActionListener (ob1);
        jb3.addActionListener (ob1);
        jb4.addActionListener (ob1);
        jf.add (jb1);
        jf.add (jb2);
        jf.add (jb3);
        jf.add (jb4);
        jf.setVisible (true);
    }
}
class MyListener implements ActionListener
{
    public void actionPerformed (ActionEvent ae)
    {
        try
        {
            String buttonname = ae.getActionCommand ();
            if (buttonname.equals ("Metal"))
         {
             UIManager.setLookAndFeel ("javax.swing.plaf.metal.MetalLookAndFeel");
             SwingUtilities.updateComponentTreeUI (LookAndFeelDemo.jf);
         }
            else if (buttonname.equals ("Nimbus"))
         {
             UIManager.setLookAndFeel ("javax.swing.plaf.metal.NimbusLookAndFeel");
             SwingUtilities.updateComponentTreeUI (LookAndFeelDemo.jf);
         }
            else if (buttonname.equals ("Motif"))
         {
             UIManager.setLookAndFeel ("javax.swing.plaf.metal.MotifLookAndFeel");
             SwingUtilities.updateComponentTreeUI (LookAndFeelDemo.jf);
         }
            else if (buttonname.equals ("Windows"))
         {
             UIManager.setLookAndFeel ("javax.swing.plaf.metal.WindowsLookAndFeel");
             SwingUtilities.updateComponentTreeUI (LookAndFeelDemo.jf);
         }
        }
        catch (Exception e1)
        {
        }
    }
}

Output:

Swing Controls in Java with Examples

In the next article, I am going to discuss the Swing Dialog box in Java with examples. Here, in this article, I try to explain Swing Controls in Java with Examples and I hope you enjoy this Swing Controls in Java with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *