Skip to content
Home » Swing Classes In Java | Sự Khác Biệt Giữa Awt Và Swing

Swing Classes In Java | Sự Khác Biệt Giữa Awt Và Swing

Java Swing For Beginners | What is Java Swing | Java Swing Tutorial | Intellipaat

What is Swing in Java?

Swing in Java is a Graphical User Interface (GUI) toolkit that includes the GUI components. Swing provides a rich set of widgets and packages to make sophisticated GUI components for Java applications. Swing is a part of Java Foundation Classes(JFC), which is an API for Java GUI programing that provide GUI.

The Java Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older, platform dependent GUI toolkit. You can use the Java simple GUI programming components like button, textbox, etc., from the library and do not have to create the components from scratch.

In this Java Swing tutorial, you will learn Java GUI basics like-

  • What is Swing in Java?
  • What is a Container Class?
  • What is GUI in Java?
  • How to Make a GUI in Java with Example
  • Java Layout Manager
  • Java BorderLayout
  • Java FlowLayout
  • Java GridBagLayout

Java Swing class Hierarchy Diagram

All components in Java Swing are JComponent which can be added to container classes.

Container class là gì?

Container class (lớp vùng chứa) là các class có thể chứa các component khác trên đó. Vì vậy, để tạo Java GUI, chúng ta cần ít nhất một container object (đối tượng vùng chứa). Java Swing có 3 loại container.

  1. Panel (bảng điều khiển): là một container thuần túy và thực chất không phải là một window (cửa sổ). Mục đích duy nhất của Panel là tổ chức các component trên một window.
  2. Frame (khung): là một window hoàn chỉnh có đầy đủ title (tiêu đề) và các icon (biểu tượng).
  3. Dialog (hộp thoại): có thể được coi như một pop-up window sẽ bật ra khi một tin nhắn cần được hiển thị. Nó không phải là window hoàn chỉnh như Frame.
Java Swing For Beginners | What is Java Swing | Java Swing Tutorial | Intellipaat
Java Swing For Beginners | What is Java Swing | Java Swing Tutorial | Intellipaat

Swing trong Java là gì?

Swing trong Java là một bộ công cụ Giao diện đồ họa người dùng (Graphical User Interface hay GUI) bao gồm các GUI component. Swing cung cấp một bộ widget và package phong phú để tạo các GUI component phức tạp cho các ứng dụng Java. Swing là một phần của Java Foundation Classes (JFC), một API cho các chương trình Java cung cấp GUI.

Thư viện Java Swing được xây dựng trên đầu Java Abstract Widget Toolkit (AWT), một bộ công cụ GUI cũ hơn và phụ thuộc và nền tảng (platform dependent). Bạn có thể sử dụng các component lập trình Java GUI như nút (button), hộp văn bản (textbox), v.v. từ thư viện và không phải tạo các component từ đầu.

Java Swing class Hierarchy Diagram

Tất cả các component trong Java Swing là JComponent có thể được thêm vào container class (lớp vùng chứa).

Difference between Java Swing and Java AWT

There are certain points from which Java Swing is different than Java AWT as mentioned below:

Java AWT is an API to develop GUI applications in Java.

Swing is a part of Java Foundation Classes and is used to create various applications.

Components of AWT are heavy weighted.

The components of Java Swing are lightweight.

Components are platform dependent.

Components are platform independent.

Execution Time is more than Swing.

Execution Time is less than AWT.

AWT components require java.awt package.

Swing components requires javax.swing package.

To know more about the topic, refer to Java Swing vs Java AWT.

Java GUI: Full Course ☕ (FREE)
Java GUI: Full Course ☕ (FREE)

Ví dụ Java Swing – kế thừa lớp JFrame

Chúng ta cũng có thể kế thừa lớp JFrame, vì vậy không cần phải tạo thể hiện của lớp JFrame.

package vn.viettuts.swing; import javax.swing.JButton; import javax.swing.JFrame; public class JavaSwingExample3 extends JFrame {// kế thừa lớp JFrame public JavaSwingExample3() { JButton b = new JButton(“click”);// tạo button b.setBounds(130, 50, 100, 40); add(b);// thêm button vào JFrame setSize(400, 200); setLayout(null); setVisible(true); } public static void main(String[] args) { new JavaSwingExample3(); } }

Java Swing Tutorial

Java Swing tutorial 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.

Difference between AWT and Swing

There are many differences between java awt and swing that are given below.

What is JFC

The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop applications.

Hierarchy of Java Swing classes

The hierarchy of java swing API is given below.

Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are given below.

Java Swing Examples

There are two ways to create a frame:

We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example

Let’s see a simple swing example where we are creating one button and adding it on the JFrame object inside the main() method.

File: FirstSwingExample.java

Example of Swing by Association inside constructor

We can also write all the codes of creating JFrame, JButton and method call inside the java constructor.

File: Simple.java

The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets the position of the button.

Simple example of Swing by inheritance

We can also inherit the JFrame class, so there is no need to create the instance of JFrame class explicitly.

File: Simple2.java

Next TopicJava JButton Class

Java Swing là một phần của Java Foundation Classes (JFC) được sử dụng để tạo các ứng dụng window-based. Nó được xây dựng trên API AWT (Abstract Windowing Toolkit) và được viết hoàn toàn bằng Java.

Không giống như AWT, Java Swing cung cấp các thành phần không phụ thuộc vào nền tảng và nhẹ hơn.

Gói javax.swing cung cấp các lớp cho java swing API như JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser, v.v.

Nội dung chính

Features Of Swing Class

  • Pluggable look and feel.
  • Uses MVC architecture.
  • Lightweight Components
  • Platform Independent
  • Advanced features such as JTable, JTabbedPane, JScollPane, etc.
  • Java is a platform-independent language and runs on any client machine, the GUI look and feel, owned and delivered by a platform-specific O/S, simply does not affect an application’s GUI constructed using Swing components.
  • Lightweight Components: Starting with the JDK 1.1, its AWT-supported lightweight component development. For a component to qualify as lightweight, it must not depend on any non-Java [O/s based) system classes. Swing components have their own view supported by Java’s look and feel classes.
  • Pluggable Look and Feel: This feature enable the user to switch the look and feel of Swing components without restarting an application. The Swing library supports components’ look and feels that remain the same across all platforms wherever the program runs. The Swing library provides an API that gives real flexibility in determining the look and feel of the GUI of an application
  • Highly customizable – Swing controls can be customized in a very easy way as visual appearance is independent of internal representation.
  • Rich controls– Swing provides a rich set of advanced controls like Tree TabbedPane, slider, colorpicker, and table controls.
JAVA - How To Design Login And Register Form In Java Netbeans
JAVA – How To Design Login And Register Form In Java Netbeans

Java


import


java.awt.*;


class


button {


button()


Frame f =


new


Frame();


Button b1 =


new


Button(


"OK"


);


b1.setBounds(


100


50


50


50


);


f.add(b1);


Button b2 =


new


Button(


"SUBMIT"


);


b2.setBounds(


100


101


50


50


);


f.add(b2);


Button b3 =


new


Button(


"CANCEL"


);


b3.setBounds(


100


150


80


50


);


f.add(b3);


f.setSize(


500


500


);


f.setLayout(


null


);


f.setVisible(


true


);


public


static


void


main(String a[]) {


new


button(); }

Output:
Example 3: Program to Add Checkbox in the Frame

Ví dụ về Java Swing

Có hai cách để tạo khung (Frame):

  • Bằng cách tạo đối tượng của lớp JFrame.
  • Bằng cách kế thừa lớp JFrame.

Chúng ta có thể viết code của Swing bên trong hàm main(), constructor hoặc bất kỳ phương thức nào khác.

Ví dụ Swing Java đơn giản

Chúng ta hãy xem một ví dụ swing đơn giản, nơi chúng ta đang tạo một button và thêm nó vào đối tượng JFrame bên trong phương thức main().

File: FirstSwingExample.java

package vn.viettuts.swing; import javax.swing.JButton; import javax.swing.JFrame; public class FirstSwingExample { public static void main(String[] args) { JFrame f = new JFrame();// tạo thể hiện của JFrame JButton b = new JButton(“click”);// tạo thể hiện của JButton b.setBounds(130, 50, 100, 40);// trục x , y , width, height f.setTitle(“Ví dụ Java Swing”); f.add(b);// thêm button vào JFrame f.setSize(400, 200);// thiết lập kích thước cho của sổ f.setLayout(null);// không sử dụng trình quản lý bố cục f.setVisible(true);// hiển thị cửa sổ } }

Kết quả:

Senior Programmers vs Junior Developers #shorts
Senior Programmers vs Junior Developers #shorts

Java GridBagLayout

It is the more sophisticated of all layouts. It aligns components by placing them within a grid of cells, allowing components to span more than one cell.

Step 8) Create chat frameHow about creating a chat frame like below?

Try to code yourself before looking at the program below.

//Usually you will require both swing and awt packages // even if you are working with just swings. import javax.swing.*; import java.awt.*; class gui { public static void main(String args[]) { //Creating the Frame JFrame frame = new JFrame(“Chat Frame”); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 400); //Creating the MenuBar and adding components JMenuBar mb = new JMenuBar(); JMenu m1 = new JMenu(“FILE”); JMenu m2 = new JMenu(“Help”); mb.add(m1); mb.add(m2); JMenuItem m11 = new JMenuItem(“Open”); JMenuItem m22 = new JMenuItem(“Save as”); m1.add(m11); m1.add(m22); //Creating the panel at bottom and adding components 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(tf); panel.add(send); panel.add(reset); // Text Area at the Center JTextArea ta = new JTextArea(); //Adding Components to the frame. frame.getContentPane().add(BorderLayout.SOUTH, panel); frame.getContentPane().add(BorderLayout.NORTH, mb); frame.getContentPane().add(BorderLayout.CENTER, ta); frame.setVisible(true); } }

How to Make a GUI in Java with Example

Now in this Java GUI Tutorial, let’s understand how to create a GUI in Java with Swings in Java examples.

Step 1) Copy code into an editorIn first step Copy the following code into an editor.

import javax.swing.*; class gui{ public static void main(String args[]){ JFrame frame = new JFrame(“My First GUI”); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); JButton button = new JButton(“Press”); frame.getContentPane().add(button); // Adds Button to content pane of frame frame.setVisible(true); } }

Step 2) Run the codeNext step, Save, Compile, and Run the code

Step 3) Copy following code into an editorNow let’s Add a Button to our frame. Copy following code into an editor from given Java UI Example

import javax.swing.*; class gui{ public static void main(String args[]){ JFrame frame = new JFrame(“My First GUI”); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); JButton button1 = new JButton(“Press”); frame.getContentPane().add(button1); frame.setVisible(true); } }

Step 4) Execute the code

Next, Execute the code. You will get a big button.

Step 5) Add two buttonsHow about adding two buttons? Copy the following code into an editor.

import javax.swing.*; class gui{ public static void main(String args[]){ JFrame frame = new JFrame(“My First GUI”); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); JButton button1 = new JButton(“Button 1”); JButton button2 = new JButton(“Button 2”); frame.getContentPane().add(button1); frame.getContentPane().add(button2); frame.setVisible(true); } }

Step 6) Save & Run the programNext, Save, Compile, and Run the program.

Step 7) Check outputUnexpected output =? Buttons are getting overlapped.

Java Anonymous Inner Classes Explained in 6 Minutes
Java Anonymous Inner Classes Explained in 6 Minutes

Lớp Container là gì?

Các lớp vùng chứa là các lớp có thể có các thành phần khác trên đó. Vì vậy, để tạo Java Swing GUI, chúng ta cần ít nhất một đối tượng container. Có 3 loại vùng chứa Java Swing.

  1. Bảng điều khiển : Nó là một vùng chứa thuần túy và bản thân nó không phải là một cửa sổ. Mục đích duy nhất của Panel là tổ chức các thành phần trên một cửa sổ.
  2. Khung : Đây là một cửa sổ hoạt động đầy đủ với tiêu đề và các biểu tượng.
  3. Hộp thoại : Nó có thể được coi như một cửa sổ bật lên bật ra khi một tin nhắn được hiển thị. Nó không phải là một cửa sổ hoạt động đầy đủ như Frame.

