Swing in Java
Swing in Java
INTRODUCTION TO SWING:
The AWT library took help of underlying OS to generate peers for each UI component.
Also they need not take on the “look & feel” of the target platform ; thus helps in maintaining a
consistent “look & feel” over all platforms
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
3) AWT doesn't support pluggable look and feel. Swing supports pluggab
5) AWT doesn't follows MVC(Model View Controller) where model Swing follows MVC.
represents data, view represents presentation and controller
acts as an interface between model and view.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
Method Description
public void setLayout(LayoutManager m) sets the layout manager for the component.
java.awt.Component
java.awt.Container
javax.swing.JComponent
Swing Components
JAPPLET:
JApplet is a java swing public class designed for developers usually written in Java. JApplet is
generally in the form of Java bytecode that runs with the help of a Java virtual machine (JVM) or
Applet viewer from Sun Microsystems. It was first introduced in 1995.
JApplet can also be written in other programming languages and can later be compiled to Java
byte code.
In the above example, we have created all the controls in init() method because it is invoked only once.
myapplet.html
1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Class Declaration
Following is the declaration for javax.swing.ImageIcon class −
public class ImageIcon
extends Object
implements Icon, Serializable, Accessible
Field
Following are the fields for javax.swing.ImageIcon class −
Class Constructors
Sr.No. Constructor & Description
1 ImageIcon()
Creates an uninitialized image icon.
ImageIcon(byte[] imageData)
ImageIcon(Image image)
4
Creates an ImageIcon from an image object.
ImageIcon(String filename)
6
Creates an ImageIcon from the specified file.
ImageIcon(URL location)
8
Creates an ImageIcon from the specified URL.
Class Methods
Sr.No. Method & Description
AccessibleContext getAccessibleContext()
1
Gets the AccessibleContext associated with this ImageIcon.
String getDescription()
2
Gets the description of the image.
int getIconHeight()
3
Gets the height of the icon.
int getIconWidth()
4
Gets the width of the icon.
Image getImage()
5
Returns this icon's Image.
int getImageLoadStatus()
6
Returns the status of the image loading operation.
ImageObserver getImageObserver()
7
Returns the image observer for the image.
String toString()
13
Returns a string representation of this image.
Methods Inherited
This class inherits methods from the following classes −
java.lang.Object
ImageIcon Example
Create the following Java program using any editor of your choice in
say D:/ > SWING > com > tutorialspoint > gui >
SwingControlDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public SwingControlDemo(){
prepareGUI();
swingControlDemo.showImageIconDemo();
mainFrame.setSize(400,400);
mainFrame.addWindowListener(new WindowAdapter() {
System.exit(0);
});
statusLabel.setSize(350,100);
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
String description) {
if (imgURL != null) {
} else {
return null;
controlPanel.add(commentlabel);
mainFrame.setVisible(true);
Compile the program using the command prompt. And no error occurs, it
means the compilation is successful. Run the program using the following
command.
the following output is generated:
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display
a single line of read only text. The text can be changed by an application but a user cannot
edit it directly. It inherits JComponent c.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, imag
horizontalAlignment) alignment.
Commonly used Methods:
Methods Description
void setText(String text) It defines the single line of text this component will display.
void It sets the alignment of the label's contents along the X axis.
setHorizontalAlignment(int
alignment)
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along the X axis.
Output:
Java JLabel Example with ActionListener
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class LabelExample extends Frame implements ActionListener{
5. JTextField tf; JLabel l; JButton b;
6. LabelExample(){
7. tf=new JTextField();
8. tf.setBounds(50,50, 150,20);
9. l=new JLabel();
10. l.setBounds(50,100, 250,20);
11. b=new JButton("Find IP");
12. b.setBounds(50,150,95,30);
13. b.addActionListener(this);
14. add(b);add(tf);add(l);
15. setSize(400,400);
16. setLayout(null);
17. setVisible(true);
18. }
19. public void actionPerformed(ActionEvent e) {
20. try{
21. String host=tf.getText();
22. String ip=java.net.InetAddress.getByName(host).getHostAddress();
23. l.setText("IP of "+host+" is: "+ip);
24. }catch(Exception ex){System.out.println(ex);}
25. }
26. public static void main(String[] args) {
27. new LabelExample();
28. }}
Output:
TextField
The object of a JTextField class is a text component that allows the editing of a single line
text. It inherits JTextComponent class.
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int columns) Creates a new TextField initialized with the specified text a
JTextField(int columns) Creates a new empty TextField with the specified number
Commonly used Methods:
Methods Description
Action getAction() It returns the currently set Action for this ActionEvent so
Action is set.
COMBO BOX:
Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user
is shown on the top of a menu. It inherits JComponent class.
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specifi
JComboBox(Vector<?> items) Creates a JComboBox that contains the elements in the specifi
void removeAllItems() It is used to remove all the items from the list.
Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.
SCROLL PANES:
A JscrollPane is used to make scrollable view of a component. When screen size is limited,
we use a scroll pane to display a large component or a component whose size can change
dynamically.
Constructors
Constructor Purpose
JScrollPane(int, int)
JScrollPane(Component,
int, int)
Useful Methods
Modifier Method Description
Void setColumnHeaderView(Compone It sets the column header for the scroll pane.
nt)
Void setRowHeaderView(Component) It sets the row header for the scroll pane.
JScrollPane Example
1. import java.awt.FlowLayout;
2. import javax.swing.JFrame;
3. import javax.swing.JScrollPane;
4. import javax.swing.JtextArea;
5.
6. public class JScrollPaneExample {
7. private static final long serialVersionUID = 1L;
8.
9. private static void createAndShowGUI() {
10.
11. // Create and set up the window.
12. final JFrame frame = new JFrame("Scroll Pane Example");
13.
14. // Display the window.
15. frame.setSize(500, 500);
16. frame.setVisible(true);
17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18.
19. // set flow layout for the frame
20. frame.getContentPane().setLayout(new FlowLayout());
21.
22. JTextArea textArea = new JTextArea(20, 20);
23. JScrollPane scrollableTextArea = new JScrollPane(textArea);
24.
25. scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR
_ALWAYS);
26. scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWA
YS);
27.
28. frame.getContentPane().add(scrollableTextArea);
29. }
30. public static void main(String[] args) {
31.
32.
33. javax.swing.SwingUtilities.invokeLater(new Runnable() {
34.
35. public void run() {
36. createAndShowGUI();
37. }
38. });
39. }
40. }
OUTPUT:
TREE :
The JTree class is used to display the tree structured data or hierarchical data. JTree is a
complex component. It has a 'root node' at the top most which is a parent for all nodes in
the tree. It inherits JComponent class.
JTree(Object[] value) Creates a JTree with every element of the specified array as the child of a
JTree(TreeNode root) Creates a JTree with the specified TreeNode as its root, which displays the
TABLE:The JTable class is used to display data in tabular form. It is composed of rows
and columns.
Output: