Swing (Java): Difference between revisions

Content deleted Content added
m Reverted edits by 2601:647:4F00:31F0:A18F:F27A:3C1B:AE7D (talk) to last revision by Mathglot: nonconstructive edits
Tags: Removed redirect Rollback SWViewer [1.4]
Undo vandalism
 
(40 intermediate revisions by 25 users not shown)
Line 1:
{{Short description|Java-based GUI toolkit}}
{{Multiple issues|
[[File:Gui-widgets.png|thumb|300px|Example Swing widgets in Java]]
{{more citations needed|date=May 2010}}
{{original research|date=May 2010}}
}}
 
[[File:Gui-widgets.png|thumb|300px|Example Swing widgets in Java]]
'''Swing''' is a [[Graphical user interface|GUI]] [[widget toolkit]] for [[Java (programming language)|Java]].<ref>{{Cite news|url=https://www.techopedia.com/definition/26102/java-swing|title=What is Java Swing? - Definition from Techopedia|work=Techopedia Inc.|access-date=2018-11-03|language=en}}</ref> It is part of [[Oracle Corporation|Oracle]]'s [[Java Foundation Classes]] (JFC)&nbsp;&ndash; an [[Application programming interface|API]] for providing a [[graphical user interface]] (GUI) for Java programs.
 
Line 11 ⟶ 8:
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 [[Cascading Style Sheets|CSS]] / [[FXML]] based framework that it intended to be the successor to Swing, called [[JavaFX]].<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|date=July 2017 }}</ref>
 
==History==
Line 26 ⟶ 23:
|archive-url = https://web.archive.org/web/20120509230952/http://www2.prnewswire.com/cgi-bin/stories.pl?ACCT=104&STORY=%2Fwww%2Fstory%2F84048&EDATE=
|archive-date = 2012-05-09
}}</ref> The "Java Foundation Classes" were later renamed "Swing."{{Clarify|date=May 2024|reason=The JFC FAQ page at https://www.oracle.com/java/technologies/foundation-classes-faq.html describes Swing as being one component of the JFC alongside AWT etc. This was my understanding: that Swing is one part of the JFC rather than the two being synonymous. Are they sometimes treated as such because the changes to Java that added the JFC are the same ones that added Swing, so it's a little blurred? Are there any sources we can cite with regard to this claim that the JFC were renamed to Swing? I think JFC is a term currently in use.}}
}}</ref> The "Java Foundation Classes" were later renamed "Swing."
 
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|archive-url=https://web.archive.org/web/20190326211553/https://jaxenter.com/jdk-11-javafx-separate-module-142186.html|archive-date=2019-03-26|title=JDK 11 update: JavaFX will be decoupled from the JDK|date=March 8, 2018 |author=Gabriela Motroc}}</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|date=July 2017 }}</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>
 
Members of the Java Client team that was responsible for Swing included JeffJames DinkinsGosling (Architect), Rick Levenson (manager), Amy Fowler & Hans Muller (co-technical leads), Tom Ball, Jeff Dinkins, Georges Saab,<ref>{{cite web |last1=Zakhour |first1=Sharon |title=Why is Swing Called Swing? |url=https://blogs.oracle.com/thejavatutorials/why-is-swing-called-swing |website=The Java Tutorials Blog |access-date=24 September 2020}}</ref> Jim Graham, Rick Levenson, Tim Prinzing, Jonni Kanerva, and Jeannette Hung, Tom& Ball,Jim and Amy FowlerGraham (technical2D leadGraphics).<ref>{{cite web |last1=John |first1=Yu |title=Rich clients emerge as alternatives for Web applications |url=https://www.computerworld.com/article/2571634/rich-clients-emerge-as-alternatives-for-web-applications.html |website=ComputerWorld |date=27 August 2003 |access-date=24 September 2020}}</ref>
 
==Architecture==
Line 42 ⟶ 39:
 
====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====
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]] 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]] (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,wat 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 Update 10|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]]).
 