Java GridBagLayout

Đây là layout phức tạp nhất. Nó sắp xếp các component bằng cách đặt chúng trong một lưới ô, cho phép các component kéo dài nhiều hơn một ô.

Bước 8. Làm thế nào để tạo một chat frame như bên dưới?

Thử tự code trước khi nhìn vào lời giải bên dưới nhé!

//Usually you will require both swing and awt packages

// even if you are working with just swings.

import javax.swing.*;

import java.awt.*;

class gui {

public static void main(String args[]) {

//Creating the Frame

JFrame frame = new JFrame(“Chat Frame”);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(400, 400);

//Creating the MenuBar and adding components

JMenuBar mb = new JMenuBar();

JMenu m1 = new JMenu(“FILE”);

JMenu m2 = new JMenu(“Help”);

mb.add(m1);

mb.add(m2);

JMenuItem m11 = new JMenuItem(“Open”);

JMenuItem m22 = new JMenuItem(“Save as”);

m1.add(m11);

m1.add(m22);

//Creating the panel at bottom and adding components

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(tf);

panel.add(send);

panel.add(reset);

// Text Area at the Center

JTextArea ta = new JTextArea();

//Adding Components to the frame.

frame.getContentPane().add(BorderLayout.SOUTH, panel);

frame.getContentPane().add(BorderLayout.NORTH, mb);

frame.getContentPane().add(BorderLayout.CENTER, ta);

frame.setVisible(true);

Tổng hợp việc làm IT – Software trên VietnamWorksVietnamWorks InTECHTheo guru99

Create Java Application with JTable and Form using Swing GUI Builder of Netbeans IDE (+ Source Code)
Create Java Application with JTable and Form using Swing GUI Builder of Netbeans IDE (+ Source Code)

Kết luận:

Trong bài viết trên, chúng ta đã thảo luận về Java Swing là gì, hệ thống phân cấp các lớp Swing Java.

Với tất cả các thành phần đi kèm với Swing trong Java, việc xây dựng các ứng dụng GUI được tối ưu hóa trở nên dễ dàng hơn.

Hy vọng thông qua bài viết này các bạn đã hiểu về Swing và biết cách ứng dụng nó khi sử dụng ngôn ngữ lập trình Java.

Và nếu bạn muốn tìm hiểu rõ hơn ngôn ngữ này, có thể tham gia ngay khóa học lập trình Java của Ironhack Việt Nam

Chúc các bạn thành công.

See: Description

Interface Description
Action

The

BoundedRangeModel

Defines the data model used by components like

ButtonModel

State model for buttons.

CellEditor

This interface defines the methods any general editor should be able to implement.

ComboBoxEditor

The editor component used for JComboBox components.

ComboBoxModel

A data model for a combo box.

DesktopManager

DesktopManager objects are owned by a JDesktopPane object.

Icon

A small fixed size picture, typically used to decorate components.

JComboBox.KeySelectionManager

The interface that defines a

ListCellRenderer

Identifies components that can be used as “rubber stamps” to paint the cells in a JList.

ListModel

This interface defines the methods components like JList use to get the value of each cell in a list and the length of the list.

ListSelectionModel

This interface represents the current state of the selection for any of the components that display a list of values with stable indices.

MenuElement

Any component that can be placed into a menu should implement this interface.

MutableComboBoxModel

A mutable version of

Painter

A painting delegate.

Renderer

Defines the requirements for an object responsible for “rendering” (displaying) a value.

RootPaneContainer

This interface is implemented by components that have a single JRootPane child: JDialog, JFrame, JWindow, JApplet, JInternalFrame.

Scrollable

An interface that provides information to a scrolling container like JScrollPane.

ScrollPaneConstants

Constants used with the JScrollPane component.

SingleSelectionModel

A model that supports at most one indexed selection.

SpinnerModel

A model for a potentially unbounded sequence of object values.

SwingConstants

A collection of constants generally used for positioning and orienting components on the screen.

UIDefaults.ActiveValue

This class enables one to store an entry in the defaults table that’s constructed each time it’s looked up with one of the

UIDefaults.LazyValue

This class enables one to store an entry in the defaults table that isn’t constructed until the first time it’s looked up with one of the

WindowConstants

Constants used to control the window-closing operation.

Class Description
AbstractAction

This class provides default implementations for the JFC

AbstractButton

Defines common behaviors for buttons and menu items.

AbstractCellEditor

A base class for

AbstractListModel

The abstract definition for the data model that provides a

AbstractSpinnerModel

This class provides the ChangeListener part of the SpinnerModel interface that should be suitable for most concrete SpinnerModel implementations.

ActionMap
BorderFactory

Factory class for vending standard

Box

A lightweight container that uses a BoxLayout object as its layout manager.

Box.Filler

An implementation of a lightweight component that participates in layout but has no view.

BoxLayout

A layout manager that allows multiple components to be laid out either vertically or horizontally.

ButtonGroup

This class is used to create a multiple-exclusion scope for a set of buttons.

CellRendererPane

This class is inserted in between cell renderers and the components that use them.

ComponentInputMap
DebugGraphics

Graphics subclass supporting graphics debugging.

DefaultBoundedRangeModel

A generic implementation of BoundedRangeModel.

DefaultButtonModel

The default implementation of a

DefaultCellEditor

The default editor for table and tree cells.

DefaultComboBoxModel

The default model for combo boxes.

DefaultDesktopManager

This is an implementation of the

DefaultFocusManager

This class has been obsoleted by the 1.4 focus APIs.

DefaultListCellRenderer

Renders an item in a list.

DefaultListCellRenderer.UIResource

A subclass of DefaultListCellRenderer that implements UIResource.

DefaultListModel

This class loosely implements the

DefaultListSelectionModel

Default data model for list selections.

DefaultRowSorter

An implementation of

DefaultRowSorter.ModelWrapper
DefaultSingleSelectionModel

A generic implementation of SingleSelectionModel.

FocusManager

This class has been obsoleted by the 1.4 focus APIs.

GrayFilter

An image filter that “disables” an image by turning it into a grayscale image, and brightening the pixels in the image.

GroupLayout
ImageIcon

An implementation of the Icon interface that paints Icons from Images.

InputMap
InputVerifier

The purpose of this class is to help clients support smooth focus navigation through GUIs with text fields.

InternalFrameFocusTraversalPolicy

A FocusTraversalPolicy which can optionally provide an algorithm for determining a JInternalFrame’s initial Component.

JApplet

An extended version of

JButton

An implementation of a “push” button.

JCheckBox

An implementation of a check box — an item that can be selected or deselected, and which displays its state to the user.

JCheckBoxMenuItem

A menu item that can be selected or deselected.

JColorChooser
JComboBox

A component that combines a button or editable field and a drop-down list.

JComponent

The base class for all Swing components except top-level containers.

JDesktopPane

A container used to create a multiple-document interface or a virtual desktop.

JDialog

The main class for creating a dialog window.

JEditorPane

A text component to edit various kinds of content.

JFileChooser
JFormattedTextField
JFormattedTextField.AbstractFormatter

Instances of

JFormattedTextField.AbstractFormatterFactory

Instances of

JFrame

An extended version of

JInternalFrame

A lightweight object that provides many of the features of a native frame, including dragging, closing, becoming an icon, resizing, title display, and support for a menu bar.

JInternalFrame.JDesktopIcon

This component represents an iconified version of a

JLabel

A display area for a short text string or an image, or both.

JLayer
JLayeredPane
JList

A component that displays a list of objects and allows the user to select one or more items.

JList.DropLocation

A subclass of

JMenu

An implementation of a menu — a popup window containing

JMenuBar

An implementation of a menu bar.

JMenuItem

An implementation of an item in a menu.

JOptionPane
JPanel
JPasswordField
JPopupMenu

An implementation of a popup menu — a small window that pops up and displays a series of choices.

JPopupMenu.Separator

A popup menu-specific separator.

JProgressBar

A component that visually displays the progress of some task.

JRadioButton

An implementation of a radio button — an item that can be selected or deselected, and which displays its state to the user.

JRadioButtonMenuItem

An implementation of a radio button menu item.

JRootPane

A lightweight container used behind the scenes by

JScrollBar

An implementation of a scrollbar.

JScrollPane

Provides a scrollable view of a lightweight component.

JSeparator
JSlider

A component that lets the user graphically select a value by sliding a knob within a bounded interval.

JSpinner

A single line input field that lets the user select a number or an object value from an ordered sequence.

JSpinner.DateEditor

An editor for a

JSpinner.DefaultEditor

A simple base class for more specialized editors that displays a read-only view of the model’s current value with a

JSpinner.ListEditor

An editor for a

JSpinner.NumberEditor

An editor for a

JSplitPane
JTabbedPane

A component that lets the user switch between a group of components by clicking on a tab with a given title and/or icon.

JTable

The

JTable.DropLocation

A subclass of

JTextArea
JTextField
JTextPane

A text component that can be marked up with attributes that are represented graphically.

JToggleButton

An implementation of a two-state button.

JToggleButton.ToggleButtonModel

The ToggleButton model

JToolBar
JToolBar.Separator

A toolbar-specific separator.

JToolTip

Used to display a “Tip” for a Component.

JTree
JTree.DropLocation

A subclass of

JTree.DynamicUtilTreeNode
JTree.EmptySelectionModel
JViewport

The “viewport” or “porthole” through which you see the underlying information.

JWindow
KeyStroke

A KeyStroke represents a key action on the keyboard, or equivalent input device.

LayoutFocusTraversalPolicy

A SortingFocusTraversalPolicy which sorts Components based on their size, position, and orientation.

LayoutStyle
LookAndFeel
MenuSelectionManager

A MenuSelectionManager owns the selection in menu hierarchy.

OverlayLayout

A layout manager to arrange components over the top of each other.

Popup

Popups are used to display a

PopupFactory
ProgressMonitor

A class to monitor the progress of some operation.

ProgressMonitorInputStream

Monitors the progress of reading from some InputStream.

RepaintManager

This class manages repaint requests, allowing the number of repaints to be minimized, for example by collapsing multiple requests into a single repaint for members of a component tree.

RowFilter
RowFilter.Entry

An

RowSorter
RowSorter.SortKey

SortKey describes the sort order for a particular column.

ScrollPaneLayout

The layout manager used by

ScrollPaneLayout.UIResource

The UI resource version of

SizeRequirements

For the convenience of layout managers, calculates information about the size and position of components.

SizeSequence
SortingFocusTraversalPolicy

A FocusTraversalPolicy that determines traversal order by sorting the Components of a focus traversal cycle based on a given Comparator.

SpinnerDateModel
SpinnerListModel

A simple implementation of

SpinnerNumberModel
Spring

An instance of the

SpringLayout
SpringLayout.Constraints
SwingUtilities

A collection of utility methods for Swing.

SwingWorker

An abstract class to perform lengthy GUI-interaction tasks in a background thread.

Timer

Fires one or more

ToolTipManager

Manages all the

TransferHandler

This class is used to handle the transfer of a

TransferHandler.DropLocation

Represents a location where dropped data should be inserted.

TransferHandler.TransferSupport

This class encapsulates all relevant details of a clipboard or drag and drop transfer, and also allows for customizing aspects of the drag and drop experience.

UIDefaults

A table of defaults for Swing components.

UIDefaults.LazyInputMap
UIDefaults.ProxyLazyValue

This class provides an implementation of

UIManager
UIManager.LookAndFeelInfo

Provides a little information about an installed

ViewportLayout

The default layout manager for

Enum Description
DropMode

Drop modes, used to determine the method by which a component tracks and indicates a drop location during drag and drop.

GroupLayout.Alignment

Enumeration of the possible ways

JTable.PrintMode

Printing modes, used in printing

LayoutStyle.ComponentPlacement
RowFilter.ComparisonType

Enumeration of the possible comparison values supported by some of the default

SortOrder

SortOrder is an enumeration of the possible sort orderings.

SwingWorker.StateValue

Values for the

Exception Description
UnsupportedLookAndFeelException

An exception that indicates the requested look & feel management classes are not present on the user’s system.

Provides a set of “lightweight” (all-Java language) components that, to the maximum degree possible, work the same on all platforms. For a programmer’s guide to using these components, see Creating a GUI with JFC/Swing, a trail in The Java Tutorial. For other resources, see Related Documentation.

Typical Swing applications do processing in response to an event
generated from a user gesture. For example, clicking on a

JButton

notifies all

ActionListeners

added to the

JButton

. As all events generated from a user gesture are
dispatched on the event dispatching thread, most developers are not
impacted by the restriction.

Where the impact lies, however, is in constructing and showing a
Swing application. Calls to an application’s

main

method,
or methods in

Applet

, are not invoked on the event
dispatching thread. As such, care must be taken to transfer control
to the event dispatching thread when constructing and showing an
application or applet. The preferred way to transfer control and begin
working with Swing is to use

invokeLater

. The

invokeLater

method schedules a

Runnable

to be processed on
the event dispatching thread. The following two examples work equally
well for transferring control and starting up a Swing application:

public class MyApp implements Runnable { public void run() { // Invoked on the event dispatching thread. // Construct and show GUI. } public static void main(String[] args) { SwingUtilities.invokeLater(new MyApp(args)); } }Or:

public class MyApp { MyApp(String[] args) { // Invoked on the event dispatching thread. Do any initialization // here. } public void show() { // Show the UI. } public static void main(final String[] args) { // Schedule a job for the event-dispatching thread: // creating and showing this application’s GUI. SwingUtilities.invokeLater(new Runnable() { public void run() { new MyApp(args).show(); } }); } }This restriction also applies to models attached to Swing components. For example, if a


TableModelis attached to a


JTable, the


TableModelshould only be modified on the event dispatching thread. If you modify the model on a separate thread you run the risk of exceptions and possible display corruption.

As all events are delivered on the event dispatching thread, care must
be taken in event processing. In particular, a long running task, such
as network io or computational intensive processing, executed on the
event dispatching thread blocks the event dispatching thread from
dispatching any other events. While the event dispatching thread is
blocked the application is completely unresponsive to user
input. Refer to

SwingWorker

for the preferred way to do such
processing when working with Swing.

More information on this topic can be found in the Swing tutorial, in particular the section on How to Use Threads.

For overviews, tutorials, examples, guides, and other documentation, please see:

Submit a bug or feature For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.Copyright © 1993, 2020, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

Java


import


java.io.*;


import


javax.swing.*;


class


GFG {


public


static


void


main(String[] args)


JFrame frame =


new


JFrame();


JButton button =


new


JButton(


" GFG WebSite Click"


);


button.setBounds(


150


200


220


50


);


frame.add(button);


frame.setSize(


500


600


);


frame.setLayout(


null


);


frame.setVisible(


true


);

Output:
Example 2: Write a program to create three buttons with caption OK, SUBMIT, CANCEL.
Create your First Java Frame using Visual Studio Code | Create Java GUI Forms using VS Code
Create your First Java Frame using Visual Studio Code | Create Java GUI Forms using VS Code

Java GridBagLayout

Nó là phức tạp hơn của tất cả các bố cục. Nó sắp xếp các thành phần bằng cách đặt chúng trong một lưới ô, cho phép các thành phần kéo dài nhiều hơn một ô.

Java GridBagLayout

Bước 8) Tạo khung trò chuyện

Còn cách tạo khung trò chuyện như bên dưới?

Hãy thử tự viết mã trước khi xem chương trình bên dưới.


//Usually you will require both swing and awt packages // even if you are working with just swings. import javax.swing.*; import java.awt.*; class gui { public static void main(String args[]) { //Creating the Frame JFrame frame = new JFrame("Chat Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 400); //Creating the MenuBar and adding components JMenuBar mb = new JMenuBar(); JMenu m1 = new JMenu("FILE"); JMenu m2 = new JMenu("Help"); mb.add(m1); mb.add(m2); JMenuItem m11 = new JMenuItem("Open"); JMenuItem m22 = new JMenuItem("Save as"); m1.add(m11); m1.add(m22); //Creating the panel at bottom and adding components 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(tf); panel.add(send); panel.add(reset); // Text Area at the Center JTextArea ta = new JTextArea(); //Adding Components to the frame. frame.getContentPane().add(BorderLayout.SOUTH, panel); frame.getContentPane().add(BorderLayout.NORTH, mb); frame.getContentPane().add(BorderLayout.CENTER, ta); frame.setVisible(true); } }

Bạn có thể tham khảo thêm thông tin về java tại Blog của T3H và đăng ký khóa học lập trình phù hợp với nhu cầu với mức giá ưu đãi nhất!

Java Swing Tutorial: How to Create a GUI Application in Java

Ứng dụng của Java Swing

Java Swing được dùng để hỗ trợ tạo giao diện đồ hoạ người dùng (với Java).

Bộ công cụ này cung cấp các bộ điều khiển nâng cao như thanh trượt, colorpicker, Tree, TabbedPane và bảng điều khiển,..

Swing có những đặc điểm:

  • Độc lập với thiết bị
  • Có thể tuỳ chỉnh, mở rộng
  • Khá nhẹ
  • Có thể cấu hình

Ngoài ra bạn cũng có thể tùy chỉnh các điều khiển xoay một cách dễ dàng mà không ảnh hưởng đến các thành phần khác.

Ever wondered how Batiks were made!? Look no Further!! Tour the Hoffman Batik factory in Bali!
Ever wondered how Batiks were made!? Look no Further!! Tour the Hoffman Batik factory in Bali!

Ví dụ Java Swing – tạo đối tượng của lớp JFrame

Chúng ta cũng có thể viết tất cả các mã tạo JFrame, JButton bên trong constructor.

package vn.viettuts.swing; import javax.swing.JButton; import javax.swing.JFrame; public class JavaSwingExample2 { JFrame f; public JavaSwingExample2() { f = new JFrame();// tạo thể hiện của JFrame JButton b = new JButton(“click”);// tạo thể hiện của JButton b.setBounds(130, 50, 100, 40); f.add(b);// thêm button vào JFrame f.setSize(400, 200);// thiết lập kích thước cho của sổ f.setLayout(null);// không sử dụng trình quản lý bố cục f.setVisible(true);// hiển thị cửa sổ } }

Java


import


java.awt.*;


class


Lan {


Lan()


Frame f =


new


Frame();


Label l1 =


new


Label(


"Select known Languages"


);


l1.setBounds(


100


50


120


80


);


f.add(l1);


Checkbox c2 =


new


Checkbox(


"Hindi"


);


c2.setBounds(


100


150


50


50


);


f.add(c2);


Checkbox c3 =


new


Checkbox(


"English"


);


c3.setBounds(


100


200


80


50


);


f.add(c3);


Checkbox c4 =


new


Checkbox(


"marathi"


);


c4.setBounds(


100


250


80


50


);


f.add(c4);


f.setSize(


500


500


);


f.setLayout(


null


);


f.setVisible(


true


);


public


static


void


main(String ar[]) {


new


Lan(); }

Output:
Full Course of Swing in Java | Java GUI | Advanced Java |Hindi
Full Course of Swing in Java | Java GUI | Advanced Java |Hindi

The MVC Connection

  • In general, a visual component is a composite of three distinct aspects:

    1. The way that the component looks when rendered on the screen.
    2. The way such that the component reacts to the user.
    3. The state information associated with the component.
  • Over the years, one component architecture has proven itself to be exceptionally effective: – Model-View-Controller or MVC for short.
  • In MVC terminology, the model corresponds to the state information associated with the Component.
  • The view determines how the component is displayed on the screen, including any aspects of the view that are affected by the current state of the model.
  • The controller determines how the component reacts to the user.

The simplest Swing components have capabilities far beyond AWT components as follows:

  • Swing buttons and labels can be displaying images instead of or in addition to text.
  • The borders around most Swing components can be changed easily. For example, it is easy to put a 1-pixel border around the outside of a Swing label.
  • Swing components do not have to be rectangular. Buttons, for example, can be round.
  • Now The Latest Assertive technologies such as screen readers can easily get information from Swing components. Example: A screen reader tool can easily capture the text that is displayed on a Swing button or label.

Cấu trúc phân cấp lớp Java Swing

Phân cấp của API Java swing như liệt kê ở hình dưới đây:

Phân cấp API Java swing

Chú thích: Tất cả các thành phần trong swing được kế thừa từ lớp Jcomponent như JButton, JComboBox, JList, JLabel đều có thể được thêm vào lớp Container.

Container là các window như Frame và Dialog. Các container này chỉ có thể thêm một thành phần vào chính nó.

Inner Class Java Tutorial - Creating and Using Inner Classes
Inner Class Java Tutorial – Creating and Using Inner Classes

FAQs

Here are some frequently asked questions related to Java Swing:

Q1: How is Java Swing is different from AWT?Ans: Unlike AWT, which is based on native components and has limited customization options, Swing is entirely written in Java and offers a higher degree of customization and control over the appearance and behavior of components.

Q2: What are the main components of Java Swing?Ans: Java Swing provides a wide range of components for creating GUI applications, including buttons, labels, text fields, checkboxes, radio buttons, menus, and many others.

Q3: How do I create a basic GUI application using Java Swing?Ans: To create a basic GUI application using Java Swing, you will typically create a JFrame object to serve as the main window and add various components to it using layout managers. You can then set the properties of the components and add event handlers to respond to user interactions.

Q4: How do layout managers in Java Swing work?Ans: Each layout manager in Java Swing works in a slightly different way, but they all allow you to specify the position and size of components relative to each other and to the container. For example, the BorderLayout manager arranges components in five regions (north, south, east, west, and center) and allows you to specify the preferred size of each component using the BorderLayout constants.

Java Swing và những điều mà bạn chưa biết

08/02/2022 09:25

Swing trong Java là một bộ công cụ Giao diện Người dùng Đồ họa (GUI) bao gồm các thành phần GUI. Swing cung cấp một bộ widget và gói phong phú để tạo ra các thành phần GUI tinh vi cho các ứng dụng Java. Swing là một phần của Java Foundation Classes (JFC), là một API để lập trình Java GUI cung cấp GUI.

Thư viện Java Swing được xây dựng dựa trên Bộ công cụ tiện ích con trừu tượng Java ( AWT ), một bộ công cụ GUI phụ thuộc vào nền tảng cũ hơn. Bạn có thể sử dụng các thành phần lập trình GUI đơn giản của Java như nút, hộp văn bản, v.v., từ thư viện và không phải tạo các thành phần từ đầu.

Sự khác biệt giữa AWT và Swing

No. Java AWT Java Swing
1) Phụ thuộc nền tảng (Platform Dependent) Độc lập với nền tảng (Platform Independent)
2) Thành phần của AWT nặng Thành phần của Swing khá nhẹ
3) AWT không hỗ trợ pluggable look and feel. Swing hỗ trợ pluggable look and feel.
4) AWT có ít thành phần hơn Swing Swing cung cấp nhiều thành phần và các thành phần cũng mạnh mẽ hơn AWT như: bảng, danh sách, cuộn màn hình, trình chọn màu,..
5) AWT không tuân theo cấu trúc MVC (Model View Controller) Swing theo cấu trúc MVC
LOGIN Form with MYSQL Database JDBC | JAVA SWING GUI
LOGIN Form with MYSQL Database JDBC | JAVA SWING GUI

Các phương thức thường dùng của lớp Component

Các phương thức của lớp Component được sử dụng rộng rãi trong java swing được đưa ra dưới đây.

Phương thức Mô tả
public void add(Component c) thêm một thành phần vào thành phần khác.
public void setSize(int width, int height) thiết lập kích thước của thành phần.
public void setLayout(LayoutManager m) thiết lập trình quản lý bố cục (layout) cho thành phần.
public void setVisible(boolean b) thiết lập khả năng hiển thị của thành phần. Nó theo mặc định là false (ẩn)

Cách tạo GUI trong Java với ví dụ

Bây giờ trong Hướng dẫn Java GUI này, chúng ta hãy hiểu cách tạo GUI trong Java với các ví dụ Swings trong Java.

Bước 1) Sao chép mã vào trình

chỉnh sửa Trong bước đầu tiên, Sao chép mã sau vào trình chỉnh sửa.


import javax.swing.*; class gui{ public static void main(String args[]){ JFrame frame = new JFrame("My First GUI"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); JButton button = new JButton("Press"); frame.getContentPane().add(button); // Adds Button to content pane of frame frame.setVisible(true); } }

Bước 2) Chạy mã

Bước tiếp theo, Lưu, Biên dịch và Chạy mã

Bước 3) Sao chép đoạn mã sau vào một trình soạn thảo

Bây giờ hãy Thêm một nút vào khung của chúng ta. Sao chép mã sau vào một trình soạn thảo từ Ví dụ về giao diện người dùng Java nhất định


import javax.swing.*; class gui{ public static void main(String args[]){ JFrame frame = new JFrame("My First GUI"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); JButton button1 = new JButton("Press"); frame.getContentPane().add(button1); frame.setVisible(true); } }

Bước 4) Thực thi mã

Tiếp theo, Thực thi mã. Bạn sẽ nhận được một nút lớn.

Bước 5) Thêm hai nút

Làm thế nào về việc thêm hai nút? Sao chép mã sau vào một trình chỉnh sửa.


import javax.swing.*; class gui{ public static void main(String args[]){ JFrame frame = new JFrame("My First GUI"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); JButton button1 = new JButton("Button 1"); JButton button2 = new JButton("Button 2"); frame.getContentPane().add(button1); frame.getContentPane().add(button2); frame.setVisible(true); } }

Bước 6) Lưu & Chạy chương trình

