For Enquiry: 93450 45466

Swing In Java: Know How To Create GUI With Examples


Swing In Java Know How To Create GUI With Examples

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.

SWING Containers

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

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 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.






Quick Enquiry

Please wait while submission in progress...


Contact Us

Chennai

  93450 45466

Bangalore

 93450 45466

Coimbatore

 95978 88270

Online

93450 45466

Madurai

97900 94102

Pondicherry

93635 21112

For Hiring

 93840 47472
 hr@fita.in

Corporate Training

 90036 23340


FITA Academy Branches

Chennai

FITA Academy - Velachery
Plot No 7, 2nd floor,
Vadivelan Nagar,
Velachery Main Road,
Velachery, Chennai - 600042
Tamil Nadu

    :   93450 45466

FITA Academy - Anna Nagar
No 14, Block No, 338, 2nd Ave,
Anna Nagar,
Chennai 600 040, Tamil Nadu
Next to Santhosh Super Market

    :   93450 45466

FITA Academy - T Nagar
05, 5th Floor, Challa Mall,
T Nagar,
Chennai 600 017, Tamil Nadu
Opposite to Pondy Bazaar Globus

    :   93450 45466

FITA Academy - Tambaram
Nehru Nagar, Kadaperi,
GST Road, West Tambaram,
Chennai 600 045, Tamil Nadu
Opposite to Saravana Jewellers Near MEPZ

    :   93450 45466

FITA Academy - Thoraipakkam
5/350, Old Mahabalipuram Road,
Okkiyam Thoraipakkam,
Chennai 600 097, Tamil Nadu
Next to Cognizant Thoraipakkam Office
& Opposite to Nilgris Supermarket

    :   93450 45466

FITA Academy - Porur
17, Trunk Rd,
Porur
Chennai 600116, Tamil Nadu
Above Maharashtra Bank

    :   93450 45466

FITA Academy - Pallikaranai
335A, 13th Main Rd,
Ram Nagar South Extn,
Pallikaranai, Chennai,
Tamil Nadu 600100

    :   93450 45466

Bangalore

FITA Academy Marathahalli
No 7, J J Complex,
ITPB Road, Aswath Nagar,
Marathahalli Post,
Bengaluru 560037

    :   93450 45466

Coimbatore

FITA Academy - Saravanampatty
First Floor, Promenade Tower,
171/2A, Sathy Road, Saravanampatty,
Coimbatore - 641035
Tamil Nadu

    :   95978 88270

FITA Academy - Singanallur
348/1, Kamaraj Road,
Varadharajapuram, Singanallur,
Coimbatore - 641015
Tamil Nadu

    :   95978 88270

Other Locations

FITA Academy - Madurai
No.2A, Sivanandha salai,
Arapalayam Cross Road,
Ponnagaram Colony,
Madurai - 625016, Tamil Nadu

    :   97900 94102

FITA Academy - Pondicherry
410, Villianur Main Rd,
Sithananda Nagar, Nellitope,
Puducherry - 605005
Near IG Square

    :   93635 21112

FITA Academy - Tiruppur
61D, Poongodi Towers 2nd floor,
Periyar Colony Bus Stop,
Tirupur - 641 652

    :   9940122502

Read More Read less
  • Are You Located in Any of these Areas

    Adyar, Adambakkam, Anna Salai, Ambattur, Ashok Nagar, Aminjikarai, Anna Nagar, Besant Nagar, Chromepet, Choolaimedu, Guindy, Egmore, K.K. Nagar, Kodambakkam, Koyambedu, Ekkattuthangal, Kilpauk, Meenambakkam, Medavakkam, Nandanam, Nungambakkam, Madipakkam, Teynampet, Nanganallur, Navalur, Mylapore, Pallavaram, Purasaiwakkam, OMR, Porur, Pallikaranai, Poonamallee, Perambur, Saidapet, Siruseri, St.Thomas Mount, Perungudi, T.Nagar, Sholinganallur, Triplicane, Thoraipakkam, Tambaram, Vadapalani, Valasaravakkam, Villivakkam, Thiruvanmiyur, West Mambalam, Velachery and Virugambakkam.

    FITA Velachery or T Nagar or Thoraipakkam OMR or Anna Nagar or Tambaram or Porur branch is just few kilometre away from your location. If you need the best training in Chennai, driving a couple of extra kilometres is worth it!