Swing, a key part of Java’s foundational classes, is a versatile and cross-platform toolkit for building window-based applications. It provides a wide range of components like buttons, scroll bars, and text fields, which can be combined to create graphical user interfaces (GUIs). Swing’s lightweight nature makes it efficient, and it’s platform-independent, ensuring consistent functionality across different operating systems. This article explores the fundamental concepts and techniques involved in developing Java applications with Swing, empowering developers to design interactive and user-friendly software interfaces for a variety of purposes. Join Java training in Chennai and start your journey in the field of Java development
What is Swing In Java?
Swing, a lightweight GUI toolkit in Java, offers an extensive array of widgets for crafting efficient window-based applications. It’s an integral component of the Java Foundation Classes (JFC), built atop the AWT API and entirely coded in Java. Notably, Swing is platform-independent, in contrast to AWT, and boasts lightweight components. This versatility streamlines application development, as developers can readily leverage existing GUI components such as buttons and checkboxes, eliminating the need to begin from scratch and simplifying the design process.
Container Class
A container class is any class that contains other components within it. In the context of GUI application development, at least one container class is essential. There are three primary types of container classes:
JPanel
Panels are used to organise and group components within a window. They serve as a way to structure the layout of elements on the screen.
JFrame
Frames are fully functional windows that typically include icons, titles, and the ability to be moved, minimised, maximised, and closed. They provide the main application window.
JDialog
Dialogs are like pop-up windows that can display information, request user input, or provide alerts. However, they are not as fully functional as frames and are often used for specific tasks within an application.
These container classes play a crucial role in designing the structure and user interface of graphical applications in Java.
Java Swing Class Hierarchy
In Swing, components such as JButton, JComboBox, JList, and JLabel inherit from the JComponent class, making them compatible for inclusion in container classes. Containers, represented by windows-like frames and dialogue boxes, serve as the foundation for building graphical user interfaces (GUIs).
These basic swing components in Java are fundamental building blocks for constructing GUI applications. Developers can utilise methods like setLayout to customise the layout of components within containers, overriding the default layout as needed.
Containers like JFrame and JDialog have the capability to add components to themselves, allowing for the creation of complex and interactive interfaces. Below, we’ll explore a few examples of these components to illustrate how they can be effectively utilised in GUI application development. Enfrol for Java training in Mumbai and be a full-time developer in the field of Java programming
JButton Class
The provided code is an example of how to create a simple GUI application in Java Swing. Here’s an explanation of the code:
import javax.swing.*;
public class example{
public static void main(String args[]) {
JFrame a = new JFrame("example");
JButton b = new JButton("click me");
b.setBounds(40,90,85,20);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}
This code creates a simple Swing application with a JFrame containing a JButton. When you run this code, it will display a window with a button labelled “click me.” However, it’s important to note that this example doesn’t include any action when the button is clicked; you would typically add an ActionListener to specify what should happen when the button is pushed.
JTextField Class
The description you provided is about a JTextField in Java Swing. Here’s a rephrased explanation:
A JTextField in Java Swing is a component that inherits from the JTextComponent class. It is primarily used to enable the editing of single-line text. This means it provides a user interface element where users can input and edit text in a single line, making it suitable for various text input scenarios within graphical user interfaces.
The provided code is a Java Swing application example that creates a JFrame containing a JTextField.
import javax.swing.*;
public class example{
public static void main(String args[]) {
JFrame a = new JFrame("example");
JTextField b = new JTextField("edureka");
b.setBounds(50,100,200,30);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}
When you run this code, it will display a window (JFrame) containing a single-line text field (JTextField) with the initial text “FITA Academy.” Users can interact with the text field to input and edit text.
JScrollBar Class
A JScrollPane in Java Swing is a component used to add scrollbars, both horizontally and vertically, to a container that might contain more content than can be displayed within its visible area. This component is crucial for enabling users to navigate and view the entire content of a larger or overflowing area, such as a panel or text area, by providing scrollbars that allow for scrolling in both horizontal and vertical directions. Confused about Java? Join Java training in Bangalore and learn from the fundamentals with our expert trainers
import javax.swing.*;
class example{
example(){
JFrame a = new JFrame("example");
JScrollBar b = new JScrollBar();
b.setBounds(90,90,40,90);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[]){
new example();
}
}
JPanel Class
The provided code creates a Java Swing example that adds a vertical scrollbar to a JFrame. However, it’s important to note that it does not include a horizontal scrollbar.
import javax.swing.*;
class example{
example(){
JFrame a = new JFrame("example");
JScrollBar b = new JScrollBar();
b.setBounds(90,90,40,90);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[]){
new example();
}
}
JMenu Class
A JPanel in Java Swing is a component that inherits from the JComponent class. It serves as a versatile container that provides space for an application to attach and organise various other components. JPanel acts as a blank canvas where developers can add and arrange other swing components in Java, making it a fundamental building block for constructing graphical user interfaces (GUIs) in Java applications. If you want to know more about the latest interview question for a java developer job role, Check out Java Interview Questions and Answers, which will help you get an insight into the various types of questions and tips.
import java.awt.*;
import javax.swing.*;
public class Example{
Example(){
JFrame a = new JFrame("example");
JPanel p = new JPanel();
p.setBounds(40,70,200,200);
JButton b = new JButton("click me");
b.setBounds(60,50,80,40);
p.add(b);
a.add(p);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[])
{
new Example();
}
}
JList Class
A JMenu in swing controls in Java inherits from the JMenuItem class and is a pull-down menu component typically displayed from the menu bar. It serves as a container for a list of menu items or submenus that users can interact with to access various actions or options within a graphical user interface (GUI) application. JMenus are an essential part of creating user-friendly and organised menu systems in Swing and AWT in Java applications.
import javax.swing.*;
class Example{
JMenu menu;
JMenuItem a1,a2;
Example()
{
JFrame a = new JFrame("Example");
menu = new JMenu("options");
JMenuBar m1 = new JMenuBar();
a1 = new JMenuItem("example");
a2 = new JMenuItem("example1");
menu.add(a1);
menu.add(a2);
m1.add(menu);
a.setJMenuBar(m1);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[])
{
new Example();
}
}
JLabel Class
The JList class in Java Swing inherits from the JComponent class. It is used to create a graphical component that represents a list of text items or other objects. JList provides a way to display and interact with lists of items within a graphical user interface (GUI) application, making it a valuable component for tasks involving lists, selections, and data presentation.
import javax.swing.*;
public class Example
{
Example(){
JFrame a = new JFrame("example");
DefaultListModel l = new DefaultListModel< >();
l.addElement("first item");
l.addElement("second item");
JList b = new JList< >(l);
b.setBounds(100,100,75,75);
a.add(b);
a.setSize(400,400);
a.setVisible(true);
a.setLayout(null);
}
public static void main(String args[])
{
new Example();
}
}
JComboBox Class
The JPopupMenu class in swing controls in Java inherits from the JComponent class and is used to display a pop-up menu of selectable choices within a graphical user interface (GUI). It enables developers to create context menus or dropdown menus that appear when triggered, offering a set of options for users to choose from in response to a specific action or context.
import javax.swing.*;
public class Example{
JFrame a;
Example(){
a = new JFrame("example");
string courses[] = { "core java","advance java", "java servlet"};
JComboBox c = new JComboBox(courses);
c.setBounds(40,40,90,20);
a.add(c);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[])
{
new Example();
}
}
Layout Manager
Layout managers in swing controls in Java programs are essential for arranging components within containers. Several commonly used layout managers include:
BorderLayout
- BorderLayout is the default layout manager for JFrame.
- It divides the container into five regions: top, bottom, left, right, and center.
- Components placed within these regions can expand and occupy available space.
FlowLayout
- FlowLayout is the default layout manager for JPanel.
- It arranges components in a row, one after the other.
- Components are added sequentially, and when the horizontal space is exhausted, they wrap to the next row.
GridBagLayout
- GridBagLayout allows components to be placed in a grid.
- Components can span multiple cells both horizontally and vertically.
- This layout manager provides fine-grained control over component positioning and sizing.
Each of these layout managers serves different purposes and is suited to different design requirements in Swing GUI applications. Choosing the appropriate layout manager is crucial for achieving the desired user interface layout and behaviour. Learn Java from the fundamentals, JoinJava training in Hyderabad and equip yourself with advanced Java knowledge
Example: Chat Frame
import javax.swing.*;
import java.awt.*;
class Example {
public static void main(String args[]) {
JFrame frame = new JFrame("Chat Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
JMenuBar ob = new JMenuBar();
JMenu ob1 = new JMenu("FILE");
JMenu ob2 = new JMenu("Help");
ob.add(ob1);
ob.add(ob2);
JMenuItem m11 = new JMenuItem("Open");
JMenuItem m22 = new JMenuItem("Save as");
ob1.add(m11);
ob1.add(m22);
JPanel panel = new JPanel(); // the panel is not visible in output
JLabel label = new JLabel("Enter Text");
JTextField tf = new JTextField(10); // accepts upto 10 characters
JButton send = new JButton("Send");
JButton reset = new JButton("Reset");
panel.add(label); // Components Added using Flow Layout
panel.add(label); // Components Added using Flow Layout
panel.add(tf);
panel.add(send);
panel.add(reset);
JTextArea ta = new JTextArea();
frame.getContentPane().add(BorderLayout.SOUTH, panel);
frame.getContentPane().add(BorderLayout.NORTH, tf);
frame.getContentPane().add(BorderLayout.CENTER, ta);
frame.setVisible(true);
}
}
Within this article, we have delved into the realm of swing controls in Java and the intricate hierarchy of Java Swing classes. The extensive assortment of components provided by Java Swing simplifies the development of highly optimised and visually engaging GUI applications. As the Java programming language stands as a structured and foundational language in the software development landscape, it is imperative for aspiring programmers to attain comprehensive mastery over its multifaceted concepts. In an era of growing demand for robust and user-friendly applications, this proficiency becomes paramount in ensuring success in the field of Java development.