Tiếp theo, Lưu, Biên dịch và Chạy chương trình.

Bước 7) Kiểm tra đầu ra Đầu ra

không mong muốn =? Các nút đang bị chồng lên nhau.

>>> Tham khảo: Khóa học lập trình Java

#1 Java Swing Tutorial | JFrame in Java Swing
#1 Java Swing Tutorial | JFrame in Java Swing

Sự khác nhau giữa AWT và Swing

Có rất nhiều sự khác biệt giữa java awt và swing được đưa ra dưới đây.

No. Java AWT Java Swing
1) Các thành phần AWT là phụ thuộc nền tảng. Các thành phần Java swing là độc lập nền tảng.
2) Các thành phần AWT là nặng. Các thành phần Swing là nhẹ.
3) AWT không hỗ trợ plugin. Swing có hỗ trợ plugin.
4) AWT cung cấp ít thành phần hơn Swing. Swing cung cấp nhiều thành phần mạnh mẽ hơn AWT như tables, lists, scrollpanes, colorchooser, tabbedpane, vv.
5) AWT không tuân theo MVC(Model View Controller) trong đó model biểu diễn data, view biểu diễn hiển thị và controller biểu diễn các action để kết nối model với view. Swing tuân theo mô hình MVC.

Full Stack Web Development Internship Program

  • 29k Enrolled Learners
  • Weekend/Weekday
  • Live Class