Finally, in terms of visual composition and management, Swing favors [[Layout manager|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 [[Java applet|applet]] 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.)
Line 73 ⟶ 70:
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 Update 10|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 82 ⟶ 79:
The [[Standard Widget Toolkit]] (SWT) is a competing toolkit originally developed by [[IBM]] and now maintained by the [[Eclipse (software)|Eclipse]] [[Free software community|community]]. 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 [[Java Native Interface|JNI]] 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.<ref>{{cite web |last1=Strenn |first1=Stephen |date=2006-03-03 |df=mdy |url=http://www.javalobby.org/java/forums/t65168.html |title=Swing vs. SWT Performance - Have a Look at the Call Stacks |work=Javalobby |url-status=usurped |archive-url=https://web.archive.org/web/20170917172003/http://www.javalobby.org/java/forums/t65168.html |archive-date=2017-09-17}}</ref> A fairly thorough set of benchmarks in 2005 concluded that neither Swing nor SWT clearly outperformed the other in the general case.<ref>{{cite web
|last1=Žagar |first1=Klemen
|last2=Križnar |first2=Igor
Line 101 ⟶ 98:
 
<syntaxhighlight lang="java">
// Hello.java (Java SE 58)
import javax.swing.*;
 
public class Hello extends JFrame {
public Hello() {
super("helloHello World");
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.add(new JLabel("Hello, world!"));
this.pack();
this.setVisible(true);
}
 
public static void main(final String[] args) {
new HelloSwingUtilities.invokeLater(Hello::new);
}
}
</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>"helloHello World"</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 '''{{Javadoc|module=java.desktop|package=java.awt|class=Component|member=setVisible(boolean)|text=setVisible(boolean)|monotype=y}}''' method inherited from the {{Javadoc|module=java.desktop|package=java.awt|class=Component|text=Component|monotype=y}} superclass is called with the Boolean parameter <code>'''true'''</code>, which causes the frame to be displayed.
 
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. andThe causes it to be displayed bycode callinguses the '''{{Javadoc:SE|namemodule=setVisible(boolean)|java/awt.desktop|Componentpackage=javax.swing|setVisibleclass=SwingUtilities|member=invokeLater(booleanjava.lang.Runnable)|text=invokeLater(Runnable)|monotype=y}}''' method inheritedto invoke the constructor from the {{Javadoc:SE|java/awt|Component}}AWT superclass[[event withdispatching thethread]] booleanin parameterorder to ensure the <code>'''true'''</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 AWT [[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">
Line 141 ⟶ 138:
public class SwingExample implements Runnable {
private JFrame f;
 
public void runSwingExample() {
@Override
public void run() {
// Create the window
JFrame f = new JFrame("Hello, World!");
// Sets the behavior for when the window is closed
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Line 152 ⟶ 148:
// Add a label and a button
f.add(new JLabel("Hello, world!"));
f.add(new JButton("Press me!"));
}
 
@Override
public void run() {
// Arrange the components inside the window
f.pack();
Line 160:
public static void main(String[] args) {
SwingExample se = new SwingExample();
// Schedules the application to be run at the correct time in the event queue.
SwingUtilities.invokeLater(senew SwingExample());
}
 
Line 168 ⟶ 167:
</syntaxhighlight>
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 {{Javadoc:SE|member=invokeLater(Runnable)|javax/swing|SwingUtilities|invokeLater(java.lang.Runnable)|module=java.desktop}}), created in the main method (see [[Event dispatching thread#Swing and thread safety|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 safety|thread-safe]], meaning that invoking resources from multiple threads can result in thread interference and memory consistency errors.<ref>http{{Cite web|url=https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html |title=The Event Dispatch Thread|website=docs.oracle.com}}</ref>
 
===Text Field===
 
Text fields enable users to input text or data into your application. Creating a text field in Swing is straightforward – instantiate a JTextField object and add it to a container.
<syntaxhighlight lang="java">
import javax.swing.*;
 
public class TextFieldExample {
public static void main(String[] args) {
// Create a JFrame
JFrame frame = new JFrame("Text Field Example");
 
// Create a JTextField
JTextField textField = new JTextField(20);
 
// Add the text field to the JFrame
frame.add(textField);
 
// Set the size of the JFrame and make it visible
frame.setSize(300, 200);
frame.setVisible(true);
}
}}
</syntaxhighlight>
 
Enhancing functionality in text fields improves user interaction. By attaching DocumentListener interfaces, you can dynamically monitor changes in the text content, enabling real-time validation, formatting, or auto-completion of input data.
 
Validating text field input is crucial for ensuring data integrity and preventing errors. Swing provides multiple validation techniques, including regular expressions, input masks, or custom validation logic. By implementing InputVerifier interfaces, you can define specific validation rules and offer immediate feedback to users when input is invalid.<ref>https://geeksprogramming.com/java-swing-tutorial-for-beginners/ The Event Dispatch Thread</ref>
 
===Another example===
Line 206 ⟶ 233:
}
 
public static void main(String[] args) throws InvocationTargetException, InterruptedException {
// Swing calls must be run by the event dispatching thread.
SwingUtilities.invokeAndWait(() -> new Sample());
Line 212 ⟶ 239:
}
</syntaxhighlight>
The layout is set to null using the {{Javadoc:SE|member=setLayout(LayoutManager)|java/awt|Container|setLayout(java.awt.LayoutManager)|module=java.desktop}} 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.<ref>{{cite book|last1=Eckel|first1=Bruce|title=Thinking in Java|date=2006|publisher=Prentice Hall|isbn=978-0131872486|page=942|edition=4|url=http://www.agentgroup.unimore.it/~nicola/courses/IngegneriaDelSoftware/java/books/ThinkingInJava.pdf|access-date=13 May 2016|url-status=dead|archive-url=https://web.archive.org/web/20160514000820/http://www.agentgroup.unimore.it/~nicola/courses/IngegneriaDelSoftware/java/books/ThinkingInJava.pdf|archive-date=14 May 2016}}</ref>
 
==See also==
*[[swingLabs]] – Extensions to Swing that might be included in Swing in the future.
*[[Standard Widget Toolkit]] – A third party widget toolkit maintained by the [[Eclipse Foundation]].
*[[JavaFX]] – A [[software platform]] for creating and delivering [[desktop applications]] as well as [[Rich Internet Application|rich internet applications]] that can run across a wide variety of devices, which is intended to be the successor to Swing. JavaFX is currently part of the [[OpenJDK]], under the [[OpenJFX]] project.<ref>{{cite web |title=JavaFX Developer Home |url=https://www.oracle.com/technetwork/java/javase/overview/javafx-overview-2158620.html |website=www.oracle.com}}</ref>
 
== References ==
Line 237 ⟶ 264:
*{{Javadoc:SE-guide|swing|The Swing API documentation}}
 
{{Java desktop}}
{{Widget toolkits}}
 
[[Category:Java (programming language)]]
[[Category:Java (programming language) libraries]]
[[Category:Java APIs]]
[[Category:Widget toolkits]]
[[Category:JavaJDK APIscomponents]]