Swing (Java): Difference between revisions

Content deleted Content added
Tag: Reverted
Undo vandalism
 
(19 intermediate revisions by 13 users not shown)
Line 1:
{{Short description|Java-based GUI toolkit}}
[[File:Gui-widgets.png|thumb|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 7 ⟶ 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 22 ⟶ 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|module=java.desktop|package=javax.swing|monotype=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 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 55 ⟶ 56:
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|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|module=java.desktop|package=javax.swing|class=JTable|text=JTable|monotype=y}} has a model called {{Javadoc|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]].
Line 78 ⟶ 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 119 ⟶ 120:
The <code>'''Hello'''</code> class <code>'''extends'''</code> the '''{{Javadoc|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|module=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|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|module=java.desktop|package=javax.swing|class=JLabel|text=JLabel|monotype=y}}''' is created for the string '''"Hello, world!"''' and the '''{{Javadoc|module=java.desktop|package=java.awt|class=Container|member=add(java.awt.Component)|text=add(Component)|monotype=y}}''' method inherited from the {{Javadoc|module=java.desktop|package=java.awt|class=Container|text=Container|monotype=y}} superclass is called to add the label to the frame. The '''{{Javadoc|module=java.desktop|package=java.awt|class=Window|text=pack()|member=pack()|monotype=y}}''' method inherited from the {{Javadoc|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 and causes it to be displayed by calling 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 with the boolean parameter <code>'''true'''</code>. The code uses the '''{{Javadoc|module=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===
Line 166 ⟶ 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[] 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);
f 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 211 ⟶ 240:
</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>
===A GridBagLayout example using the Packer subclass of the GridBagLayout Manager===
[[File:Java Swing GridBagLayout example.png|thumb]]
The GridBagLayout class provides a rectangular layout mechanism which is specified using instances of the GridBagConstraints class. This mechanism is very tedious in code because of all the individual lines of code needed to specify the attributes in the GridBagConstraints instances, and the fact that the constraints are not reusable due to each instance used being referenced continuously at runtime. The Packer and PackAs class and interface available at https://github.com/greggwon/Packer, provide a repackaging of the power of this layout manager into a different API. The instances of GridBagConstraints are managed behind the scenes and this makes it much easier to create layouts of components.
 
The name Packer was used because this chaining API style mimics the original TCL/TK "pack" command that this API was designed to mimic when Java was first released and people were using tcl/tk for UIs on lots of different systems.
 
The example application below shows how easy it is to create a 10 line input form using a loop without having to use layered/stacked FlowLayout or other hard coded static layouts.
<syntaxhighlight lang="java">
import javax.swing.*;
import java.awt.*;
import org.wonderly.awt.*;
 
public class ExampleGridbagLayout extends JFrame {
 
public static void main(String args[]) {
ExampleGridbagLayout f = new ExampleGridbagLayout(args);
f.pack();
f.setLocationRelativeTo( null );
f.setVisible(true);
}
 
protected ExampleGridbagLayout( String args[] ) {
Packer pk = new Packer(this);
int y = -1;
for( int i = 0; i < 10; ++i ) {
// On new row
pk.pack( new JLabel("Field #"+(i+1)) ).gridx(0).gridy(++y).inset(0,4,0,4).fillx(0);
pk.pack( new JTextField(10) ).gridx(1).gridy(y).fillx();
}
 
// On new row
pk.pack( new JSeparator() ).gridx(0).gridy(++y).gridw(2).fillx().inset(4,4,4,4);
 
// On new row
pk.pack( new JButton("Cancel") ).gridx(0).gridy(++y).west();
pk.pack( new JButton("Okay") ).gridx(1).gridy(y).east();
}
</syntaxhighlight>
==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 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>
*[https://www.webswing.org Webswing] - is a web server that allows you to run any Java Swing application inside your web browser, using only pure HTML5.
 
== References ==
Line 277 ⟶ 267:
{{Widget toolkits}}
 
[[Category:Java (programming language)]]
[[Category:Java (programming language) libraries]]
[[Category:Java APIs]]
[[Category:Widget toolkits]]
[[Category:JavaJDK APIscomponents]]