Swing in java is part of Java foundation class which is lightweight and platform independent. It is used for creating window based applications. It includes components like button, scroll bar, text field etc. Putting together all these components makes a graphical user interface. In this article, we will go through the concepts involved in the process of building applications using swing in Java. Following are the concepts discussed in this article:

Swing in Java is a lightweight GUI toolkit which has a wide variety of widgets for building optimized window based applications. It is a part of the JFC( Java Foundation Classes). It is build on top of the AWT API and entirely written in java. It is platform independent unlike AWT and has lightweight components.

It becomes easier to build applications since we already have GUI components like button, checkbox etc. This is helpful because we do not have to start from the scratch.

Any class which has other components in it is called as a container class. For building GUI applications at least one container class is necessary.

Following are the three types of container classes:

Panel – It is used to organize components on to a window

Frame – A fully functioning window with icons and titles

Dialog – It is like a pop up window but not fully functional like the frame

AWT SWING

Explanation: All the components in swing like JButton, JComboBox, JList, JLabel are inherited from the JComponent class which can be added to the container classes. Containers are the windows like frame and dialog boxes. Basic swing components are the building blocks of any gui application. Methods like setLayout override the default layout in each container. Containers like JFrame and JDialog can only add a component to itself. Following are a few components with examples to understand how we can use them.

It is used to create a labelled button. Using the ActionListener it will result in some action when the button is pushed. It inherits the AbstractButton class and is platform independent.

Example:

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); } }

Output:

It inherits the JTextComponent class and it is used to allow editing of single line text.

Example:

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); } }

Output:

It is used to add scroll bar, both horizontal and vertical.

Example:

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(); } }

Output:

It inherits the JComponent class and provides space for an application which can attach any other component.

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(); } }

Output:

It inherits the JMenuItem class, and is a pull down menu component which is displayed from the menu bar.

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(); } }

Output:

It inherits JComponent class, the object of JList class represents a list of text items.

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(); } }

Output:

It is used for placing text in a container. It also inherits JComponent class.

import javax.swing.*; public class Example{ public static void main(String args[]) { JFrame a = new JFrame(“example”); JLabel b1; b1 = new JLabel(“edureka”); b1.setBounds(40,40,90,20); a.add(b1); a.setSize(400,400); a.setLayout(null); a.setVisible(true); } }

Output:

It inherits the JComponent class and is used to show pop up menu of choices.

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(); } }

Output:

To arrange the components inside a container we use the layout manager. Following are several layout managers:

Border layout

Flow layout

GridBag layout

The default layout manager for every JFrame is BorderLayout. It places components in upto five places which is top, bottom, left, right and center.

FlowLayout simply lays the components in a row one after the other, it is the default layout manager for every JPanel.

GridBagLayout places the components in a grid which allows the components to span more than one cell.

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); } }

This is a simple example for creating a GUI using swing in Java.

If you’re just beginning, then watch at this Java Tutorial to Understand the Fundamental Java Concepts.

In this article we have discussed swing in Java and hierarchy of Java swing classes. With all the components which comes with swing in Java, it becomes easier to build optimized GUI applications. Java programming language is a structured programming language and with the increasing demand it becomes extremely important to master all the concepts in Java programming. To kick-start your learning and to become an expert in java programming, enroll to Edureka’s Java Certification program.

Got a question for us? please mention this in the comments section of this ‘Swing In Java’ article and we will get back to you as soon as possible.

Course Name Date Details
Java Certification Training Course

Class Starts on 24th February,2024

24th February

SAT&SUN (Weekend Batch)

View Details
Java Certification Training Course

Class Starts on 30th March,2024

30th March

SAT&SUN (Weekend Batch)

View Details

edureka.co

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don’t take advantage of improvements introduced in later releases and might use technology no longer available.See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

This section explains how to compile and run a Swing application from the command line. For information on compiling and running a Swing application using NetBeans IDE, see Running Tutorial Examples in NetBeans IDE. The compilation instructions work for all Swing programs applets, as well as applications. Here are the steps you need to follow:

You can download the latest release of the JDK for free from http://www.oracle.com/technetwork/java/javase/downloads/index.html.

You can use a simple program we provide, called HelloWorldSwing, that brings up the GUI shown in the figure below. The program is in a single file,

HelloWorldSwing.java

. When you save this file, you must match the spelling and capitalization of its name exactly.

The

HelloWorldSwing.java

example, like all of our Swing tutorial examples, is created inside a package. If you look at the source code, you see the following line at the beginning of the file:

package start;

This means you must put the

HelloWorldSwing.java

file inside of a

start

directory. You compile and run the example from the directory above the

start

directory. The tutorial examples from the Using Swing Components lesson are inside of a

components

package and the examples from the Writing Event Listeners lesson are inside a

events

package, and so on. For more information, you might want to see the

Packages

lesson.

Your next step is to compile the program. To compile the example, from the directory above the

HelloWorldSwing.java

file:

javac start/HelloWorldSwing.java

If you prefer, you may compile the example from within the

start

directory:

javac HelloWorldSwing.java

but you must remember to leave the

start

directory to execute the program.

If you are unable to compile, make sure you are using the compiler in a recent release of the Java platform. You can verify the version of your compiler or Java Runtime Environment (JRE) using these commands

javac -version java -version

Once you’ve updated your JDK, you should be able to use the programs in this trail without changes. Another common mistake is installing the JRE and not the full Java Development Kit (JDK) needed to compile these programs. Refer to the Getting Started trail to help you solve any compiling problems you encounter. Another resource is the Troubleshooting Guide for Java™ SE 6 Desktop Technologies.

After you compile the program successfully, you can run it. From the directory above the

start

directory:

java start.HelloWorldSwing

Package Description
java.awt.im.spi

Provides interfaces that enable the development of input methods that can be used with any Java runtime environment.

javax.swing

Provides a set of “lightweight” (all-Java language) components that, to the maximum degree possible, work the same on all platforms.

javax.swing.border

Provides classes and interface for drawing specialized borders around a Swing component.

javax.swing.colorchooser

Contains classes and interfaces used by the

javax.swing.event

Provides for events fired by Swing components.

javax.swing.filechooser

Contains classes and interfaces used by the

javax.swing.plaf

Provides one interface and many abstract classes that Swing uses to provide its pluggable look-and-feel capabilities.

javax.swing.plaf.basic

Provides user interface objects built according to the Basic look and feel.

javax.swing.plaf.metal

Provides user interface objects built according to the Java look and feel (once codenamed Metal), which is the default look and feel.

javax.swing.plaf.multi

Provides user interface objects that combine two or more look and feels.

javax.swing.plaf.nimbus

Provides user interface objects built according to the cross-platform Nimbus look and feel.

javax.swing.plaf.synth

Synth is a skinnable look and feel in which all painting is delegated.

javax.swing.table

Provides classes and interfaces for dealing with

javax.swing.text

Provides classes and interfaces that deal with editable and noneditable text components.

javax.swing.text.html

Provides the class

javax.swing.tree

Provides classes and interfaces for dealing with

Class and Description
JFrame

An extended version of

Class and Description
AbstractButton

Defines common behaviors for buttons and menu items.

AbstractButton.AccessibleAbstractButton

This class implements accessibility support for the

AbstractCellEditor

A base class for

AbstractListModel

The abstract definition for the data model that provides a

AbstractSpinnerModel

This class provides the ChangeListener part of the SpinnerModel interface that should be suitable for most concrete SpinnerModel implementations.

Action

The

ActionMap
BoundedRangeModel

Defines the data model used by components like

Box

A lightweight container that uses a BoxLayout object as its layout manager.

ButtonGroup

This class is used to create a multiple-exclusion scope for a set of buttons.

ButtonModel

State model for buttons.

CellEditor

This interface defines the methods any general editor should be able to implement.

ComboBoxEditor

The editor component used for JComboBox components.

ComboBoxModel

A data model for a combo box.

ComponentInputMap
DefaultButtonModel

The default implementation of a

DefaultCellEditor.EditorDelegate

The protected

DefaultListCellRenderer

Renders an item in a list.

DefaultRowSorter.ModelWrapper
DesktopManager

DesktopManager objects are owned by a JDesktopPane object.

DropMode

Drop modes, used to determine the method by which a component tracks and indicates a drop location during drag and drop.

FocusManager

This class has been obsoleted by the 1.4 focus APIs.

GroupLayout.Alignment

