Content deleted Content added
Undo vandalism |
|||
(36 intermediate revisions by 22 users not shown) | |||
Line 1:
{{Short description|Java-based GUI toolkit}}
}}▼
▲[[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) – 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.}}
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
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 James Gosling (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> Tim Prinzing, Jonni Kanerva, and Jeannette Hung & Jim Graham (2D Graphics).<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
Swing is a '''component-based framework''', whose components are all ultimately derived from the {{Javadoc
====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.
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
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
====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
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.
For example, the {{Javadoc
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 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
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
import javax.swing.*;
public class Hello extends JFrame {
public Hello() {
super("
}
public static void main(
}
}
</syntaxhighlight>
The first '''<code>import</code>''' includes all the public classes and interfaces from the '''{{Javadoc
The <code>'''Hello'''</code> class <code>'''extends'''</code> the '''{{Javadoc
The <code>'''Hello()'''</code> [[constructor (object-oriented programming)|constructor]] initializes the frame by first calling the superclass constructor, passing the parameter <code>"
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.
===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
<syntaxhighlight lang="java">
Line 141 ⟶ 138:
public class SwingExample implements Runnable {
private JFrame f;
@Override▼
▲ public void run() {
// Create the window
// 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) {
// Schedules the application to be run at the correct time in the event queue.
SwingUtilities.invokeLater(
}
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>
===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
*[[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
== References ==
Line 238 ⟶ 264:
*{{Javadoc:SE-guide|swing|The Swing API documentation}}
{{Java desktop}}
{{Widget toolkits}}
[[Category:Java APIs]]▼
[[Category:Widget toolkits]]
|