12 Swing — Java Programming
12.1 Swing
The user interface components in application and applets can be built using AWT components provided by Java. Java also provides another alternative, supercharged components called Swing components. Swing is a set of classes that provides more powerful and flexible components than are possible with the AWT. In addition to buttons, check boxes, and labels, Swing provides several other exiting components such as buttons with additional capabilities, textarea with existing features, trees, tables, progress meters, tool tips and component organizers.
Unlike AWT components, Swing components are based on JFC (Java Foundation Classes) and are not implemented by platform specific code. Instead, they are written entirely in Java and therefore are platform-independent. So they are called lightweight components. The AWT components, which are platform dependent, are called heavyweight component.
The following table lists various swing components and their AWT counterparts:
AWT Components |
Swing Components |
Applet |
JApplet |
Button |
JButton |
CheckBox |
JCheckBox |
ComboBox |
J ComboBox |
Component |
J Component |
Dialog |
JDialog |
Frame |
JFrame |
Label |
JLabel |
List |
JList |
Menu |
JMenu |
Panel |
JPanel |
ScrollBar |
JScrollBar |
TextArea |
JTextArea |
TextField |
JTextField |
Window |
JWindow |
The main differences between AWT and Swing are
AWT | SWING |
Components are Platform dependent | Components are Platform independent |
not Pluggable | Pluggable |
limited components | powerful and large number of components |
No MVC Architecture | Supports MVC |
*MVC means Model View Architecture.
12.2 Hierarchy of Java SWING classes
12.3 Components
Method | Description |
---|---|
public void add(Component c) | add a component on another component. |
public void setSize(int width,int height) | sets size of the component. |
public void setLayout(LayoutManager m) | sets the layout manager for the component. |
public void setVisible(boolean b) | sets the visibility of the component. It is by default false. |
12.4 TextField
The swing text field is encapsulated by the JTextComponent class, which extends Jcomponent. It provides functionality that is common to swing text components. An instance of the text field can be obtained by using one of the following constructors.
JTextField() JtextField(int cols) JtextField(String str, int cols) JtextField(String str)
Str is the string that should be present in the TextField by default and the cols is the number of columns in the text field.
12.5 Button
Swing buttons provide features that are not found in the Button class defined by AWT package. For example, an icon can be displayed on a swing button, different icons can be displayed on the button when it is disabled, pressed, or selected. A button can be created using one of the following constructors:
JButton(Icon ico) JButton(String str) JButton(String str, Icon ico)
Str is the text that should be displayed on the button by default and ico is the default icon displayed on the button.
The following example in the field is modified when the button is pressed each time.
There are two ways to create a frame:
- By creating the object of Frame class (association)
- By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.
Program 12.1 Using Swing to display Label and Button in a Grid.
//simpleSwing.java import javax.swing.*; import java.awt.*; public class simpleSwing{ public static void main(String[] args) { JFrame f=new JFrame(); JLabel l=new JLabel("This is Label"); JButton b=new JButton("Click on this Button"); f.add(l); f.add(b); f.setSize(500,500); f.setLayout(new GridLayout()); f.setVisible(true); } }
12.1 simpleSwing demonstration
You can also rewrite this program using a constructor or extending the JFrame class
Program 12.2 Program to display the number of times a button is pressed using ActionListener
//buttonPressed.java import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class buttonPressed implements ActionListener{ JTextField t;JButton b;int i; public buttonPressed() { JFrame f=new JFrame(); JLabel l=new JLabel("This is Label"); t=new JTextField(); b=new JButton("Click on this Button"); f.add(l); f.add(b); f.add(t); b.addActionListener(this); f.setSize(500,500); f.setLayout(new GridLayout()); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent ae) { i++; t.setText("Button clicked "+i+" times"); } public static void main(String args[]) { buttonPressed bp = new buttonPressed(); } } When this program is run and the button is clicked multiple times the output will be as follows:
12.6 CheckBox
The JCheckBox which provides the functionality of a checkbox can be instantiated using one of the following constructors
JCheckBox(String str)
JCheckBox(String str, Boolean l)
JCheckBox(String str, Icon ico)
JCheckBox(String str, Icon ico, Boolean state)
Str is the string text associated with the checkbox , ico is the ico displayed for the checkbox and the state specifies if the check box is checked or not. The check box with return true if it is checked. To receive the events related to check boxes the class building them shold implement the ItemListener interface. The events are handled by the itemStateCHange() method. The getItem() method can be used to determine which item has generated the event.
12.7 Radio Buttons
Radio buttons are supported by the JRadiaButton class. The constructors available for the instantiating the radio buttons are as follows:
JRadioButton(String str)
JRadioButton(String str, Boolean state)
JRadioButton(String str, Icon ico)
JRadioButton(String str, Icon ico, Boolean state)
The variables are same as in the case of the checkboxes. Radio buttons must be configured into a group. Only one of the buttons in that group can be selected at any time. Any previously selected button will be deselected automatically. To add radio button to a group, ButtonGroup class is instantiated and the buttons are added using the add() method.
12.8 Combo Boxes
Swing provides a combo box that can display one entry at a time. It can also display a drop-down list that allows a user to select a different entry. You can also type your solution into the text field. The constructors for instantiating the combo box are:
JComboBox()
JComboBox(Vetor vect)
Here vet is vector that initializes the combo box. Items are added to the list of choices by the method addItem() method.
Program 12.3 Program to demonstrate the use of combo box
import java.awt.*; import javax.swing.*; import java.awt.event.*; public class All extends JFrame implements ItemListener, ActionListener { JTextField jtf; JCheckBox jcb; JComboBox<String> jcob; public All() { setTitle("All"); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout()); JPanel p1 = new JPanel(); JPanel p2 = new JPanel(); JPanel p3 = new JPanel(); JPanel p4 = new JPanel(); jtf = new JTextField(15); p1.add(jtf); jcb = new JCheckBox("CheckBox"); jcb.addItemListener(this); p2.add(jcb); ButtonGroup bg = new ButtonGroup(); JRadioButton b1 = new JRadioButton("Radio 1"); JRadioButton b2 = new JRadioButton("Radio 2"); b1.addActionListener(this); b2.addActionListener(this); bg.add(b1); bg.add(b2); p3.add(b1); p3.add(b2); jcob = new JComboBox<>(); jcob.addItemListener(this); jcob.addItem("Sunil"); jcob.addItem("Amar"); jcob.addItem("Badri"); p4.add(jcob); add(p1); add(p2); add(p3); add(p4); setVisible(true); } public void actionPerformed(ActionEvent ae) { jtf.setText(ae.getActionCommand()); } public void itemStateChanged(ItemEvent ie) { if (ie.getSource() == jcb) { jtf.setText(jcb.getText()); } else { jtf.setText((String) ie.getItem()); } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new All(); } }); } }
12.9 Tabbed Panes
Tabbed pane is a component that appears as a group of folders in a file cabinet. Each folder has a title. When a user selects a folder, its contents become visible. Only one of the folders may be selected at a time. The constructor for instantiating the tabbed panes is JTabbedPane(). You can add panels to each page of the tabbed pane using the method addTab(String str, Component comp). Here str is the title of the tab and comp is the panel that is added to the particular pane.
Program 12.4 Program for Tabbed panes
import java.awt.*; import javax.swing.*; public class Tpane extends JFrame { public Tpane() { setTitle("Tabbed Pane Example"); setSize(300, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); init(); setVisible(true); } public void init() { JTabbedPane jtp = new JTabbedPane(); jtp.addTab("First", new MyPanel1()); jtp.addTab("Second", new MyPanel2()); jtp.addTab("Third", new MyPanel3()); getContentPane().add(jtp); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Tpane(); } }); } } class MyPanel1 extends JPanel { MyPanel1() { JLabel l = new JLabel("This is first Pane"); add(l); } } class MyPanel2 extends JPanel { MyPanel2() { JLabel l = new JLabel("This is second Pane"); add(l); } } class MyPanel3 extends JPanel { MyPanel3() { JLabel l = new JLabel("This is third Pane"); add(l); } }
12.10 Scroll Panes
The scroll pane is a component that presents a rectangular are in which a component may be viewed. Horizontal and vertical scroll bard may be provided if necessary. Scroll panes in swing are implemented using the JScrollPane class. The constructors are as follows
JScrollPane(Component comp)
JScrollPane(int vsb, int hsb)
JScrollPane(Component comp, int vsb, int hsb)
Here comp is the component that is to be added to the scroll pane and hsb and vsb are the constants that define when horizontal and vertical scroll bars are to be show in the scroll pane. Some of the examples of these constants are
HORIZONTAL_SCROLLBAR_ALWAYS
HORIZONTAL_SCROLLBAR_AS_NEEDED
VERTICAL_SCROLLBAR_ALWAYS
VERTICAL _SCROLLBAR_AS_NEEDED
Program 12.5. Program to demonstrate Scroll Bars
import java.awt.*; import javax.swing.*; public class Scroll extends JFrame { public Scroll() { setTitle("Scroll Pane Example"); setSize(300, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); init(); setVisible(true); } public void init() { Container cp = getContentPane(); cp.setLayout(new BorderLayout()); // Use BorderLayout to place JScrollPane in the center JPanel jp = new JPanel(); jp.setLayout(new GridLayout(10, 10)); // Use GridLayout for buttons int b = 0; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { jp.add(new JButton("Button " + b)); b++; } } int v = JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED; int h = JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp = new JScrollPane(jp, v, h); cp.add(jsp, BorderLayout.CENTER); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Scroll(); } }); } }
12.11 Summary
You are introduced with AWT that has the flexibility to provide a user interface that appears the same on all platforms. The concept of Swing is also introduced. As, in future Swing may take over. AWT Classes, Events, text fields, buttons, check boxes, radio buttons, scroll bars, windows, menus etc., are discussed with examples.
Media Attributions
- Picture1
- Picture2
- Picture3
- Picture4
- Picture5