Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Swing (Java)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Examples== ===Hello World=== This example Swing application creates a single window with "Hello, world!" inside: <syntaxhighlight lang="java"> // Hello.java (Java SE 8) import javax.swing.*; public class Hello extends JFrame { public Hello() { super("Hello World"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); add(new JLabel("Hello, world!")); pack(); setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(Hello::new); } } </syntaxhighlight> The first '''<code>import</code>''' includes all the public classes and interfaces from the '''{{Javadoc|module=java.desktop|package=javax.swing|monotype=y}}''' package. 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>"Hello 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. 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=== [[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|module=java.desktop|package=javax.swing|class=JFrame|text=JFrame|monotype=y}}) containing a label and a button. <syntaxhighlight lang="java"> 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 { private JFrame f; public SwingExample() { // Create the window f = new JFrame("Hello World!"); // Sets the behavior for when the window is closed f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // Add a layout manager so that the button is not placed on top of the label f.setLayout(new FlowLayout()); // 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(); // By default, the window is not visible. Make it visible. f.setVisible(true); } public static void main(String[] args) { // Schedules the application to be run at the correct time in the event queue. SwingUtilities.invokeLater(new SwingExample()); } } </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>{{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=== In this example let javax.swing.JFrame be super class and add our own widget(s) to it (in this case, a JButton). <syntaxhighlight lang="java"> 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 { private final JButton b = new JButton(); public Sample() { super(); this.setTitle("HelloApp"); this.getContentPane().setLayout(null); this.setBounds(100, 100, 180, 140); this.add(makeButton()); this.setVisible(true); this.setDefaultCloseOperation(EXIT_ON_CLOSE); } private JButton makeButton() { b.setText("Click me!"); b.setBounds(40, 40, 100, 30); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(b, "Hello World!"); } }); return b; } public static void main(String[] args) throws InvocationTargetException, InterruptedException { // Swing calls must be run by the event dispatching thread. SwingUtilities.invokeAndWait(() -> new Sample()); } } </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>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)