Enumeration of the possible ways

GroupLayout.Group
GroupLayout.ParallelGroup
GroupLayout.SequentialGroup
Icon

A small fixed size picture, typically used to decorate components.

InputMap
InputVerifier

The purpose of this class is to help clients support smooth focus navigation through GUIs with text fields.

InternalFrameFocusTraversalPolicy

A FocusTraversalPolicy which can optionally provide an algorithm for determining a JInternalFrame’s initial Component.

JButton

An implementation of a “push” button.

JCheckBox

An implementation of a check box — an item that can be selected or deselected, and which displays its state to the user.

JColorChooser
JComboBox

A component that combines a button or editable field and a drop-down list.

JComboBox.KeySelectionManager

The interface that defines a

JComponent

The base class for all Swing components except top-level containers.

JComponent.AccessibleJComponent

Inner class of JComponent used to provide default support for accessibility.

JDesktopPane

A container used to create a multiple-document interface or a virtual desktop.

JDialog

The main class for creating a dialog window.

JEditorPane

A text component to edit various kinds of content.

JEditorPane.AccessibleJEditorPane

This class implements accessibility support for the

JFormattedTextField
JFormattedTextField.AbstractFormatter

Instances of

JFormattedTextField.AbstractFormatterFactory

Instances of

JInternalFrame

A lightweight object that provides many of the features of a native frame, including dragging, closing, becoming an icon, resizing, title display, and support for a menu bar.

JInternalFrame.JDesktopIcon

This component represents an iconified version of a

JLabel

A display area for a short text string or an image, or both.

JLayeredPane
JList

A component that displays a list of objects and allows the user to select one or more items.

JList.DropLocation

A subclass of

JMenu

An implementation of a menu — a popup window containing

JMenu.WinListener

A listener class that watches for a popup window closing.

JMenuBar

An implementation of a menu bar.

JMenuItem

An implementation of an item in a menu.

JMenuItem.AccessibleJMenuItem

This class implements accessibility support for the

JPanel
JPopupMenu

An implementation of a popup menu — a small window that pops up and displays a series of choices.

JRootPane

A lightweight container used behind the scenes by

JScrollBar

An implementation of a scrollbar.

JScrollPane

Provides a scrollable view of a lightweight component.

JSeparator
JSpinner

A single line input field that lets the user select a number or an object value from an ordered sequence.

JSpinner.DefaultEditor

A simple base class for more specialized editors that displays a read-only view of the model’s current value with a

JTable

The

JTable.DropLocation

A subclass of

JTable.PrintMode

Printing modes, used in printing

JTextField
JTextField.AccessibleJTextField

This class implements accessibility support for the

JToggleButton

An implementation of a two-state button.

JToggleButton.AccessibleJToggleButton

This class implements accessibility support for the

JToolTip

Used to display a “Tip” for a Component.

JTree
JTree.DropLocation

A subclass of

JTree.EmptySelectionModel
JTree.TreeSelectionRedirector

Handles creating a new

JViewport

The “viewport” or “porthole” through which you see the underlying information.

JViewport.ViewListener

A listener for the view.

KeyStroke

A KeyStroke represents a key action on the keyboard, or equivalent input device.

LayoutStyle
LayoutStyle.ComponentPlacement
ListCellRenderer

Identifies components that can be used as “rubber stamps” to paint the cells in a JList.

ListModel

This interface defines the methods components like JList use to get the value of each cell in a list and the length of the list.

ListSelectionModel

This interface represents the current state of the selection for any of the components that display a list of values with stable indices.

LookAndFeel
MenuElement

Any component that can be placed into a menu should implement this interface.

MenuSelectionManager

A MenuSelectionManager owns the selection in menu hierarchy.

MutableComboBoxModel

A mutable version of

Popup

Popups are used to display a

PopupFactory
ProgressMonitor

A class to monitor the progress of some operation.

RepaintManager

This class manages repaint requests, allowing the number of repaints to be minimized, for example by collapsing multiple requests into a single repaint for members of a component tree.

RootPaneContainer

This interface is implemented by components that have a single JRootPane child: JDialog, JFrame, JWindow, JApplet, JInternalFrame.

RowFilter
RowFilter.ComparisonType

Enumeration of the possible comparison values supported by some of the default

RowFilter.Entry

An

RowSorter
RowSorter.SortKey

SortKey describes the sort order for a particular column.

Scrollable

An interface that provides information to a scrolling container like JScrollPane.

ScrollPaneConstants

Constants used with the JScrollPane component.

ScrollPaneLayout

The layout manager used by

SingleSelectionModel

A model that supports at most one indexed selection.

SizeRequirements

For the convenience of layout managers, calculates information about the size and position of components.

SortingFocusTraversalPolicy

A FocusTraversalPolicy that determines traversal order by sorting the Components of a focus traversal cycle based on a given Comparator.

SortOrder

SortOrder is an enumeration of the possible sort orderings.

SpinnerDateModel
SpinnerListModel

A simple implementation of

SpinnerModel

A model for a potentially unbounded sequence of object values.

SpinnerNumberModel
Spring

An instance of the

SpringLayout.Constraints
SwingConstants

A collection of constants generally used for positioning and orienting components on the screen.

SwingWorker.StateValue

Values for the

ToolTipManager

Manages all the

TransferHandler

This class is used to handle the transfer of a

TransferHandler.DropLocation

Represents a location where dropped data should be inserted.

TransferHandler.TransferSupport

This class encapsulates all relevant details of a clipboard or drag and drop transfer, and also allows for customizing aspects of the drag and drop experience.

UIDefaults

A table of defaults for Swing components.

UIDefaults.LazyValue

This class enables one to store an entry in the defaults table that isn’t constructed until the first time it’s looked up with one of the

UIManager.LookAndFeelInfo

Provides a little information about an installed

UnsupportedLookAndFeelException

An exception that indicates the requested look & feel management classes are not present on the user’s system.

WindowConstants

Constants used to control the window-closing operation.

Class and Description
Icon

A small fixed size picture, typically used to decorate components.

Class and Description
Icon

A small fixed size picture, typically used to decorate components.

JColorChooser
JComponent

The base class for all Swing components except top-level containers.

JPanel
Class and Description
JComponent

The base class for all Swing components except top-level containers.

JInternalFrame

A lightweight object that provides many of the features of a native frame, including dragging, closing, becoming an icon, resizing, title display, and support for a menu bar.

MenuElement

Any component that can be placed into a menu should implement this interface.

MenuSelectionManager

A MenuSelectionManager owns the selection in menu hierarchy.

RowSorter
Class and Description
Icon

A small fixed size picture, typically used to decorate components.

Class and Description
ActionMap
ComponentInputMap
Icon

A small fixed size picture, typically used to decorate components.

InputMap
JButton

An implementation of a “push” button.

JComboBox

A component that combines a button or editable field and a drop-down list.

JComponent

The base class for all Swing components except top-level containers.

JFileChooser
JLayer
JList

A component that displays a list of objects and allows the user to select one or more items.

JOptionPane
JPopupMenu

An implementation of a popup menu — a small window that pops up and displays a series of choices.

JSplitPane
JTabbedPane

A component that lets the user switch between a group of components by clicking on a tab with a given title and/or icon.

JTree
Popup

Popups are used to display a

Class and Description
AbstractAction

This class provides default implementations for the JFC

AbstractButton

Defines common behaviors for buttons and menu items.

AbstractListModel

The abstract definition for the data model that provides a

Action

The

ActionMap
BoxLayout

A layout manager that allows multiple components to be laid out either vertically or horizontally.

CellRendererPane

This class is inserted in between cell renderers and the components that use them.

ComboBoxEditor

The editor component used for JComboBox components.

ComboBoxModel

A data model for a combo box.

DesktopManager

DesktopManager objects are owned by a JDesktopPane object.

Icon

A small fixed size picture, typically used to decorate components.

JButton

An implementation of a “push” button.

JColorChooser
JComboBox

A component that combines a button or editable field and a drop-down list.

JComponent

The base class for all Swing components except top-level containers.

JDesktopPane

A container used to create a multiple-document interface or a virtual desktop.

JFileChooser
JFrame

An extended version of

JInternalFrame

A lightweight object that provides many of the features of a native frame, including dragging, closing, becoming an icon, resizing, title display, and support for a menu bar.

JInternalFrame.JDesktopIcon

This component represents an iconified version of a

JLabel

A display area for a short text string or an image, or both.

JList

A component that displays a list of objects and allows the user to select one or more items.

JMenu

An implementation of a menu — a popup window containing

JMenuBar

An implementation of a menu bar.

JMenuItem

An implementation of an item in a menu.

JOptionPane
JPanel
JPopupMenu

An implementation of a popup menu — a small window that pops up and displays a series of choices.

JProgressBar

A component that visually displays the progress of some task.

JRootPane

A lightweight container used behind the scenes by

JScrollBar

An implementation of a scrollbar.

JScrollPane

Provides a scrollable view of a lightweight component.

JSeparator
JSlider

A component that lets the user graphically select a value by sliding a knob within a bounded interval.

JSpinner

A single line input field that lets the user select a number or an object value from an ordered sequence.

JSplitPane
JTabbedPane

A component that lets the user switch between a group of components by clicking on a tab with a given title and/or icon.

JTable

The

JTextField
JToolBar
JTree
JTree.DropLocation

A subclass of

KeyStroke

A KeyStroke represents a key action on the keyboard, or equivalent input device.

ListCellRenderer

Identifies components that can be used as “rubber stamps” to paint the cells in a JList.

ListModel

This interface defines the methods components like JList use to get the value of each cell in a list and the length of the list.

ListSelectionModel

This interface represents the current state of the selection for any of the components that display a list of values with stable indices.

LookAndFeel
MenuElement

Any component that can be placed into a menu should implement this interface.

MenuSelectionManager

A MenuSelectionManager owns the selection in menu hierarchy.

RootPaneContainer

This interface is implemented by components that have a single JRootPane child: JDialog, JFrame, JWindow, JApplet, JInternalFrame.

ScrollPaneConstants

Constants used with the JScrollPane component.

SwingConstants

A collection of constants generally used for positioning and orienting components on the screen.

Timer

Fires one or more

UIDefaults

A table of defaults for Swing components.

Class and Description
AbstractAction

This class provides default implementations for the JFC

AbstractButton

Defines common behaviors for buttons and menu items.

AbstractListModel

The abstract definition for the data model that provides a

Action

The

ActionMap
CellRendererPane

This class is inserted in between cell renderers and the components that use them.

ComboBoxEditor

The editor component used for JComboBox components.

ComboBoxModel

A data model for a combo box.

DefaultListCellRenderer

Renders an item in a list.

Icon

A small fixed size picture, typically used to decorate components.

JButton

An implementation of a “push” button.

JComboBox

A component that combines a button or editable field and a drop-down list.

JComponent

The base class for all Swing components except top-level containers.

JFileChooser
JInternalFrame

A lightweight object that provides many of the features of a native frame, including dragging, closing, becoming an icon, resizing, title display, and support for a menu bar.

JLabel

A display area for a short text string or an image, or both.

JList

A component that displays a list of objects and allows the user to select one or more items.

JMenu

An implementation of a menu — a popup window containing

JPanel
JPopupMenu

An implementation of a popup menu — a small window that pops up and displays a series of choices.

JScrollPane

Provides a scrollable view of a lightweight component.

JSeparator
JSlider

A component that lets the user graphically select a value by sliding a knob within a bounded interval.

JToolBar
LayoutStyle
ListCellRenderer

Identifies components that can be used as “rubber stamps” to paint the cells in a JList.

ListModel

This interface defines the methods components like JList use to get the value of each cell in a list and the length of the list.

LookAndFeel
MenuElement

Any component that can be placed into a menu should implement this interface.

ScrollPaneConstants

Constants used with the JScrollPane component.

SwingConstants

A collection of constants generally used for positioning and orienting components on the screen.

UIDefaults

