Back to: Java Tutorials For Beginners and Professionals
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.
- JLabel
- JRadioButton
- ButtonGroup
- JCheckBox
- JTextField
- JTextArea
- JButton
- Border
- JComboBox
- JTabbedPane
- JPasswordField
- Look and Feel Management in Java Swing
JLabel
The object of the JLabel class may be a component for putting text in 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
- JLabel(): It is used to create a JLabel instance with no image and with an empty string for the title.
- JLabel(String s): It is used to create a JLabel instance with the specified text.
- JLabel(Icon i): It is used to create a JLabel instance with the specified image.
- JLabel(String s, Icon I, int horizontalAlignment): It is used to create a JLabel instance with the specified text, image, and horizontal alignment.
Example 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:
JRadioButton Swing Control in Java
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
- JRadioButton(): It is used to create an unselected radio button with no text.
- JRadioButton(Label): It is used to create an unselected radio button with specified text.
- 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
- JCheckBox(): It is used to create an initially unselected checkbox button with no text, no icon.
- JCheckBox(Label): It is used to create an initially unselected checkbox with text.
- JCheckBox(Label, boolean): It is used to create a checkbox with text and specifies whether or not it is initially selected.
- 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
- JTextField(): It is used to create a new Text Field.
- JTextField(String text): It is used to create a new Text Field initialized with the specified text.
- JTextField(String text, int columns): It is used to create a new Text field initialized with the specified text and columns.
- 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
- JTextArea(): It is used to create a text area that displays no text initially.
- JTextarea(String s): It is used to create a text area that displays specified text initially.
- 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.
- 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.
Example 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:
JButton Swing Control in Java
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
- JButton(): It is used to create a button with no text and icon.
- JButton(String s): It is used to create a button with the specified text.
- JButton(Icon i): It is used to create a button with the specified icon object.
Border Swing Control in Java
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 the SetBorder() method.
Component.setBorder(Border);
Methods of Border
- Border createLineBorder(Color, int): It is used to create a line border. Here, the Color object specifies the color of the line and int specifies the width in pixels of the line.
- 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.
- 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.
- 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.
- 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.
- CompoundBorder createCompoundBorder(Border, Border): Combine two borders into one. Here, the first argument specifies the outer border; the second, the inner border.
Example to understand JButton and Border Swing Controls in 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:
JComboBox Swing Control in Java
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
- JComboBox(): It is used to create a JComboBox with a default data model.
- JComboBox(Object[] items): It is used to create a JComboBox that contains the elements in the specified array.
- JComboBox(Vector<?> items): It is used to create a JComboBox that contains the elements in the specified Vector.
Example to understand JComboBox Swing 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:
JTabbedPane Swing Control in Java
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
- JTabbedPane(): It is used to create an empty TabbedPane.
- JTabbedPane(int tabPlacement): It is used to create an empty TabbedPane with a specified tab placement.
- JTabbedPane(int tabPlacement, int tabLayoutPolicy): It is used to create an empty TabbedPane with a specified tab placement and tab layout policy.
Example 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:
JPasswordField Swing Control in Java
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
- JPasswordField(): It is used to construct a new JPasswordField, with a default document, null starting text string, and column width.
- JPasswordField(int columns): It is used to construct a new empty JPasswordField with the specified number of columns.
- JPasswordField(String text): It is used to construct a new JPasswordField initialized with the specified text.
- JPasswordField(String text, int columns): It is used to construct a new JPasswordField initialized with the specified text and columns.
Example 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:
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:
- MetalLookAndFeel
- MotifLookAndFeel
- NimbusLooAndFeel (added from Java1.6)
- WindowsLookAndFeel
- WindowsClassicLookAndFeel
The above looks and feels are the predefined classes.
Steps to apply a look and feel:
- 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().
- Once the look and feel are set we can apply them 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 of the component. To update a whole component tree we need to call updateComponentTreeUI() from SwingUtilities class.
Example 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:
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.