HOME

TheInfoList



OR:

Swing is a GUI
widget toolkit A widget toolkit, widget library, GUI toolkit, or UX library is a library or a collection of libraries containing a set of graphical control elements (called ''widgets'') used to construct the graphical user interface (GUI) of programs. Most widge ...
for
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mos ...
. It is part of Oracle's Java Foundation Classes (JFC) – an
API An application programming interface (API) is a way for two or more computer programs to communicate with each other. It is a type of software interface, offering a service to other pieces of software. A document or standard that describes how ...
for providing a
graphical user interface The GUI ( "UI" by itself is still usually pronounced . or ), graphical user interface, is a form of user interface that allows users to interact with electronic devices through graphical icons and audio indicator such as primary notation, inst ...
(GUI) for Java programs. Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit (AWT). Swing provides a
look and feel In software design, the look and feel of a graphical user interface comprises aspects of its design, including elements such as colors, shapes, layout, and typefaces (the "look"), as well as the behavior of dynamic elements such as buttons, boxe ...
that emulates the look and feel of several platforms, and also supports a
pluggable look and feel Pluggable look and feel is a mechanism used in the Java Swing widget toolkit allowing to change the look and feel of the graphical user interface at runtime. Swing allows an application to specialize the look and feel of widgets by modifying the ...
that allows applications to have a look and feel unrelated to the underlying platform. It has more powerful and flexible components than AWT. In addition to familiar components such as buttons, check boxes and labels, Swing provides several advanced components such as tabbed panel, scroll panes, trees, tables, and lists. Unlike AWT components, Swing components are not implemented by platform-specific code. Instead, they are written entirely in Java and therefore are platform-independent. In December 2008, Sun Microsystems (Oracle's predecessor) released the CSS / FXML based framework that it intended to be the successor to Swing, called
JavaFX JavaFX is a software platform for creating and delivering desktop applications, as well as rich web applications that can run across a wide variety of devices. JavaFX has support for desktop computers and web browsers on Microsoft Windows, Linu ...
.


History

The
Internet Foundation Classes The Internet Foundation Classes (IFC) is a GUI widget toolkit and graphics library for Java originally developed by Netcode Corporation and first released by Netscape Corporation on December 16, 1996. The Java IFC was fairly close to the early vers ...
(IFC) were a
graphics library A graphics library is a program library designed to aid in rendering computer graphics to a monitor. This typically involves providing optimized versions of functions that handle common rendering tasks. This can be done purely in software and runn ...
for Java originally developed by
Netscape Communications Corporation Netscape Communications Corporation (originally Mosaic Communications Corporation) was an American independent computer services company with headquarters in Mountain View, California and then Dulles, Virginia. Its Netscape web browser was onc ...
and first released on December 16, 1996. On April 2, 1997, Sun Microsystems and
Netscape Communications Corporation Netscape Communications Corporation (originally Mosaic Communications Corporation) was an American independent computer services company with headquarters in Mountain View, California and then Dulles, Virginia. Its Netscape web browser was onc ...
announced their intention to incorporate IFC with other technologies to form the Java Foundation Classes. The "Java Foundation Classes" were later renamed "Swing." Swing introduced a mechanism that allowed the
look and feel In software design, the look and feel of a graphical user interface comprises aspects of its design, including elements such as colors, shapes, layout, and typefaces (the "look"), as well as the behavior of dynamic elements such as buttons, boxe ...
of every component in an application to be altered without making substantial changes to the application code. The introduction of support for a
pluggable look and feel Pluggable look and feel is a mechanism used in the Java Swing widget toolkit allowing to change the look and feel of the graphical user interface at runtime. Swing allows an application to specialize the look and feel of widgets by modifying the ...
allows Swing components to emulate the appearance of native components while still retaining the benefits of platform independence. Originally distributed as a separately downloadable library, Swing has been included as part of the Java Standard Edition since release 1.2. The Swing classes and components are contained in the package hierarchy. Development of Swing's successor,
JavaFX JavaFX is a software platform for creating and delivering desktop applications, as well as rich web applications that can run across a wide variety of devices. JavaFX has support for desktop computers and web browsers on Microsoft Windows, Linu ...
, started in 2005, and it was officially introduced two years later at JavaOne 2007. JavaFX was open-sourced in 2011 and, in 2012, it became part of the Oracle JDK download. JavaFX is replacing Swing owing to several advantages, including being more lightweight, having CSS styling, sleek design controls, and the use of FXML and Scene Builder. In 2018, JavaFX was made a part of the OpenJDK under the OpenJFX project to increase the pace of its development. Members of the Java Client team that was responsible for Swing included James Gosling (Architect), Rick Levenson (manager), Amy Fowler & Hans Muller (co-technical leads), Tom Ball, Jeff Dinkins, Georges Saab, Tim Prinzing, Jonni Kanerva, and Jeannette Hung & Jim Graham (2D Graphics).


Architecture

Swing is a platform-independent, " model–view–controller" GUI framework for Java, which follows a single- threaded programming model. Additionally, this framework provides a layer of abstraction between the code structure and graphic presentation of a Swing-based GUI.


Foundations

Swing is platform-independent because it is completely written in Java. Complete documentation for all Swing classes can be found in th
Java API Guide
for Version 6 or th
Java Platform Standard Edition 8 API Specification
for Version 8.


Extensible

Swing is a highly modular-based architecture, which allows for the "plugging" of various custom implementations of specified framework interfaces: Users can provide their own custom implementation(s) of these components to override the default implementations using Java's inheritance mechanism via . Swing is a component-based framework, whose components are all ultimately derived from the class. Swing objects asynchronously fire events, have bound properties, and respond to a documented set of methods specific to the component. Swing components are JavaBeans components, compliant with th
JavaBeans specification


Configurable

Swing's heavy reliance on runtime mechanisms and indirect composition patterns allows it to respond at run time to fundamental changes in its settings. For example, a Swing-based application is capable of
hot swapping Hot swapping is the replacement or addition of components to a computer system without stopping, shutting down, or rebooting the system; hot plugging describes the addition of components only. Components which have such functionality are said ...
its user-interface during runtime. Furthermore, users can provide their own look and feel implementation, which allows for uniform changes in the look and feel of existing Swing applications without any programmatic change to the application code.


Lightweight UI

Swing's high level of flexibility is reflected in its inherent ability to override the native host
operating system An operating system (OS) is system software that manages computer hardware, software resources, and provides common services for computer programs. Time-sharing operating systems schedule tasks for efficient use of the system and may also i ...
(OS)'s GUI controls for displaying itself. Swing "paints" its controls using the Java 2D APIs, rather than calling a native user interface toolkit. Thus, a Swing component does not have a corresponding native OS GUI component, and is free to render itself in any way that is possible with the underlying graphics GUIs. However, at its core, every Swing component relies on an AWT container, since (Swing's) extends (AWT's) Container. This allows Swing to plug into the host OS's GUI management framework, including the crucial device/screen mappings and user interactions, such as key presses or mouse movements. Swing simply "transposes" its own (OS-agnostic) semantics over the underlying (OS-specific) components. So, for example, every Swing component paints its rendition on the graphic device in response to a call to component.paint(), which is defined in (AWT) Container. But unlike AWT components, which delegated the painting to their OS-native "heavyweight" widget, Swing components are responsible for their own rendering. This transposition and decoupling is not merely visual, and extends to Swing's management and application of its own OS-independent semantics for events fired within its component containment hierarchies. Generally speaking, the Swing architecture delegates the task of mapping the various flavors of OS GUI semantics onto a simple, but generalized, pattern to the AWT container. Building on that generalized platform, it establishes its own rich and complex GUI semantics in the form of the model.


Loosely coupled and MVC

The Swing library makes heavy use of the model–view–controller software
design pattern A design pattern is the re-usable form of a solution to a design problem. The idea was introduced by the architect Christopher Alexander and has been adapted for various other disciplines, particularly software engineering. The "Gang of Four" boo ...
, which conceptually decouples the data being viewed from the user interface controls through which it is viewed. Because of this, most Swing components have associated ''models'' (which are specified in terms of Java interfaces), and the programmers can use various default implementations or provide their own. The framework provides default implementations of model interfaces for all of its concrete components. The typical use of the Swing framework does not require the creation of custom models, as the framework provides a set of default implementations that are transparently, by default, associated with the corresponding child class in the Swing library. In general, only complex components, such as tables, trees and sometimes lists, may require the custom model implementations around the application-specific data structures. To get a good sense of the potential that the Swing architecture makes possible, consider the hypothetical situation where custom models for tables and lists are wrappers over
DAO Dao, Dão or DAO may refer to: * Tao (Chinese: "The Way" 道), a philosophical concept * Dao (Chinese sword) (刀), a type of Chinese sword * Dao (Naga sword), a weapon and a tool of Naga people People and language * Yao people, a minority ethni ...
and/or EJB services. Typically, Swing component model objects are responsible for providing a concise interface defining events fired, and accessible properties for the (conceptual) data model for use by the associated JComponent. Given that the overall MVC pattern is a loosely coupled collaborative object relationship pattern, the model provides the programmatic means for attaching event listeners to the data model object. Typically, these events are model centric (ex: a "row inserted" event in a table model) and are mapped by the JComponent
specialization Specialization or Specialized may refer to: Academia * Academic specialization, may be a course of study or major at an academic institution or may refer to the field in which a specialist practices * Specialty (medicine), a branch of medical ...
into a meaningful event for the GUI component. For example, the has a model called that describes an interface for how a table would access tabular data. A default implementation of this operates on a two-dimensional
array An array is a systematic arrangement of similar objects, usually in rows and columns. Things called an array include: {{TOC right Music * In twelve-tone and serial composition, the presentation of simultaneous twelve-tone sets such that the ...
. The view component of a Swing JComponent is the object used to graphically represent the conceptual GUI control. A distinction of Swing, as a GUI framework, is in its reliance on programmatically rendered GUI controls (as opposed to the use of the native host OS's GUI controls). Prior to Java 6 Update 10, this distinction was a source of complications when mixing AWT controls, which use native controls, with Swing controls in a GUI (see Mixing AWT and Swing components). Finally, in terms of visual composition and management, Swing favors relative layouts (which specify the positional relationships between components) as opposed to absolute layouts (which specify the exact location and size of components). This bias towards "fluid"' visual ordering is due to its origins in the
applet In computing, an applet is any small application that performs one specific task that runs within the scope of a dedicated widget engine or a larger program, often as a plug-in. The term is frequently used to refer to a Java applet, a program ...
operating environment that framed the design and development of the original Java GUI toolkit. (Conceptually, this view of the layout management is quite similar to that which informs the rendering of HTML content in browsers, and addresses the same set of concerns that motivated the former.)


Relationship to AWT

Since early versions of Java, a portion of the
Abstract Window Toolkit The Abstract Window Toolkit (AWT) is Java's original platform-dependent windowing, graphics, and user-interface widget toolkit, preceding Swing. The AWT is part of the Java Foundation Classes (JFC) — the standard API for providing a graphi ...
(AWT) has provided platform-independent APIs for user interface components. In AWT, each component is rendered and controlled by a native peer component specific to the underlying windowing system. By contrast, Swing components are often described as ''lightweight'' because they do not require allocation of native resources in the operating system's windowing toolkit. The AWT components are referred to as ''heavyweight components''. Much of the Swing API is generally a complementary extension of the AWT rather than a direct replacement. In fact, every Swing lightweight interface ultimately exists within an AWT heavyweight component because all of the top-level components in Swing (, , , and ) extend an AWT top-level container. Prior to Java 6 Update 10, the use of both lightweight and heavyweight components within the same window was generally discouraged due to
Z-order Z-order is an ordering of overlapping two-dimensional objects, such as Window (computing), windows in a stacking window manager, shapes in a vector graphics editor, or objects in a 3D application.Foley, James, Andries van Dam, Steven Feiner, and ...
incompatibilities. However, later versions of Java have fixed these issues, and both Swing and AWT components can now be used in one GUI without Z-order issues. The core rendering functionality used by Swing to draw its lightweight components is provided by
Java 2D Java 2D is an API for drawing two-dimensional graphics using the Java programming language. Every Java 2D drawing operation can ultimately be treated as ''filling'' a ''shape'' using a ''paint'' and ''compositing'' the result onto the screen. ...
, another part of JFC.


Relationship to SWT

The
Standard Widget Toolkit The Standard Widget Toolkit (SWT) is a graphical widget toolkit for use with the Java platform. It was originally developed by Stephen Northover at IBM and is now maintained by the Eclipse Foundation in tandem with the Eclipse IDE. It is an alter ...
(SWT) is a competing toolkit originally developed by IBM and now maintained by the Eclipse
community A community is a social unit (a group of living things) with commonality such as place, norms, religion, values, customs, or identity. Communities may share a sense of place situated in a given geographical area (e.g. a country, village, ...
. SWT's implementation has more in common with the heavyweight components of AWT. This confers benefits such as more accurate fidelity with the underlying native windowing toolkit, at the cost of an increased exposure to the native platform in the programming model. There has been significant debate and speculation about the performance of SWT versus Swing; some hinted that SWT's heavy dependence on
JNI In software design, the Java Native Interface (JNI) is a foreign function interface programming software framework, framework that enables Java (programming language), Java code running in a Java virtual machine (JVM) to call and be called by n ...
would make it slower when the GUI component and Java need to communicate data, but faster at rendering when the data model has been loaded into the GUI, but this has not been confirmed either way. A fairly thorough set of benchmarks in 2005 concluded that neither Swing nor SWT clearly outperformed the other in the general case.


Examples


Hello World

This example Swing application creates a single window with "Hello, world!" inside: // Hello.java (Java SE 8) import javax.swing.*; public class Hello extends JFrame The first import includes all the public classes and interfaces from the package. The Hello class extends the class; the JFrame class implements a
window A window is an opening in a wall, door, roof, or vehicle that allows the exchange of light and may also allow the passage of sound and sometimes air. Modern windows are usually glazed or covered in some other transparent or translucent mat ...
with a title bar and a close control. The Hello() constructor initializes the frame by first calling the superclass constructor, passing the parameter "hello", which is used as the window's title. It then calls the method inherited from JFrame to set the default operation when the close control on the title bar is selected to this causes the JFrame to be disposed of when the frame is closed (as opposed to merely hidden), which allows the Java virtual machine to exit and the program to terminate. Next, a is created for the string "Hello, world!" and the method inherited from the superclass is called to add the label to the frame. The method inherited from the superclass is called to size the window and lay out its contents. The main() method is called by the Java virtual machine when the program starts. It instantiates a new Hello frame and causes it to be displayed by calling the method inherited from the superclass with the boolean parameter true. The code uses the method to invoke the constructor from the AWT
event dispatching thread The event dispatching thread (EDT) is a background thread used in Java to process events from the Abstract Window Toolkit (AWT) graphical user interface event queue. It is an example of the generic concept of event-driven programming, that is popu ...
in order to ensure the code is executed in a
thread-safe Thread safety is a computer programming concept applicable to multi-threaded code. Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without uni ...
manner. Once the frame is displayed, exiting the main method does not cause the program to terminate because the event dispatching thread remains active until all of the Swing top-level windows have been disposed.


Window with Button

The following is a rather simple Swing-based program. It displays a window (a ) containing a label and a button. import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.WindowConstants; import javax.swing.SwingUtilities; public class SwingExample implements Runnable Notice how all instantiation and handling of Swing components are done by creating an instance of the class, which implements the Runnable interface. This is then run on the Event Dispatch Thread by use of the method ), created in the main method (see Swing and thread safety). Although Swing code can be run without using this technique (for instance, by not implementing Runnable and moving all commands from the run method to the main method), it is considered to be good form, as Swing is not
thread-safe Thread safety is a computer programming concept applicable to multi-threaded code. Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without uni ...
, meaning that invoking resources from multiple threads can result in thread interference and memory consistency errors.


Another example

In this example let javax.swing.JFrame be super class and add our own widget(s) to it (in this case, a JButton). import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Sample extends JFrame The layout is set to null using the method since JFrame uses java.awt.BorderLayout as its default layout-manager. With BorderLayout anything which is added to the container is placed in the center and stretched to accommodate any other widgets. Of course, most real world GUI applications would prefer to use a layout-manager instead of placing everything on absolute co-ordinates.


See also

* swingLabs – Extensions to Swing that might be included in Swing in the future. *
Standard Widget Toolkit The Standard Widget Toolkit (SWT) is a graphical widget toolkit for use with the Java platform. It was originally developed by Stephen Northover at IBM and is now maintained by the Eclipse Foundation in tandem with the Eclipse IDE. It is an alter ...
– A third party widget toolkit maintained by the
Eclipse Foundation The Eclipse Foundation AISBL is an independent, Europe-based not-for-profit corporation that acts as a steward of the Eclipse open source software development community, with legal jurisdiction in the European Union. It is an organization suppo ...
. *
JavaFX JavaFX is a software platform for creating and delivering desktop applications, as well as rich web applications that can run across a wide variety of devices. JavaFX has support for desktop computers and web browsers on Microsoft Windows, Linu ...
– A
software platform A computing platform or digital platform is an environment in which a piece of software is executed. It may be the hardware or the operating system (OS), even a web browser and associated application programming interfaces, or other underlying ...
for creating and delivering desktop applications as well as rich internet applications that can run across a wide variety of devices, which is intended to be the successor to Swing. JavaFX is under the OpenJFX project.
Webswing
- is a web server that allows you to run any Java Swing application inside your web browser, using only pure HTML5.


References


Citations


Sources

* Matthew Robinson, Pavel Vorobiev: ''Swing, Second Edition'', Manning, * David M. Geary: ''Graphic Java 2, Volume 2: Swing'', Prentice Hall, * John Zukowski: ''The Definitive Guide to Java Swing, Third Edition'', Apress, * James Elliott, Robert Eckstein, Marc Loy, David Wood, Brian Cole: ''Java Swing'', O'Reilly, * Kathy Walrath, Mary Campione, Alison Huml, Sharon Zakhour: ''The JFC Swing Tutorial: A Guide to Constructing GUIs'', Addison-Wesley Professional, * Joshua Marinacci, Chris Adamson: ''Swing Hacks'', O'Reilly, * Ivan Portyankin
''Swing, Effective User Interfaces (Russian)''
, 2nd Ed., 2010, Moscow, "Lory",


External links

* {{Widget toolkits Java (programming language) Java (programming language) libraries Java APIs Widget toolkits