A table of defaults for Swing components.

Class and Description
JComboBox

A component that combines a button or editable field and a drop-down list.

JComponent

The base class for all Swing components except top-level containers.

JFileChooser
JList

A component that displays a list of objects and allows the user to select one or more items.

JOptionPane
JPopupMenu

An implementation of a popup menu — a small window that pops up and displays a series of choices.

JSplitPane
JTabbedPane

A component that lets the user switch between a group of components by clicking on a tab with a given title and/or icon.

JTree
LookAndFeel
Popup

Popups are used to display a

UIDefaults

A table of defaults for Swing components.

Class and Description
Icon

A small fixed size picture, typically used to decorate components.

JComponent

The base class for all Swing components except top-level containers.

LookAndFeel
Painter

A painting delegate.

UIDefaults

A table of defaults for Swing components.

Class and Description
AbstractButton

Defines common behaviors for buttons and menu items.

ComboBoxEditor

The editor component used for JComboBox components.

Icon

A small fixed size picture, typically used to decorate components.

JButton

An implementation of a “push” button.

JComponent

The base class for all Swing components except top-level containers.

JInternalFrame

A lightweight object that provides many of the features of a native frame, including dragging, closing, becoming an icon, resizing, title display, and support for a menu bar.

JLabel

A display area for a short text string or an image, or both.

JPanel
JRootPane

A lightweight container used behind the scenes by

JScrollPane

Provides a scrollable view of a lightweight component.

JSeparator
JSlider

A component that lets the user graphically select a value by sliding a knob within a bounded interval.

JSplitPane
ListCellRenderer

Identifies components that can be used as “rubber stamps” to paint the cells in a JList.

LookAndFeel
ScrollPaneConstants

Constants used with the JScrollPane component.

SwingConstants

A collection of constants generally used for positioning and orienting components on the screen.

UIDefaults

A table of defaults for Swing components.

Class and Description
CellEditor

This interface defines the methods any general editor should be able to implement.

DefaultRowSorter

An implementation of

JComponent

The base class for all Swing components except top-level containers.

JComponent.AccessibleJComponent

Inner class of JComponent used to provide default support for accessibility.

JLabel

A display area for a short text string or an image, or both.

JTable

The

ListSelectionModel

This interface represents the current state of the selection for any of the components that display a list of values with stable indices.

RowSorter
SwingConstants

A collection of constants generally used for positioning and orienting components on the screen.

Class and Description
AbstractAction

This class provides default implementations for the JFC

Action

The

DropMode

Drop modes, used to determine the method by which a component tracks and indicates a drop location during drag and drop.

Icon

A small fixed size picture, typically used to decorate components.

JComponent

The base class for all Swing components except top-level containers.

JComponent.AccessibleJComponent

Inner class of JComponent used to provide default support for accessibility.

JEditorPane

A text component to edit various kinds of content.

JFormattedTextField
JFormattedTextField.AbstractFormatter

Instances of

JFormattedTextField.AbstractFormatterFactory

Instances of

KeyStroke

A KeyStroke represents a key action on the keyboard, or equivalent input device.

Scrollable

An interface that provides information to a scrolling container like JScrollPane.

SizeRequirements

For the convenience of layout managers, calculates information about the size and position of components.

SwingConstants

A collection of constants generally used for positioning and orienting components on the screen.

TransferHandler.DropLocation

Represents a location where dropped data should be inserted.

Class and Description
AbstractAction

This class provides default implementations for the JFC

Action

The

Icon

A small fixed size picture, typically used to decorate components.

JEditorPane

A text component to edit various kinds of content.

SizeRequirements

For the convenience of layout managers, calculates information about the size and position of components.

SwingConstants

A collection of constants generally used for positioning and orienting components on the screen.

Class and Description
CellEditor

This interface defines the methods any general editor should be able to implement.

DefaultListSelectionModel

Default data model for list selections.

Icon

A small fixed size picture, typically used to decorate components.

JComponent

The base class for all Swing components except top-level containers.

JLabel

A display area for a short text string or an image, or both.

JTextField
JTree
Scrollable

An interface that provides information to a scrolling container like JScrollPane.

SwingConstants

A collection of constants generally used for positioning and orienting components on the screen.

Timer

Fires one or more

Submit a bug or feature For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.Copyright © 1993, 2024, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

This article is about Programming

How to Create a GUI with Java

By NIIT Editorial

Published on 27/07/2021

8 minutes

GUI, which stands for Graphical User Interface, is a user-friendly visual experience builder for Java applications. It comprises graphical units like buttons, labels, windows, etc. via which users can connect with an application. Swing and JavaFX are two commonly used applications to create GUIs in Java.

Elements of GUI:

A GUI comprises an array of user interface elements. All these elements are displayed when a user is interacting with an application and they are as follows:

1. Input commands such as buttons, check boxes, dropdown lists and text fields.

2. Informational components like banners, icons, labels or notification dialogs.

3. Navigational units like menus, sidebars and breadcrumbs.

GUI in JAVA: Swing and JavaFX

As mentioned above, to create a GUI in Java, Swing and JavaFX are the most commonly used applications. Swing was designed with a flexible architecture to make the elements customizable and easy to plug-and-play which is why it is the first choice for java developers while creating GUIs.

As far as JavaFX is concerned, it consists of a totally different set of graphic components along with new features and terminologies.

Creating a GUI

The process of creating a GUI in Swing starts with creating a class that represents the main GUI. An article of this class acts as a container which holds all the other components to be displayed.

In most of the projects, the main interface article is a frame, i.e., the JFrame class in javax.swing package. A frame is basically a window which is displayed whenever a user opens an application on his/her computer. It has a title bar and buttons such as minimize, maximize and close along with other features.

The JFrame class consists of simple constructors such as JFrame() and JFrame(String). The JFrame() leaves the frame’s title bar empty, whereas the JFrame(String) places the title bar to a specified text.

Apart from the title, the size of the frame can also be customized. It can be established by incorporating the setSize(int, int) method by inserting the width and height desired for the frame. The size of a frame is always designated in pixels.

For example, calling setSize(550,350) would create a frame that would be 550 pixels wide and 350 pixels tall.

Usually, frames are invisible at the time of their creation. However, a user can make them visible by using the frame’s setVisible(boolean) method by using the word ‘true’ as an argument.

The following are the steps to create GUI in Java

STEP 1: The following code is to be copied into an editor

STEP 2: Save and compile the code as mentioned above and then run it.

STEP 3: Adding buttons to the above frame. To create a component in Java, the user is required to create an object of that component’s class. We have already understood the container class JFrame.

One such component to implement is JButton. This class represents the clickable buttons. In any application or program, buttons trigger user actions. Literally, every action begins with a click; like to close an application, the user would click on the close button.

A swing can also be inserted, which can feature a text, a graphical icon or a combination of both. A user can use the following constructors:

· JButton(String): This button is labelled with a specified text.

· JButton(Icon): This button is labelled with a graphical icon.

· JButton(String,Icon): This button is labelled with a combination of text and icon.

The following code is to be copied into an editor:

STEP 4: The above is to be executed. A big button will appear on the screen.

STEP 5: A user can add two buttons to the frame as well. Copy the code given below into an editor.

STEP 6: Save, compile and run the above code.

STEP 7: Unpredicted output = ? It means that the buttons are getting overlapped.

STEP 8: A user can create chat frames as well. Below is an example of the same:

The following is the code for creating a chat frame:

Conclusion

It can be concluded that creating GUI in Java is a very easy and user-friendly process as the Java applications provide customization according to the requirements of the user. To learn more about Java, and to become an expert in Java development go to NIIT and check out the courses that give great insight on Java.

PGP in Full Stack Product Engineering

Become an Industry-Ready StackRoute Certified Full Stack Product Engineer who can take up Product Development and Digital Transformation projects. Job Assured Program* with a minimum CTC of ₹7LPA*

Job Assured Program*

Easy Financing Options

Introduction to Java Swing

Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window Toolkit [AWT]. Java Swing offers much-improved functionality over AWT, new components, expanded components features, and excellent event handling with drag-and-drop support.

Introduction of Java Swing

Swing has about four times the number of User Interface [UI] components as AWT and is part of the standard Java distribution. By today’s application GUI requirements, AWT is a limited implementation, not quite capable of providing the components required for developing complex GUIs required in modern commercial applications. The AWT component set has quite a few bugs and does take up a lot of system resources when compared to equivalent Swing resources. Netscape introduced its Internet Foundation Classes [IFC] library for use with Java. Its Classes became very popular with programmers creating GUI’s for commercial applications.

  • Swing is a Set of API (API- Set of Classes and Interfaces)
  • Swing is Provided to Design Graphical User Interfaces
  • Swing is an Extension library to the AWT (Abstract Window Toolkit) 5:00 – 5:30 pm
  • Includes New and improved Components that have been enhancing the looks and Functionality of GUIs’
  • Swing can be used to build (Develop) The Standalone swing GUI Apps as Servlets and Applets
  • It Employs model/view design architecture.
  • Swing is more portable and more flexible than AWT, the Swing is built on top of the AWT.
  • Swing is Entirely written in Java.
  • Java Swing Components are Platform-independent, and The Swing Components are lightweight.
  • Swing Supports a Pluggable look and feel and Swing provides more powerful components.
  • such as tables, lists, Scrollpanes, Colourchooser, tabbed pane, etc.
  • Further Swing Follows MVC.
Java Swings Introduction, Difference between AWT and Swings, Important Methods of Component Class
Java Swings Introduction, Difference between AWT and Swings, Important Methods of Component Class

What is a Container Class?

Container classes are classes that can have other components on it. So for creating a Java Swing GUI, we need at least one container object. There are 3 types of Java Swing containers.

  1. Panel: It is a pure container and is not a window in itself. The sole purpose of a Panel is to organize the components on to a window.
  2. Frame: It is a fully functioning window with its title and icons.
  3. Dialog: It can be thought of like a pop-up window that pops out when a message has to be displayed. It is not a fully functioning window like the Frame.

Hướng dẫn học lập trình Java Swing từ A đến Z

Dưới đây là một số ví dụ đơn giản để tạo GUI bằng Swing trong Java:

JButton Class – Lớp JButton

Nó được dùng để tạo ra một nút (button) có tên.

Việc sử dụng ActionListener sẽ dẫn đến một số hành động khi nút được nhấn.

Nó kế thừa lớp AbstractButton và độc lập với nền tảng.

Ví dụ:

1

10

11

12

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);

Output:

Một nút button có tên

JTextField Class – Lớp JTextField

Nó kế thừa lớp JTextComponent và dùng để cho phép chỉnh sửa dòng đơn

Ví dụ:

1

10

11

12

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);

Output:

JTextField Class

JScrollBar Class – lớp JScrollBar

Dùng để thêm thanh cuộn (cả ngang và dọc)

Ví dụ:

1

10

11

12

13

14

15

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();

Output:

JScrollBar Class

JPanel Class – Lớp JPanel

Kế thừa lớp JComponent, cung cấp không gian cho một ứng dụng (có thể đính kèm bất kỳ thành phần nào khác).

1

10

11

12

13

14

15

16

17

18

19

20

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();

Output:

Panel Class

JMenu Class – Lớp JMenu

Kế thừa lớp JMenuItem, là một thành phần menu kéo xuống (hiển thị từ thanh menu).

1

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

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();

Output:

Lớp JMenu

JList Class – Lớp JList

Kế thừa lớp JComponent, đối tượng của lớp Jlist đại diện cho danh sách các mục văn bản.

Next

1

10

11

12

13

14

15

16

17

18

19

20

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();

Output:

Lớp JList

JLabel Class – Lớp JLabel

Được dùng để đặt văn bản trong vùng chứa, lớp JLabel cũng kế thừa lớp JComponent.

1

10

11

12

13

14

import javax.swing.*;

