Swing (Java): Difference between revisions

Content deleted Content added
Method references weren't a thing prior to Java 8.
Use new {{Javadoc}} template
Line 25:
 
Swing introduced a mechanism that allowed the [[look and feel]] 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]] 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 Platform, Standard Edition|Java Standard Edition]] since release 1.2.<ref>{{cite web|url=http://www.sun.com/smi/Press/sunflash/1998-12/sunflash.981208.9.xml |title=SUN DELIVERS NEXT VERSION OF THE JAVA PLATFORM |date=August 2007 |publisher=[[Sun Microsystems]] |quote=''The Java Foundation Classes are now core to the Java 2 platform and includes:The Project Swing set of GUI components, Drag & Drop, Java 2D API which provides new 2D and AWT graphics capabilities as well as printing support, The Java look and feel interface, A new Accessibility API '' |access-date=2012-01-08 |url-status=unfit |archive-url=https://web.archive.org/web/20070816170028/http://www.sun.com/smi/Press/sunflash/1998-12/sunflash.981208.9.xml |archive-date=August 16, 2007 }}</ref> The Swing classes and components are contained in the {{Javadoc:SE|module=java.desktop|package=javax.swing|javax/swingmonotype=y}} [[Java package|package]] hierarchy.
 
Development of Swing's successor, [[JavaFX]], started in 2005, and it was officially introduced two years later at JavaOne 2007.<ref>{{Cite web|url=https://jaxenter.com/jdk-11-javafx-separate-module-142186.html|title=JDK 11 update: JavaFX will be decoupled from the JDK}}</ref> 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 [[Cascading Style Sheets|CSS]] styling, sleek design controls, and the use of [[FXML]] and Scene Builder.<ref>{{Cite web|url=https://opensourceforu.com/2017/07/developing-basic-gui-application-using-javafx-eclipse/|title=Developing a basic GUI application using JavaFX in Eclipse}}</ref> In 2018, JavaFX was made a part of the OpenJDK under the OpenJFX project to increase the pace of its development.<ref>{{Cite web|url=https://blogs.oracle.com/java-platform-group/the-future-of-javafx-and-other-java-client-roadmap-updates|title=The Future of JavaFX and Other Java Client Roadmap Updates|last=Smith|first=Donald|date=March 7, 2018}}</ref>
Line 38:
 
====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 {{Javadoc:SE|module=java.desktop|package=javax.swing|javax/swingclass=LookAndFeel|text=LookAndFeel|monotype=y}}.
 
Swing is a '''component-based framework''', whose components are all ultimately derived from the {{Javadoc:SE|module=java.desktop|package=javax.swing|javax/swingclass=JComponent|text=JComponent|monotype=y}} 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 the [https://www.oracle.com/java/technologies/javase/javabeans-spec.html JavaBeans specification].
 
====Configurable====
Line 48:
Swing's high level of flexibility is reflected in its inherent ability to override the native host [[operating system]] (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 [[Abstract Window Toolkit|AWT]] container, since (Swing's) {{Javadoc:SE|module=java.desktop|package=javax/.swing|class=JComponent|text=JComponent|monotype=y}} 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 {{Javadoc:SE|module=java.desktop|package=javax/.swing|class=JComponent|text=JComponent|monotype=y}} model.
 
====Loosely coupled and MVC====
The Swing library makes heavy use of the [[model–view–controller]] software [[design pattern (computer science)|design pattern]],<ref>{{cite web |last1=Fowler |first1=Amy |url=https://www.oracle.com/java/technologies/a-swing-architecture.html |title=A Swing Architecture Overview |publisher=[[Sun Microsystems]] |access-date=2020-07-26}}</ref> 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 [[interface (computer science)|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 {{Javadoc:SE|module=java.desktop|package=javax/.swing|class=JComponent|text=JComponent|monotype=y}} 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 [[Data Access Object|DAO]] and/or [[Ejb|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 [[Subclass (computer science)#Subclasses and superclasses|specialization]] into a meaningful event for the GUI component.
 
For example, the {{Javadoc:SE|module=java.desktop|package=javax/.swing|class=JTable|text=JTable|monotype=y}} has a model called {{Javadoc:SE|module=java.desktop|package=javax/.swing/.table|class=TableModel|text=TableModel|monotype=y}} that describes an interface for how a table would access tabular data. A default implementation of this operates on a two-dimensional [[Array data structure|array]].
 
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 version history#Java SE 6|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 [[Abstract Window Toolkit#Mixing AWT and Swing components|Mixing AWT and Swing components]]).
Line 69:
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''.<ref>{{cite web |last1=Zakhour |first1=Sharon |last2=Petrov |first2=Anthony |date=April 2010 |df=mdy |url=https://www.oracle.com/technical-resources/articles/java/mixing-components.html |title=Mixing Heavyweight and Lightweight Components |publisher=[[Oracle Corporation|Oracle]] |access-date=2020-07-26}}</ref>
 
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 ({{Javadoc:SE|module=java.desktop|package=javax/swing|class=JApplet|text=JApplet|monotype=y}}, {{Javadoc:SE|module=java.desktop|package=javax/.swing|class=JDialog|text=JDialog|monotype=y}}, {{Javadoc:SE|module=java.desktop|package=javax/.swing|class=JFrame|text=JFrame|monotype=y}}, and {{Javadoc:SE|module=java.desktop|package=javax/.swing|class=JWindow|text=JWindow|monotype=y}}) extend an AWT top-level container. Prior to [[Java version history#Java SE 6|Java 6 Update 10]], the use of both lightweight and heavyweight components within the same window was generally discouraged due to [[Z-order]] 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]], another part of JFC.
Line 115:
</syntaxhighlight>
 
The first '''<code>import</code>''' includes all the public classes and interfaces from the '''{{Javadoc:SE|module=java.desktop|package=javax.swing|javax/swingmonotype=y}}''' package.
 
The <code>'''Hello'''</code> class <code>'''extends'''</code> the '''{{Javadoc:SE|module=java.desktop|package=javax/.swing|class=JFrame|text=JFrame|monotype=y}}''' class; the <code>JFrame</code> class implements a [[window (computing)|window]] with a [[title bar]] and a close [[Graphical control element|control]].
 
The <code>'''Hello()'''</code> [[constructor (object-oriented programming)|constructor]] initializes the frame by first calling the superclass constructor, passing the parameter <code>"hello"</code>, which is used as the window's title. It then calls the '''{{Javadoc:SE|namemodule=setDefaultCloseOperation(int)java.desktop|package=javax/.swing|class=JFrame|member=setDefaultCloseOperation(int)|text=setDefaultCloseOperation(int)|monotype=y}}''' method inherited from <code>JFrame</code> to set the default operation when the close control on the title bar is selected to '''{{Javadoc:SE|module=java.desktop|package=javax/.swing|class=WindowConstants|member=EXIT_ON_CLOSE|text=WindowConstants.EXIT_ON_CLOSE|monotype=y}}'''{{snd}} this causes the <code>JFrame</code> 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 '''{{Javadoc:SE|module=java.desktop|package=javax/.swing|class=JLabel|text=JLabel|monotype=y}}''' is created for the string '''"Hello, world!"''' and the '''{{Javadoc:SE|namemodule=add(Component)java.desktop|package=java/.awt|class=Container|member=add(java.awt.Component)|text=add(Component)|monotype=y}}''' method inherited from the {{Javadoc:SE|module=java/.desktop|package=java.awt|class=Container|text=Container|monotype=y}} superclass is called to add the label to the frame. The '''{{Javadoc:SE|namemodule=pack()java.desktop|package=java/.awt|class=Window|text=pack()|member=pack()|monotype=y}}''' method inherited from the {{Javadoc:SE|module=java/.desktop|package=java.awt|class=Window|text=Window|monotype=y}} superclass is called to size the window and lay out its contents.
 
The <code>'''main()'''</code> method is called by the Java virtual machine when the program starts. It [[Object (computer science)|instantiates]] a new '''<code>Hello</code>''' frame and causes it to be displayed by calling the '''{{Javadoc:SE|namemodule=setVisible(boolean)java.desktop|package=java/.awt|class=Component|member=setVisible(boolean)|text=setVisible(boolean)|monotype=y}}''' method inherited from the {{Javadoc:SE|module=java/.desktop|package=java.awt|class=Component|text=Component|monotype=y}} superclass with the boolean parameter <code>'''true'''</code>. The code uses the '''{{Javadoc:SE|namemodule=invokeLater(Runnable)java.desktop|package=javax/.swing|class=SwingUtilities|member=invokeLater(java.lang.Runnable)|text=invokeLater(Runnable)|monotype=y}}''' method to invoke the constructor from the AWT [[event dispatching thread]] in order to ensure the code is executed in a [[thread-safe]] manner. Once the frame is displayed, exiting the <code>main</code> 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===
[[File:Swing example on Windows 7.png|thumb|right|The basic example code running on [[Windows 7]]]]
 
The following is a rather simple Swing-based program. It displays a window (a {{Javadoc:SE|module=java.desktop|package=javax/.swing|class=JFrame|text=JFrame|monotype=y}}) containing a label and a button.
 
<syntaxhighlight lang="java">