public class Example{

public static void main(String args[])

JFrame a = new JFrame(“example”);

JLabel b1;

b1 = new JLabel(“edureka”);

b1.setBounds(40,40,90,20);

a.add(b1);

a.setSize(400,400);

a.setLayout(null);

a.setVisible(true);

Output:

Lớp JLabel

JComboBox Class- Lớp JComboBox

Kế thừa lớp JComponent, dùng để hiển thị menu lựa chọn bật lên.

1

10

11

12

13

14

15

16

17

18

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();

Output:

Lớp JComboBox

Layout Manager – Trình quản lý bố cục

Để sắp xếp các thành phần bên trong vùng chứa, chúng ta sử dụng Layout Manager.

Có một số bố cục như sau:

  1. Border layout – Bố cục đường viền
  2. Flow layout – Bố cục luồng
  3. GridBag layout – Bố cục dạng khung
Border Layout

Trình quản lý bố cục mặc định tất cả JFrame là Border Layout.

Nó đặt các thành phần ở tối đa 5 vị trí: trên, dưới, trái, phải và trung tâm.

Trình quản lý bố cục mặc định

Flow Layout

Bố cục này đặt các thành phần lần lượt vào một hàng.

Bố cục mặc định JPanel.

Đây là bố cục mặc định cho mọi JPanel.

GridBag Layout

GridBag Layout đặt các thành phần trong một lưới, nó cho phép các thành phần này trải dài hơn 1 ô.

GridBag Layout

Ví dụ: Dưới đây là một khung chat ở dạng Flow Layout

1

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

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);

Output:

Khung chat ở dạng Flow Layout

Example of Java Swing - JButton, JRadioButton and JTextArea in Hindi and English
Example of Java Swing – JButton, JRadioButton and JTextArea in Hindi and English

Các phương thức được sử dụng phổ biến của Component Class

Có một số phương thức trong lớp Component được sử dụng khá phổ biến, đó là:

Phương thức Mục đích
public void add(Component c) Bổ sung một thành phần trên một phần khác
public void setSize(int width,int height) Để cài đặt và tùy chỉnh kích cỡ của thành phần (chiều rộng, chiều cao)
public void setLayout(LayoutManager m) Để cài đặt Layout Manager cho thành phần
public void setVisible(boolean b) Để cài đặt tính nhìn thấy được (visible) của thành phần. Theo mặc định là false.

What is JFC?

JFC stands for Java Foundation Classes. JFC is the set of GUI components that simplify desktop Applications. Many programmers think that JFC and Swing are one and the same thing, but that is not so. JFC contains Swing [A UI component package] and quite a number of other items:

  • Cut and paste: Clipboard support.
  • Accessibility features: Aimed at developing GUIs for users with disabilities.
  • The Desktop Colors Features were first introduced in Java 1.1
  • Java 2D: it has Improved colors, images, and text support.
INTRODUCTION TO JAVA SWING
INTRODUCTION TO JAVA SWING

Full Stack Web Development Internship Program

  • 29k Enrolled Learners
  • Weekend/Weekday
  • Live Class

Swing in java is part of Java foundation class which is lightweight and platform independent. It is used for creating window based applications. It includes components like button, scroll bar, text field etc. Putting together all these components makes a graphical user interface. In this article, we will go through the concepts involved in the process of building applications using swing in Java. Following are the concepts discussed in this article:

Swing in Java is a lightweight GUI toolkit which has a wide variety of widgets for building optimized window based applications. It is a part of the JFC( Java Foundation Classes). It is build on top of the AWT API and entirely written in java. It is platform independent unlike AWT and has lightweight components.

It becomes easier to build applications since we already have GUI components like button, checkbox etc. This is helpful because we do not have to start from the scratch.

Any class which has other components in it is called as a container class. For building GUI applications at least one container class is necessary.

Following are the three types of container classes:

Panel – It is used to organize components on to a window

Frame – A fully functioning window with icons and titles

Dialog – It is like a pop up window but not fully functional like the frame

AWT SWING

Explanation: All the components in swing like JButton, JComboBox, JList, JLabel are inherited from the JComponent class which can be added to the container classes. Containers are the windows like frame and dialog boxes. Basic swing components are the building blocks of any gui application. Methods like setLayout override the default layout in each container. Containers like JFrame and JDialog can only add a component to itself. Following are a few components with examples to understand how we can use them.

It is used to create a labelled button. Using the ActionListener it will result in some action when the button is pushed. It inherits the AbstractButton class and is platform independent.

Example:

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); } }

Output:

It inherits the JTextComponent class and it is used to allow editing of single line text.

Example:

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); } }

Output:

It is used to add scroll bar, both horizontal and vertical.

Example:

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(); } }

Output:

It inherits the JComponent class and provides space for an application which can attach any other component.

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(); } }

Output:

It inherits the JMenuItem class, and is a pull down menu component which is displayed from the menu bar.

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(); } }

Output:

It inherits JComponent class, the object of JList class represents a list of text items.

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(); } }

Output:

It is used for placing text in a container. It also inherits JComponent class.

import javax.swing.*; public class Example{ public static void main(String args[]) { JFrame a = new JFrame(“example”); JLabel b1; b1 = new JLabel(“edureka”); b1.setBounds(40,40,90,20); a.add(b1); a.setSize(400,400); a.setLayout(null); a.setVisible(true); } }

Output:

It inherits the JComponent class and is used to show pop up menu of choices.

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(); } }

Output:

To arrange the components inside a container we use the layout manager. Following are several layout managers:

Border layout

Flow layout

GridBag layout

The default layout manager for every JFrame is BorderLayout. It places components in upto five places which is top, bottom, left, right and center.

FlowLayout simply lays the components in a row one after the other, it is the default layout manager for every JPanel.

GridBagLayout places the components in a grid which allows the components to span more than one cell.

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); } }

This is a simple example for creating a GUI using swing in Java.

If you’re just beginning, then watch at this Java Tutorial to Understand the Fundamental Java Concepts.

In this article we have discussed swing in Java and hierarchy of Java swing classes. With all the components which comes with swing in Java, it becomes easier to build optimized GUI applications. Java programming language is a structured programming language and with the increasing demand it becomes extremely important to master all the concepts in Java programming. To kick-start your learning and to become an expert in java programming, enroll to Edureka’s Java Certification program.

Got a question for us? please mention this in the comments section of this ‘Swing In Java’ article and we will get back to you as soon as possible.

Course Name Date Details
Java Certification Training Course

Class Starts on 24th February,2024

24th February

SAT&SUN (Weekend Batch)

View Details
Java Certification Training Course

Class Starts on 30th March,2024

30th March

SAT&SUN (Weekend Batch)

View Details

edureka.co

Last Updated on March 22, 2023 by Prepbytes

Java Swing is a popular framework for creating Graphical User Interfaces (GUI) in Java. It is a part of the Java Foundation Classes (JFC) and is widely used for developing desktop applications. This article discusses Java Swing, the features of Java Swing, Java Swing packages, the difference between Java Swing and Java AWT, and the advantages and disadvantages of Java Swing.

GUI trong Java là gì?

GUI (Graphical User Interface) trong Java là một trình tạo trải nghiệm trực quan cho các ứng dụng Java. Nó chủ yếu được làm bằng các thành phần đồ họa (graphical component) như button (nút), label (nhãn), window (cửa sổ), v.v. mà qua đó người dùng có thể tương tác với ứng dụng. GUI dễ sử dụng và đóng một vai trò quan trọng để xây dựng giao diện cho các ứng dụng Java.

Ví dụ về GUI trong Java

Nào, hãy bắt đầu khám phá GUI với Swing Java tutorial qua các ví dụ sau đây.

Ví dụ: Học lập trình Java GUI trong hướng dẫn Java GUI này

Bước 1. Sao chép đoạn code sau vào trình chỉnh sửa

import javax.swing.*;

class gui{

public static void main(String args[]){

JFrame frame = new JFrame(“My First GUI”);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(300,300);

JButton button = new JButton(“Press”);

frame.getContentPane().add(button); // Adds Button to content pane of frame

frame.setVisible(true);

Bước 2. Lưu lại, compile và chạy code.

Bước 3. Giờ hãy thêm một Button vào frame. Copy đoạn code bên dưới vào trình chỉnh sửa từ ví dụ Java GUI đã cho

import javax.swing.*;

class gui{

public static void main(String args[]){

JFrame frame = new JFrame(“My First GUI”);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(300,300);

JButton button1 = new JButton(“Press”);

frame.getContentPane().add(button1);

frame.setVisible(true);

Bước 4. Execute code. Bạn sẽ nhận được button như ảnh dưới

Bước 5. Để thêm hẳn 2 button? Copy đoạn code bên dưới vào trình chỉnh sửa

import javax.swing.*;

class gui{

public static void main(String args[]){

JFrame frame = new JFrame(“My First GUI”);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(300,300);

JButton button1 = new JButton(“Button 1”);

JButton button2 = new JButton(“Button 2”);

frame.getContentPane().add(button1);

frame.getContentPane().add(button2);

frame.setVisible(true);

Bước 6. Lưu, compile và chạy chương trình

Bước 7. Output trả ra không như mong đợi? Các button của bạn đang bị overlap rồi đó.

Components in Swing in java
Components in Swing in java

Java Layout Manager (trình quản lý bố cục Java)

Layout manager được sử dụng để bố trí (hoặc sắp xếp) các thành phần GUI java bên trong một container. Có nhiều layout manager, nhưng thường được sử dụng nhất là các loại sau đây:

Java BorderLayout

BorderLayout đặt các component vào tối đa năm khu vực: trên cùng, dưới cùng, trái, phải và trung tâm. Nó là trình quản lý bố cục mặc định cho mọi java JFrame

Java FlowLayout

FlowLayout là trình quản lý bố cục mặc định cho mọi JPanel. Nó lần lượt đưa ra các thành phần trong một hàng duy nhất.

What is Java Swing?

Java Swing is a popular and powerful Graphical User Interface (GUI) toolkit that is used for developing desktop applications. It is a part of the Java Foundation Classes (JFC) and provides a rich set of components and layout managers for creating a variety of GUIs. Java Swing is platform-independent and can be used on any operating system that supports Java.

It provides a set of lightweight components that are not only easy to use but also customizable. Some of the commonly used components in Swing are buttons, text fields, labels, menus, and many more.

Java Swing provides a pluggable look and feels that allows developers to customize the GUI according to the user’s preferences. It also provides a robust event-handling mechanism that allows developers to handle events generated by the graphical components.

Some of the commonly used layout managers in Java Swing are BorderLayout, FlowLayout, GridLayout, CardLayout, and BoxLayout. These layout managers allow developers to create complex and intuitive GUIs that are easy to use and navigate.

Features of Java Swing

Some of the notable features of Java Swing are:

  1. Platform Independence: Platform independence is one of Java Swing’s most remarkable features. It can run on any platform that supports Java. Thus, Swing-based applications can run on Windows, Mac, Linux, or any other Java-compatible operating system.
  2. Lightweight Components: Java Swing provides a set of lightweight components that are easy to use and customizable. These components are designed to consume less memory and use less processing power, making Swing-based applications run efficiently.
  3. Pluggable Look and Feel: Java Swing provides a pluggable look and feels that allows developers to customize the appearance of the GUI according to the user’s preferences. Developers can choose from several pre-built looks and feel themes or create their own custom themes.
  4. Layout Managers: Java Swing provides a set of layout managers that can be used to organize the graphical components in a GUI. These layout managers enable developers to create flexible and responsive GUIs that adapt to different screen sizes and resolutions.
  5. Robust Event Handling Mechanism: Java Swing provides a robust event handling mechanism that allows developers to handle events generated by the graphical components. Developers can register event listeners to detect and respond to user interactions with the GUI.

Java Swing Class Hierarchy

The Java Swing API hierarchy is shown below:

Java Swing Packages

Some of the commonly used packages in Java Swing are:

  1. javax.swing: This package contains the core components of Swing, such as JButton, JLabel, JTable, JList, and many more. It also contains the classes for creating top-level containers such as JFrame and JDialog.
  2. javax.swing.event: This package contains the classes for handling events generated by the Swing components. It includes event listener interfaces, event adapter classes, and event objects.
  3. javax.swing.border: This package contains classes for creating borders around the Swing components. It includes the classes for creating line borders, etched borders, and titled borders.
  4. javax.swing.layout: This package contains the classes for creating and managing layout managers in Swing. It includes the commonly used layout managers such as BorderLayout, FlowLayout, GridLayout, BoxLayout, and CardLayout.
  5. javax.swing.plaf: This package contains the classes for the pluggable look and feels feature of Swing. It includes the classes for creating and managing the look and feel themes, and also provides the default look and feel theme for each platform.
  6. javax.swing.text: This package contains the classes for creating and managing text components in Swing. It includes classes for creating text fields, text areas, and other text-related components.
  7. javax.swing.table: This package contains the classes for creating and managing tables in Swing. It includes the classes for creating JTable, TableModel, TableColumn, and TableCellRenderer.

Components of Java Swing

Some of the important and common components of the Java Swing class are:

  1. JFrame: JFrame is a top-level container that represents the main window of a GUI application. It provides a title bar, and minimizes, maximizes, and closes buttons.
  2. JPanel: JPanel is a container that can hold other components. It is commonly used to group related components together.
  3. JButton: JButton is a component that represents a clickable button. It is commonly used to trigger actions in a GUI application.
  4. JLabel: JLabel is a component that displays text or an image. It is commonly used to provide information or to label other components.
  5. JTextField: JTextField is a component that allows the user to input text. It is commonly used to get input from the user, such as a name or an address.
  6. JCheckBox: JCheckBox is a component that represents a checkbox. It is commonly used to get a binary input from the user, such as whether or not to enable a feature.
  7. JList: JList is a component that represents a list of elements. It is typically used to display a list of options from which the user can select one or more items.
  8. JTable: JTable is a component that represents a data table. It is typically used to present data in a tabular fashion, such as a list of products or a list of orders.
  9. JScrollPane: JScrollPane is a component that provides scrolling functionality to other components. It is commonly used to add scrolling to a panel or a table.

Difference between Java Swing and Java AWT

Here is a comparison of Java Swing and Java AWT:

Feature Java Swing Java AWT
Architecture Platform-Independent Platform-Dependent
Look and Feel Pluggable look and feel Native look and feel
Components Richer set of components Basic set of components
Performance Slower due to software rendering Faster due to native OS rendering
Event Model More flexible and powerful Simpler and less powerful
Thread Safety By default, it is not thread-safe Thread-safe by default
Customization Highly customizable Less customizable
Layout Managers More layout managers are available Fewer layout managers are available
API Extensive API with many features Basic API with fewer features
Graphics Support It supports more advanced graphics It only supports basic graphics
File Size Size is large due to additional APIs Size is small due to fewer APIs and classes

Advantages of Java Swing

Java Swing provides a number of advantages for developing graphical user interfaces (GUIs) in Java. Some of the key advantages of Java Swing are

  1. Platform Independence: Swing is written entirely in Java, which makes it platform-independent. It can run on any platform that supports Java, without any modification.
  2. Look and Feel: Java Swing provides a pluggable look and feels feature, which allows developers to customize the appearance of the components. It provides a consistent look and feels across platforms, which helps in creating a professional-looking GUI.
  3. Rich Component Set: Java Swing provides a rich set of components, including advanced components like JTree, JTable, and JSpinner. It also provides support for multimedia components, such as audio and video.
  4. Layout Managers: Java Swing provides a variety of layout managers, which makes it easy to arrange the components on a GUI. The layout managers help in creating GUIs that are visually appealing and easy to use.
  5. Event Handling: Java Swing provides a powerful and flexible event handling model, which makes it easy to handle user events such as mouse clicks and keyboard presses. The event-handling model makes it easy to add interactivity to the GUI.
  6. Customizable: Java Swing components are highly customizable, which makes it easy to create GUIs that meet the specific needs of an application. The components can be easily modified to suit the look and feel of the application.

Disadvantages of Java Swing

Some of the main disadvantages of Java Swing are:

  1. Performance: Java Swing applications can be slower than native applications because of the overhead of running the Java Virtual Machine (JVM). This can be particularly noticeable in complex applications with large amounts of data.
  2. Look and Feel: While Swing’s pluggable look and feel feature allows for customization of the components, it can be difficult to achieve a truly native look and feel. This can make Swing applications look and feel different from other native applications on the same platform, which can be confusing for users.
  3. Learning Curve: While Swing is easy to learn for developers who are already familiar with Java, it can be difficult for beginners who are not familiar with the language. The complex hierarchy of components and layout managers can also make it difficult to create complex GUIs.
  4. Resource Consumption: Java Swing applications often requires a significant amount of system resources, such as memory and computing power. This can be an issue for low-end devices with limited resources or large-scale apps with a big number of users.
  5. Lack of Mobile Support: Since Java Swing is a desktop-oriented GUI toolkit, it does not support mobile devices well. This could pose a potential challenge for developers who want to create cross-platform apps that work on both desktop and mobile platforms.

ConclusionIn conclusion, Java Swing is a powerful GUI toolkit that provides a rich set of components for creating desktop applications. Java Swing is a popular choice for desktop applications, and it continues to be widely used by developers worldwide. Ultimately, the choice of whether to use Swing or another GUI toolkit depends on the specific needs of the application and the preferences of the developer.

Java anonymous inner class 🎭
Java anonymous inner class 🎭

Components of Swing Class the task’s percentage

Component A Component is the Abstract base class for about the non-menu user-interface controls of Java SWING. Components are representing an object with a graphical representation.
Container A Container is a component that can container Java SWING Components
JComponent A JComponent is a base class for all swing UI Components In order to use a swing component that inherits from JComponent, the component must be in a containment hierarchy whose root is a top-level Java Swing container.
JLabel A JLabel is an object component for placing text in a container.
JButton This class creates a labeled button.
JColorChooser A JColorChooser provides a pane of controls designed to allow the user to manipulate and select a color.
JCheckBox A JCheckBox is a graphical (GUI) component that can be in either an on-(true) or off-(false) state.
JRadioButton The JRadioButton class is a graphical (GUI) component that can be in either an on-(true) or off-(false) state. in the group
JList A JList component represents the user with the scrolling list of text items.
JComboBox A JComboBox component is Presents the User with a show up Menu of choices.
JTextField A JTextField object is a text component that will allow for the editing of a single line of text.
JPasswordField A JPasswordField object it is a text component specialized for password entry.
JTextArea A JTextArea object is a text component that allows for the editing of multiple lines of text.
Imagelcon A ImageIcon control is an implementation of the Icon interface that paints Icons from Images
JScrollbar A JScrollbar control represents a scroll bar component in order to enable users to Select from range values.
JOptionPane JOptionPane provides set of standard dialog boxes that prompt users for a value or Something.
JFileChooser A JFileChooser it Controls represents a dialog window from which the user can select a file.
JProgressBar As the task progresses towards completion, the progress bar displays the tasks percentage on its completion.
JSlider A JSlider this class is letting the user graphically (GUI) select by using a value by sliding a knob within a bounded interval.
JSpinner A JSpinner this class is a single line input where the field that lets the user select by using a number or an object value from an ordered sequence.

Feeling lost in the vast world of Backend Development? It’s time for a change! Join our Java Backend Development – Live Course and embark on an exciting journey to master backend development efficiently and on schedule. What We Offer:

  • Comprehensive Course
  • Expert Guidance for Efficient Learning
  • Hands-on Experience with Real-world Projects
  • Proven Track Record with 100,000+ Successful Geeks

Last Updated :
09 Jan, 2024

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

Nội dung

Ngôn ngữ lập trình Java là một ngôn ngữ lập trình có nhu cầu sử dụng ngày càng cao, do đó việc nắm vững tất cả các khái niệm trong lập trình Java trở nên vô cùng quan trọng.

Swing là một trong số những khái niệm quan trọng trong Java.

Nó là một bộ công cụ có trọng lượng nhẹ, hỗ trợ các nhà lập trình tạo giao diện đồ hoạ người dùng.

Trong bài này chúng ta sẽ đi qua cái khái niệm về Java Swing và cách ứng dụng chúng nhé!

Java Swing là gì?

Java Swing là cách gọi rút gọn khi người ta nhắc đến Swing của Java Foundation (JFC). Nó là bộ công cụ GUI mà Sun Microsystems phát triển để xây dựng các ứng dụng tối ưu dùng cho window (bao gồm các thành phần như nút, thanh cuộn,…).

Swing được xây dựng trên AWT API và hoàn toàn được viết bằng Java. Tuy nhiên, nó lại khác với AWT ở chỗ bộ công cụ này thuộc loại nền tảng độc lập, bao gồm các thành phần nhẹ và phức tạp hơn AWT.

Các gói javax.swing bao gồm các lớp cho Java Swing API như JMenu, JButton, JTextField, JRadioButton, JColorChooser,…

Việc xây dựng ứng dụng sẽ trở nên dễ dàng hơn với Java Swing vì chúng ta có các bộ công cụ GUI giúp đỡ công việc.

Swing được chính thức phát hành vào tháng 3/1998. Nó đi kèm với thư viện Swing 1.0 với hơn 250 lớp, 80 giao tiếp.

Hiện nay con số này đã được tăng lên, ở phiên bản Swing 1.4 có 451 lớp và 85 giao tiếp.

Các bản phát hành Java 2 (SDK 1.2 và các phiên bản mới hơn) đều bao gồm Swing trong runtime environment.

Java GUI Tutorial - Make a GUI in 13 Minutes #99
Java GUI Tutorial – Make a GUI in 13 Minutes #99

Keywords searched by users: swing classes in java

Java Swing: Definition, Classes & Methods - Video & Lesson Transcript |  Study.Com
Java Swing: Definition, Classes & Methods – Video & Lesson Transcript | Study.Com
Introduction To Java Swing - Geeksforgeeks
Introduction To Java Swing – Geeksforgeeks
Gui Programming Part 2 - Java Programming Tutorial
Gui Programming Part 2 – Java Programming Tutorial
Swing Components In Java | Top 13 Useful Components Of Swing In Java
Swing Components In Java | Top 13 Useful Components Of Swing In Java
Java Swing Từ A - Z | Vietnamworks Intech
Java Swing Từ A – Z | Vietnamworks Intech
Swing Program In Java | A Brief Overview Of Swing Program In Java
Swing Program In Java | A Brief Overview Of Swing Program In Java
Awt And Swing In Java - Javatpoint
Awt And Swing In Java – Javatpoint
Java Swing Tutorial: Container, Components And Event Handling
Java Swing Tutorial: Container, Components And Event Handling
Title
Title
Gui Programming Part 2 - Java Programming Tutorial
Gui Programming Part 2 – Java Programming Tutorial
Java Swing With Examples- Scaler Topics
Java Swing With Examples- Scaler Topics
Swing Java: Most Up-To-Date Encyclopedia, News & Reviews
Swing Java: Most Up-To-Date Encyclopedia, News & Reviews
Java Swing: Definition, Classes & Methods - Video & Lesson Transcript |  Study.Com
Java Swing: Definition, Classes & Methods – Video & Lesson Transcript | Study.Com
Swing (Java) - Wikipedia
Swing (Java) – Wikipedia
Java Swing Tutorial - Javatpoint
Java Swing Tutorial – Javatpoint
Swing (Java) - Wikipedia
Swing (Java) – Wikipedia
Features Of Java Swing - Coding Ninjas
Features Of Java Swing – Coding Ninjas
15 Java Swing Examples
15 Java Swing Examples
Swing Components In Java - Coding Ninjas
Swing Components In Java – Coding Ninjas

See more here: kientrucannam.vn

Leave a Reply

Your email address will not be published. Required fields are marked *