Chuyển tới nội dung
Home » Swing In Advanced Java | The Mvc Connection

Swing In Advanced Java | The Mvc Connection

Java Swing For Beginners | What is Java Swing | Java Swing Tutorial | Intellipaat

Kết luận:

Trong bài viết trên, chúng ta đã thảo luận về Java Swing là gì, hệ thống phân cấp các lớp Swing Java.

Với tất cả các thành phần đi kèm với Swing trong Java, việc xây dựng các ứng dụng GUI được tối ưu hóa trở nên dễ dàng hơn.

Hy vọng thông qua bài viết này các bạn đã hiểu về Swing và biết cách ứng dụng nó khi sử dụng ngôn ngữ lập trình Java.

Và nếu bạn muốn tìm hiểu rõ hơn ngôn ngữ này, có thể tham gia ngay khóa học lập trình Java của Ironhack Việt Nam

Chúc các bạn thành công.

  • SWING Tutorial
  • SWING – Home
  • SWING – Overview
  • SWING – Environment
  • SWING – Controls
  • SWING – Event Handling
  • SWING – Event Classes
  • SWING – Event Listeners
  • SWING – Event Adapters
  • SWING – Layouts
  • SWING – Menu
  • SWING – Containers
  • SWING Useful Resources
  • SWING – Quick Guide
  • SWING – Useful Resources
  • SWING – Discussion

SWING – Overview

Swing API is a set of extensible GUI Components to ease the developer’s life to create JAVA based Front End/GUI Applications. It is build on top of AWT API and acts as a replacement of AWT API, since it has almost every control corresponding to AWT controls. Swing component follows a Model-View-Controller architecture to fulfill the following criterias.

  • A single API is to be sufficient to support multiple look and feel.

  • API is to be model driven so that the highest level API is not required to have data.

  • API is to use the Java Bean model so that Builder Tools and IDE can provide better services to the developers for use.

References[edit]

Citations[edit]

  1. ^ “What is Java Swing? – Definition from Techopedia”. Techopedia Inc. Retrieved 2018-11-03.
  2. ^ Yap, Chee (2003-04-30). “JAVA SWING GUI TUTORIAL”. New York University (NYU). Retrieved 2018-11-03.
  3. ^ “Developing a basic GUI application using JavaFX in Eclipse”. July 2017.
  4. ^ “Sun and Netscape to jointly develop Java Foundation Classes”. Netscape Communications Corporation. 1997-04-02. Archived from the original on 2012-05-09. Retrieved 2011-08-08.
  5. ^ “SUN DELIVERS NEXT VERSION OF THE JAVA PLATFORM”. Sun Microsystems. August 2007. Archived from the original on August 16, 2007. Retrieved 2012-01-08.

    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


    {{cite web}}

    : CS1 maint: unfit URL (link)

  6. ^ “JDK 11 update: JavaFX will be decoupled from the JDK”.
  7. ^ “Developing a basic GUI application using JavaFX in Eclipse”. July 2017.
  8. ^ Smith, Donald (March 7, 2018). “The Future of JavaFX and Other Java Client Roadmap Updates”.
  9. ^ Zakhour, Sharon. “Why is Swing Called Swing?”. The Java Tutorials Blog. Retrieved 24 September 2020.
  10. ^ John, Yu (27 August 2003). “Rich clients emerge as alternatives for Web applications”. ComputerWorld. Retrieved 24 September 2020.
  11. ^ Zukowski, John (August 21, 2007). “Swing threading and the event-dispatch thread”. JavaWorld. Retrieved 2020-07-26.
  12. ^ Fowler, Amy. “A Swing Architecture Overview”. Sun Microsystems. Retrieved 2020-07-26.
  13. ^ Zakhour, Sharon; Petrov, Anthony (April 2010). “Mixing Heavyweight and Lightweight Components”. Oracle. Retrieved 2020-07-26.
  14. ^ Strenn, Stephen (March 3, 2006). “Swing vs. SWT Performance – Have a Look at the Call Stacks”. Javalobby. Archived from the original on 2017-09-17.
  15. ^ Žagar, Klemen; Križnar, Igor (March 3, 2006). “SWT Vs. Swing Performance Comparison” (PDF) (1.4 ed.). Cosylab. Archived from the original (PDF) on 2015-05-26.

    It is hard to give a rule-of-thumb where SWT would outperform Swing, or vice versa. In some environments (e.g., Windows), SWT is a winner. In others (Linux, VMware hosting Windows), Swing and its redraw optimization outperform SWT significantly. Differences in performance are significant: factors of 2 and more are common, in either direction.

  16. ^ http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html The Event Dispatch Thread
  17. ^ Eckel, Bruce (2006). Thinking in Java (PDF) (4 ed.). Prentice Hall. p. 942. ISBN 978-0131872486. Archived from the original (PDF) on 14 May 2016. Retrieved 13 May 2016.
  18. ^ “JavaFX Developer Home”. www.oracle.com.

Sources[edit]

  • Matthew Robinson, Pavel Vorobiev: Swing, Second Edition, Manning, ISBN 1-930110-88-X
  • David M. Geary: Graphic Java 2, Volume 2: Swing, Prentice Hall, ISBN 0-13-079667-0
  • John Zukowski: The Definitive Guide to Java Swing, Third Edition, Apress, ISBN 1-59059-447-9
  • James Elliott, Robert Eckstein, Marc Loy, David Wood, Brian Cole: Java Swing, O’Reilly, ISBN 0-596-00408-7
  • Kathy Walrath, Mary Campione, Alison Huml, Sharon Zakhour: The JFC Swing Tutorial: A Guide to Constructing GUIs, Addison-Wesley Professional, ISBN 0-201-91467-0
  • Joshua Marinacci, Chris Adamson: Swing Hacks, O’Reilly, ISBN 0-596-00907-0
  • Ivan Portyankin, Swing, Effective User Interfaces (Russian)., 2nd Ed., 2010, Moscow, “Lory”, ISBN 5-469-00005-2

Overview

Test Series

Java, a stalwart in the realm of programming languages, is extensively used for creating versatile applications. AWT and Swing, two significant terminologies in Java, play a pivotal role in developing window-based applications. Let’s delve into the primary distinctions between AWT and Swing in Java.

Get 6 Months SuperCoaching @ just

₹2499₹1599

AWT, an acronym for “Abstract Window Toolkit”, is an API designed to facilitate the development of window-based applications in Java. It comprises a plethora of elements such as classes, methods, labels, text fields, buttons, etc., that are instrumental in designing and managing GUI.

Swing, a part of Oracle’s Java Foundation Classes, is a graphical user interface (GUI) used to design various applications. Developed with an aim to provide an advanced set of GUI components, Swing encompasses components like JTextField, JCheckbox, JMenu, etc.

S.No. AWT SWING
1. AWT stands for Abstract Window Toolkit. Swing doesn’t have a full form.
2. AWT is an API used for developing window-based applications in Java. Swing is a GUI and a part of Oracle’s Java Foundation Classes, used for application design.
3. AWT components are heavy-weighted. Swing components are light-weighted.
4. AWT components are platform-dependent. Swing components are platform-independent.
5. AWT has less functionality compared to Swing. Swing has more functionality than AWT.
6. AWT requires more execution time. Swing requires less execution time.
7. AWT has less powerful components compared to Swing. Swing boasts more powerful components than AWT.
8. AWT does not support the MVC pattern. Swing supports the MVC pattern.

Continue your learning journey and stay updated with the latest information on GATE Exam , including GATE Eligibility Criteria , GATE 2023 , GATE Admit Card , GATE Syllabus , GATE Previous Year Question Paper , and more.

Further Reading,

Sign Up Now &

The Advanced Java Swing Programming training course is designed to demonstrate an in-depth understanding of Java Swing programming.

The course begins by focusing on the more complex JFC components, like JTree and JTable. Next, it examines the Pluggable-Look-And-Feel (PLAF) framework, custom component development using the Model-View-Controller (MVC) Delegate architecture. The course concludes with a description of usability and Graphical User Interface (GUI) design principles.

Purpose
Learn how to create custom, reusable, Graphical User Interface (GUI) Swing components.
Audience
Experienced Java Swing Programmers looking to advance their Java GUI programming capabilities.
Role
Software Developer
Skill Level
Advanced
Style
Fast Track – Targeted Topic – Workshops
Duration
2 Days
Related Technologies
Java | Java Swing / JFC
Productivity Objectives
  • Describe the Java Swing component library architecture
  • Implement drag-n-drop and cut-copy-paste using the data-transfer model
  • Manipulate the 2D Graphics Application Programming Interface (API)
  • Apply Swing utilities to create a more responsive User Interface (UI)
  • Design a Swing component by extending JComponent

Last Updated on March 22, 2023 by Prepbytes

Java Swing is a popular framework for creating Graphical User Interfaces (GUI) in Java. It is a part of the Java Foundation Classes (JFC) and is widely used for developing desktop applications. This article discusses Java Swing, the features of Java Swing, Java Swing packages, the difference between Java Swing and Java AWT, and the advantages and disadvantages of Java Swing.

Java Swing For Beginners | What is Java Swing | Java Swing Tutorial | Intellipaat
Java Swing For Beginners | What is Java Swing | Java Swing Tutorial | Intellipaat

Java


import


java.awt.*;


class


Lan {


Lan()


Frame f =


new


Frame();


Label l1 =


new


Label(


"Select known Languages"


);


l1.setBounds(


100


50


120


80


);


f.add(l1);


Checkbox c2 =


new


Checkbox(


"Hindi"


);


c2.setBounds(


100


150


50


50


);


f.add(c2);


Checkbox c3 =


new


Checkbox(


"English"


);


c3.setBounds(


100


200


80


50


);


f.add(c3);


Checkbox c4 =


new


Checkbox(


"marathi"


);


c4.setBounds(


100


250


80


50


);


f.add(c4);


f.setSize(


500


500


);


f.setLayout(


null


);


f.setVisible(


true


);


public


static


void


main(String ar[]) {


new


Lan(); }

Output:

Examples[edit]

Hello World[edit]

This example Swing application creates a single window with “Hello, world!” inside:

// 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); } }

The first

import

includes all the public classes and interfaces from the

javax.swing

package.

The

Hello

class

extends

the

JFrame

class; the

JFrame

class implements a window with a title bar and a close control.

The

Hello()

constructor initializes the frame by first calling the superclass constructor, passing the parameter

"Hello World"

, which is used as the window’s title. It then calls the

setDefaultCloseOperation(int)

method inherited from

JFrame

to set the default operation when the close control on the title bar is selected to

WindowConstants.EXIT_ON_CLOSE

– this causes the

JFrame

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

JLabel

is created for the string “Hello, world!” and the

add(Component)

method inherited from the

Container

superclass is called to add the label to the frame. The

pack()

method inherited from the

Window

superclass is called to size the window and lay out its contents. The

setVisible(boolean)

method inherited from the

Component

superclass is called with the boolean parameter

true

, which causes the frame to be displayed.

The

main()

method is called by the Java virtual machine when the program starts. It instantiates a new

Hello

frame. The code uses the

invokeLater(Runnable)

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

main

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[edit]

The following is a rather simple Swing-based program. It displays a window (a

JFrame

) containing a label and a button.

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()); } }

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

SwingUtilities.invokeLater(Runnable)

), created in the main method (see 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-safe, meaning that invoking resources from multiple threads can result in thread interference and memory consistency errors.[16]

Another example[edit]

In this example let javax.swing.JFrame be super class and add our own widget(s) to it (in this case, a JButton).

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()); } }

The layout is set to null using the

Container.setLayout(LayoutManager)

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.[17]

Java Swings Introduction, Difference between AWT and Swings, Important Methods of Component Class
Java Swings Introduction, Difference between AWT and Swings, Important Methods of Component Class

What is Java Swing?

Java Swing is a popular and powerful Graphical User Interface (GUI) toolkit that is used for developing desktop applications. It is a part of the Java Foundation Classes (JFC) and provides a rich set of components and layout managers for creating a variety of GUIs. Java Swing is platform-independent and can be used on any operating system that supports Java.

It provides a set of lightweight components that are not only easy to use but also customizable. Some of the commonly used components in Swing are buttons, text fields, labels, menus, and many more.

Java Swing provides a pluggable look and feels that allows developers to customize the GUI according to the user’s preferences. It also provides a robust event-handling mechanism that allows developers to handle events generated by the graphical components.

Some of the commonly used layout managers in Java Swing are BorderLayout, FlowLayout, GridLayout, CardLayout, and BoxLayout. These layout managers allow developers to create complex and intuitive GUIs that are easy to use and navigate.

Features of Java Swing

Some of the notable features of Java Swing are:

  1. Platform Independence: Platform independence is one of Java Swing’s most remarkable features. It can run on any platform that supports Java. Thus, Swing-based applications can run on Windows, Mac, Linux, or any other Java-compatible operating system.
  2. Lightweight Components: Java Swing provides a set of lightweight components that are easy to use and customizable. These components are designed to consume less memory and use less processing power, making Swing-based applications run efficiently.
  3. Pluggable Look and Feel: Java Swing provides a pluggable look and feels that allows developers to customize the appearance of the GUI according to the user’s preferences. Developers can choose from several pre-built looks and feel themes or create their own custom themes.
  4. Layout Managers: Java Swing provides a set of layout managers that can be used to organize the graphical components in a GUI. These layout managers enable developers to create flexible and responsive GUIs that adapt to different screen sizes and resolutions.
  5. Robust Event Handling Mechanism: Java Swing provides a robust event handling mechanism that allows developers to handle events generated by the graphical components. Developers can register event listeners to detect and respond to user interactions with the GUI.

Java Swing Class Hierarchy

The Java Swing API hierarchy is shown below:

Java Swing Packages

Some of the commonly used packages in Java Swing are:

  1. javax.swing: This package contains the core components of Swing, such as JButton, JLabel, JTable, JList, and many more. It also contains the classes for creating top-level containers such as JFrame and JDialog.
  2. javax.swing.event: This package contains the classes for handling events generated by the Swing components. It includes event listener interfaces, event adapter classes, and event objects.
  3. javax.swing.border: This package contains classes for creating borders around the Swing components. It includes the classes for creating line borders, etched borders, and titled borders.
  4. javax.swing.layout: This package contains the classes for creating and managing layout managers in Swing. It includes the commonly used layout managers such as BorderLayout, FlowLayout, GridLayout, BoxLayout, and CardLayout.
  5. javax.swing.plaf: This package contains the classes for the pluggable look and feels feature of Swing. It includes the classes for creating and managing the look and feel themes, and also provides the default look and feel theme for each platform.
  6. javax.swing.text: This package contains the classes for creating and managing text components in Swing. It includes classes for creating text fields, text areas, and other text-related components.
  7. javax.swing.table: This package contains the classes for creating and managing tables in Swing. It includes the classes for creating JTable, TableModel, TableColumn, and TableCellRenderer.

Components of Java Swing

Some of the important and common components of the Java Swing class are:

  1. JFrame: JFrame is a top-level container that represents the main window of a GUI application. It provides a title bar, and minimizes, maximizes, and closes buttons.
  2. JPanel: JPanel is a container that can hold other components. It is commonly used to group related components together.
  3. JButton: JButton is a component that represents a clickable button. It is commonly used to trigger actions in a GUI application.
  4. JLabel: JLabel is a component that displays text or an image. It is commonly used to provide information or to label other components.
  5. JTextField: JTextField is a component that allows the user to input text. It is commonly used to get input from the user, such as a name or an address.
  6. JCheckBox: JCheckBox is a component that represents a checkbox. It is commonly used to get a binary input from the user, such as whether or not to enable a feature.
  7. JList: JList is a component that represents a list of elements. It is typically used to display a list of options from which the user can select one or more items.
  8. JTable: JTable is a component that represents a data table. It is typically used to present data in a tabular fashion, such as a list of products or a list of orders.
  9. JScrollPane: JScrollPane is a component that provides scrolling functionality to other components. It is commonly used to add scrolling to a panel or a table.

Difference between Java Swing and Java AWT

Here is a comparison of Java Swing and Java AWT:

Feature Java Swing Java AWT
Architecture Platform-Independent Platform-Dependent
Look and Feel Pluggable look and feel Native look and feel
Components Richer set of components Basic set of components
Performance Slower due to software rendering Faster due to native OS rendering
Event Model More flexible and powerful Simpler and less powerful
Thread Safety By default, it is not thread-safe Thread-safe by default
Customization Highly customizable Less customizable
Layout Managers More layout managers are available Fewer layout managers are available
API Extensive API with many features Basic API with fewer features
Graphics Support It supports more advanced graphics It only supports basic graphics
File Size Size is large due to additional APIs Size is small due to fewer APIs and classes

Advantages of Java Swing

Java Swing provides a number of advantages for developing graphical user interfaces (GUIs) in Java. Some of the key advantages of Java Swing are

  1. Platform Independence: Swing is written entirely in Java, which makes it platform-independent. It can run on any platform that supports Java, without any modification.
  2. Look and Feel: Java Swing provides a pluggable look and feels feature, which allows developers to customize the appearance of the components. It provides a consistent look and feels across platforms, which helps in creating a professional-looking GUI.
  3. Rich Component Set: Java Swing provides a rich set of components, including advanced components like JTree, JTable, and JSpinner. It also provides support for multimedia components, such as audio and video.
  4. Layout Managers: Java Swing provides a variety of layout managers, which makes it easy to arrange the components on a GUI. The layout managers help in creating GUIs that are visually appealing and easy to use.
  5. Event Handling: Java Swing provides a powerful and flexible event handling model, which makes it easy to handle user events such as mouse clicks and keyboard presses. The event-handling model makes it easy to add interactivity to the GUI.
  6. Customizable: Java Swing components are highly customizable, which makes it easy to create GUIs that meet the specific needs of an application. The components can be easily modified to suit the look and feel of the application.

Disadvantages of Java Swing

Some of the main disadvantages of Java Swing are:

  1. Performance: Java Swing applications can be slower than native applications because of the overhead of running the Java Virtual Machine (JVM). This can be particularly noticeable in complex applications with large amounts of data.
  2. Look and Feel: While Swing’s pluggable look and feel feature allows for customization of the components, it can be difficult to achieve a truly native look and feel. This can make Swing applications look and feel different from other native applications on the same platform, which can be confusing for users.
  3. Learning Curve: While Swing is easy to learn for developers who are already familiar with Java, it can be difficult for beginners who are not familiar with the language. The complex hierarchy of components and layout managers can also make it difficult to create complex GUIs.
  4. Resource Consumption: Java Swing applications often requires a significant amount of system resources, such as memory and computing power. This can be an issue for low-end devices with limited resources or large-scale apps with a big number of users.
  5. Lack of Mobile Support: Since Java Swing is a desktop-oriented GUI toolkit, it does not support mobile devices well. This could pose a potential challenge for developers who want to create cross-platform apps that work on both desktop and mobile platforms.

ConclusionIn conclusion, Java Swing is a powerful GUI toolkit that provides a rich set of components for creating desktop applications. Java Swing is a popular choice for desktop applications, and it continues to be widely used by developers worldwide. Ultimately, the choice of whether to use Swing or another GUI toolkit depends on the specific needs of the application and the preferences of the developer.

Full Stack Web Development Internship Program

  • 29k Enrolled Learners
  • Weekend/Weekday
  • Live Class

Swing in java is part of Java foundation class which is lightweight and platform independent. It is used for creating window based applications. It includes components like button, scroll bar, text field etc. Putting together all these components makes a graphical user interface. In this article, we will go through the concepts involved in the process of building applications using swing in Java. Following are the concepts discussed in this article:

Swing in Java is a lightweight GUI toolkit which has a wide variety of widgets for building optimized window based applications. It is a part of the JFC( Java Foundation Classes). It is build on top of the AWT API and entirely written in java. It is platform independent unlike AWT and has lightweight components.

It becomes easier to build applications since we already have GUI components like button, checkbox etc. This is helpful because we do not have to start from the scratch.

Any class which has other components in it is called as a container class. For building GUI applications at least one container class is necessary.

Following are the three types of container classes:

Panel – It is used to organize components on to a window

Frame – A fully functioning window with icons and titles

Dialog – It is like a pop up window but not fully functional like the frame

AWT SWING

Explanation: All the components in swing like JButton, JComboBox, JList, JLabel are inherited from the JComponent class which can be added to the container classes. Containers are the windows like frame and dialog boxes. Basic swing components are the building blocks of any gui application. Methods like setLayout override the default layout in each container. Containers like JFrame and JDialog can only add a component to itself. Following are a few components with examples to understand how we can use them.

It is used to create a labelled button. Using the ActionListener it will result in some action when the button is pushed. It inherits the AbstractButton class and is platform independent.

Example:

import javax.swing.*; public class example{ public static void main(String args[]) { JFrame a = new JFrame(“example”); JButton b = new JButton(“click me”); b.setBounds(40,90,85,20); a.add(b); a.setSize(300,300); a.setLayout(null); a.setVisible(true); } }

Output:

It inherits the JTextComponent class and it is used to allow editing of single line text.

Example:

import javax.swing.*; public class example{ public static void main(String args[]) { JFrame a = new JFrame(“example”); JTextField b = new JTextField(“edureka”); b.setBounds(50,100,200,30); a.add(b); a.setSize(300,300); a.setLayout(null); a.setVisible(true); } }

Output:

It is used to add scroll bar, both horizontal and vertical.

Example:

import javax.swing.*; class example{ example(){ JFrame a = new JFrame(“example”); JScrollBar b = new JScrollBar(); b.setBounds(90,90,40,90); a.add(b); a.setSize(300,300); a.setLayout(null); a.setVisible(true); } public static void main(String args[]){ new example(); } }

Output:

It inherits the JComponent class and provides space for an application which can attach any other component.

import java.awt.*; import javax.swing.*; public class Example{ Example(){ JFrame a = new JFrame(“example”); JPanel p = new JPanel(); p.setBounds(40,70,200,200); JButton b = new JButton(“click me”); b.setBounds(60,50,80,40); p.add(b); a.add(p); a.setSize(400,400); a.setLayout(null); a.setVisible(true); } public static void main(String args[]) { new Example(); } }

Output:

It inherits the JMenuItem class, and is a pull down menu component which is displayed from the menu bar.

import javax.swing.*; class Example{ JMenu menu; JMenuItem a1,a2; Example() { JFrame a = new JFrame(“Example”); menu = new JMenu(“options”); JMenuBar m1 = new JMenuBar(); a1 = new JMenuItem(“example”); a2 = new JMenuItem(“example1”); menu.add(a1); menu.add(a2); m1.add(menu); a.setJMenuBar(m1); a.setSize(400,400); a.setLayout(null); a.setVisible(true); } public static void main(String args[]) { new Example(); } }

Output:

It inherits JComponent class, the object of JList class represents a list of text items.

import javax.swing.*; public class Example { Example(){ JFrame a = new JFrame(“example”); DefaultListModel

l = new DefaultListModel< >(); l.addElement(“first item”); l.addElement(“second item”); JList

b = new JList< >(l); b.setBounds(100,100,75,75); a.add(b); a.setSize(400,400); a.setVisible(true); a.setLayout(null); } public static void main(String args[]) { new Example(); } }

Output:

It is used for placing text in a container. It also inherits JComponent class.

import javax.swing.*; public class Example{ public static void main(String args[]) { JFrame a = new JFrame(“example”); JLabel b1; b1 = new JLabel(“edureka”); b1.setBounds(40,40,90,20); a.add(b1); a.setSize(400,400); a.setLayout(null); a.setVisible(true); } }

Output:

It inherits the JComponent class and is used to show pop up menu of choices.

import javax.swing.*; public class Example{ JFrame a; Example(){ a = new JFrame(“example”); string courses[] = { “core java”,”advance java”, “java servlet”}; JComboBox c = new JComboBox(courses); c.setBounds(40,40,90,20); a.add(c); a.setSize(400,400); a.setLayout(null); a.setVisible(true); } public static void main(String args[]) { new Example(); } }

Output:

To arrange the components inside a container we use the layout manager. Following are several layout managers:

Border layout

Flow layout

GridBag layout

The default layout manager for every JFrame is BorderLayout. It places components in upto five places which is top, bottom, left, right and center.

FlowLayout simply lays the components in a row one after the other, it is the default layout manager for every JPanel.

GridBagLayout places the components in a grid which allows the components to span more than one cell.

import javax.swing.*; import java.awt.*; class Example { public static void main(String args[]) { JFrame frame = new JFrame(“Chat Frame”); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 400); JMenuBar ob = new JMenuBar(); JMenu ob1 = new JMenu(“FILE”); JMenu ob2 = new JMenu(“Help”); ob.add(ob1); ob.add(ob2); JMenuItem m11 = new JMenuItem(“Open”); JMenuItem m22 = new JMenuItem(“Save as”); ob1.add(m11); ob1.add(m22); JPanel panel = new JPanel(); // the panel is not visible in output JLabel label = new JLabel(“Enter Text”); JTextField tf = new JTextField(10); // accepts upto 10 characters JButton send = new JButton(“Send”); JButton reset = new JButton(“Reset”); panel.add(label); // Components Added using Flow Layout panel.add(label); // Components Added using Flow Layout panel.add(tf); panel.add(send); panel.add(reset); JTextArea ta = new JTextArea(); frame.getContentPane().add(BorderLayout.SOUTH, panel); frame.getContentPane().add(BorderLayout.NORTH, tf); frame.getContentPane().add(BorderLayout.CENTER, ta); frame.setVisible(true); } }

This is a simple example for creating a GUI using swing in Java.

If you’re just beginning, then watch at this Java Tutorial to Understand the Fundamental Java Concepts.

In this article we have discussed swing in Java and hierarchy of Java swing classes. With all the components which comes with swing in Java, it becomes easier to build optimized GUI applications. Java programming language is a structured programming language and with the increasing demand it becomes extremely important to master all the concepts in Java programming. To kick-start your learning and to become an expert in java programming, enroll to Edureka’s Java Certification program.

Got a question for us? please mention this in the comments section of this ‘Swing In Java’ article and we will get back to you as soon as possible.

Course Name Date Details
Java Certification Training Course

Class Starts on 24th February,2024

24th February

SAT&SUN (Weekend Batch)

View Details
Java Certification Training Course

Class Starts on 30th March,2024

30th March

SAT&SUN (Weekend Batch)

View Details

edureka.co

Nội dung

Ngôn ngữ lập trình Java là một ngôn ngữ lập trình có nhu cầu sử dụng ngày càng cao, do đó việc nắm vững tất cả các khái niệm trong lập trình Java trở nên vô cùng quan trọng.

Swing là một trong số những khái niệm quan trọng trong Java.

Nó là một bộ công cụ có trọng lượng nhẹ, hỗ trợ các nhà lập trình tạo giao diện đồ hoạ người dùng.

Trong bài này chúng ta sẽ đi qua cái khái niệm về Java Swing và cách ứng dụng chúng nhé!

Cafe Management System Project | Java Swing | NetBeans
Cafe Management System Project | Java Swing | NetBeans

Các phương thức được sử dụng phổ biến của Component Class

Có một số phương thức trong lớp Component được sử dụng khá phổ biến, đó là:

Phương thức Mục đích
public void add(Component c) Bổ sung một thành phần trên một phần khác
public void setSize(int width,int height) Để cài đặt và tùy chỉnh kích cỡ của thành phần (chiều rộng, chiều cao)
public void setLayout(LayoutManager m) Để cài đặt Layout Manager cho thành phần
public void setVisible(boolean b) Để cài đặt tính nhìn thấy được (visible) của thành phần. Theo mặc định là false.

Ứng dụng của Java Swing

Java Swing được dùng để hỗ trợ tạo giao diện đồ hoạ người dùng (với Java).

Bộ công cụ này cung cấp các bộ điều khiển nâng cao như thanh trượt, colorpicker, Tree, TabbedPane và bảng điều khiển,..

Swing có những đặc điểm:

  • Độc lập với thiết bị
  • Có thể tuỳ chỉnh, mở rộng
  • Khá nhẹ
  • Có thể cấu hình

Ngoài ra bạn cũng có thể tùy chỉnh các điều khiển xoay một cách dễ dàng mà không ảnh hưởng đến các thành phần khác.

LOGIN Form with MYSQL Database JDBC | JAVA SWING GUI
LOGIN Form with MYSQL Database JDBC | JAVA SWING GUI

History[edit]

The Internet Foundation Classes (IFC) were a graphics library for Java originally developed by Netscape Communications Corporation and first released on December 16, 1996. On April 2, 1997, Sun Microsystems and Netscape Communications Corporation announced their intention to incorporate IFC with other technologies to form the Java Foundation Classes.[4] 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 Standard Edition since release 1.2.[5] The Swing classes and components are contained in the

javax.swing

package hierarchy.

Development of Swing’s successor, JavaFX, started in 2005, and it was officially introduced two years later at JavaOne 2007.[6] 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 CSS styling, sleek design controls, and the use of FXML and Scene Builder.[7] In 2018, JavaFX was made a part of the OpenJDK under the OpenJFX project to increase the pace of its development.[8]

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,[9] Tim Prinzing, Jonni Kanerva, and Jeannette Hung & Jim Graham (2D Graphics).[10]

Swing Features

  • Light Weight − Swing components are independent of native Operating System’s API as Swing API controls are rendered mostly using pure JAVA code instead of underlying operating system calls.

  • Rich Controls − Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, and table controls.

  • Highly Customizable − Swing controls can be customized in a very easy way as visual apperance is independent of internal representation.

  • Pluggable look-and-feel − SWING based GUI Application look and feel can be changed at run-time, based on available values.

AWT and Swing in Java

AWT and Swing are used to develop window-based applications in Java. Awt is an abstract window toolkit that provides various component classes like Label, Button, TextField, etc., to show window components on the screen. All these classes are part of the Java.awt package.

On the other hand, Swing is the part of JFC (Java Foundation Classes) built on the top of AWT and written entirely in Java. The javax.swing API provides all the component classes like JButton, JTextField, JCheckbox, JMenu, etc.

The components of Swing are platform-independent, i.e., swing doesn’t depend on the operating system to show the components. Also, the Swing’s components are lightweight. The main differences between AWT and Swing are given in the following table.

Context AWT Swing
API Package The AWT Component classes are provided by the java.awt package. The Swing component classes are provided by the javax.swing package.
Operating System The Components used in AWT are mainly dependent on the operating system. The Components used in Swing are not dependent on the operating system. It is completely scripted in Java.
Weightiness The AWT is heavyweight since it uses the resources of the operating system. The Swing is mostly lightweight since it doesn’t need any Operating system object for processing. The Swing Components are built on the top of AWT.
Appearance The Appearance of AWT Components is mainly not configurable. It generally depends on the operating system’s look and feels. The Swing Components are configurable and mainly support pluggable look and feel.
Number of Components The Java AWT provides a smaller number of components in comparison to Swing. Java Swing provides a greater number of components than AWT, such as list, scroll panes, tables, color choosers, etc.
Full-Form Java AWT stands for Abstract Window Toolkit. Java Swing is mainly referred to as Java Foundation Classes (JFC).
Peers Java AWT has 21 peers. There is one peer for each control and one peer for the dialogue. Peers are provided by the operating system in the form of widgets themselves. Java Swing has only one peer in the form of OS’s window object, which provides the drawing surface used to draw the Swing’s widgets (label, button, entry fields, etc.) developed directly by Java Swing Package.
Functionality and Implementation Java AWT many features that are completely developed by the developer. It serves as a thin layer of development on the top of the OS. Swing components provide the higher-level inbuilt functions for the developer that facilitates the coder to write less code.
Memory Java AWT needs a higher amount of memory for the execution. Java Swing needs less memory space as compared to Java AWT.
Speed Java AWT is slower than swing in terms of performance. Java Swing is faster than the AWT.

Java Swing Hierarchy

Java defines the class hierarchy for all the Swing Components, which is shown in the following image.

Java Swing Example

In the following example, we have created a User form by using the swing component classes provided by the javax.swing package. Consider the example.

Output:

Java awt Example

To understand the differences between Awt and Swing, we have created the same example in awt as well. Consider the following example.

Output:

Back to: Java Tutorials For Beginners and Professionals

AOE  || Vũ Địu Cung R Shang || VN vs CHINA ngày 15/2/2024
AOE || Vũ Địu Cung R Shang || VN vs CHINA ngày 15/2/2024

Java


import


java.awt.*;


class


button {


button()


Frame f =


new


Frame();


Button b1 =


new


Button(


"OK"


);


b1.setBounds(


100


50


50


50


);


f.add(b1);


Button b2 =


new


Button(


"SUBMIT"


);


b2.setBounds(


100


101


50


50


);


f.add(b2);


Button b3 =


new


Button(


"CANCEL"


);


b3.setBounds(


100


150


80


50


);


f.add(b3);


f.setSize(


500


500


);


f.setLayout(


null


);


f.setVisible(


true


);


public


static


void


main(String a[]) {


new


button(); }

Output:
Example 3: Program to Add Checkbox in the Frame

Java


import


java.io.*;


import


javax.swing.*;


class


GFG {


public


static


void


main(String[] args)


JFrame frame =


new


JFrame();


JButton button =


new


JButton(


" GFG WebSite Click"


);


button.setBounds(


150


200


220


50


);


frame.add(button);


frame.setSize(


500


600


);


frame.setLayout(


null


);


frame.setVisible(


true


);

Output:
Example 2: Write a program to create three buttons with caption OK, SUBMIT, CANCEL.
#1 Java Swing Tutorial | JFrame in Java Swing
#1 Java Swing Tutorial | JFrame in Java Swing

Cấu trúc phân cấp lớp Java Swing

Phân cấp của API Java swing như liệt kê ở hình dưới đây:

Phân cấp API Java swing

Chú thích: Tất cả các thành phần trong swing được kế thừa từ lớp Jcomponent như JButton, JComboBox, JList, JLabel đều có thể được thêm vào lớp Container.

Container là các window như Frame và Dialog. Các container này chỉ có thể thêm một thành phần vào chính nó.

What is JFC?

JFC stands for Java Foundation Classes. JFC is the set of GUI components that simplify desktop Applications. Many programmers think that JFC and Swing are one and the same thing, but that is not so. JFC contains Swing [A UI component package] and quite a number of other items:

  • Cut and paste: Clipboard support.
  • Accessibility features: Aimed at developing GUIs for users with disabilities.
  • The Desktop Colors Features were first introduced in Java 1.1
  • Java 2D: it has Improved colors, images, and text support.
Java UI Design - Dashboard ( Part 1 )
Java UI Design – Dashboard ( Part 1 )

Components of Swing Class the task’s percentage

Component A Component is the Abstract base class for about the non-menu user-interface controls of Java SWING. Components are representing an object with a graphical representation.
Container A Container is a component that can container Java SWING Components
JComponent A JComponent is a base class for all swing UI Components In order to use a swing component that inherits from JComponent, the component must be in a containment hierarchy whose root is a top-level Java Swing container.
JLabel A JLabel is an object component for placing text in a container.
JButton This class creates a labeled button.
JColorChooser A JColorChooser provides a pane of controls designed to allow the user to manipulate and select a color.
JCheckBox A JCheckBox is a graphical (GUI) component that can be in either an on-(true) or off-(false) state.
JRadioButton The JRadioButton class is a graphical (GUI) component that can be in either an on-(true) or off-(false) state. in the group
JList A JList component represents the user with the scrolling list of text items.
JComboBox A JComboBox component is Presents the User with a show up Menu of choices.
JTextField A JTextField object is a text component that will allow for the editing of a single line of text.
JPasswordField A JPasswordField object it is a text component specialized for password entry.
JTextArea A JTextArea object is a text component that allows for the editing of multiple lines of text.
Imagelcon A ImageIcon control is an implementation of the Icon interface that paints Icons from Images
JScrollbar A JScrollbar control represents a scroll bar component in order to enable users to Select from range values.
JOptionPane JOptionPane provides set of standard dialog boxes that prompt users for a value or Something.
JFileChooser A JFileChooser it Controls represents a dialog window from which the user can select a file.
JProgressBar As the task progresses towards completion, the progress bar displays the tasks percentage on its completion.
JSlider A JSlider this class is letting the user graphically (GUI) select by using a value by sliding a knob within a bounded interval.
JSpinner A JSpinner this class is a single line input where the field that lets the user select by using a number or an object value from an ordered sequence.

Feeling lost in the vast world of Backend Development? It’s time for a change! Join our Java Backend Development – Live Course and embark on an exciting journey to master backend development efficiently and on schedule. What We Offer:

  • Comprehensive Course
  • Expert Guidance for Efficient Learning
  • Hands-on Experience with Real-world Projects
  • Proven Track Record with 100,000+ Successful Geeks

Last Updated :
09 Jan, 2024

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

Swing (Java)

Swing is a GUI widget toolkit for Java.[1] It is part of Oracle’s Java Foundation Classes (JFC) – an API for providing a graphical user interface (GUI) for Java programs.

Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit (AWT). Swing provides a look and feel that emulates the look and feel of several platforms, and also supports a pluggable look and feel that allows applications to have a look and feel unrelated to the underlying platform. It has more powerful and flexible components than AWT. In addition to familiar components such as buttons, check boxes and labels, Swing provides several advanced components such as tabbed panel, scroll panes, trees, tables, and lists.[2]

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 CSS / FXML based framework that it intended to be the successor to Swing, called JavaFX.[3]

Sự khác biệt giữa AWT và Swing

No. Java AWT Java Swing
1) Phụ thuộc nền tảng (Platform Dependent) Độc lập với nền tảng (Platform Independent)
2) Thành phần của AWT nặng Thành phần của Swing khá nhẹ
3) AWT không hỗ trợ pluggable look and feel. Swing hỗ trợ pluggable look and feel.
4) AWT có ít thành phần hơn Swing Swing cung cấp nhiều thành phần và các thành phần cũng mạnh mẽ hơn AWT như: bảng, danh sách, cuộn màn hình, trình chọn màu,..
5) AWT không tuân theo cấu trúc MVC (Model View Controller) Swing theo cấu trúc MVC
Supermarket management System full project(Java Swing)
Supermarket management System full project(Java Swing)

MVC Architecture

Swing API architecture follows loosely based MVC architecture in the following manner.

  • Model represents component’s data.

  • View represents visual representation of the component’s data.

  • Controller takes the input from the user on the view and reflects the changes in Component’s data.

  • Swing component has Model as a seperate element, while the View and Controller part are clubbed in the User Interface elements. Because of which, Swing has a pluggable look-and-feel architecture.

Architecture[edit]

Swing is a platform-independent, “model–view–controller” GUI framework for Java, which follows a single-threaded programming model.[11] Additionally, this framework provides a layer of abstraction between the code structure and graphic presentation of a Swing-based GUI.

Foundations[edit]

Swing is platform-independent because it is completely written in Java. Complete documentation for all Swing classes can be found in the Java API Guide for Version 6 or the Java Platform Standard Edition 8 API Specification for Version 8.

Extensible[edit]

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

LookAndFeel

.

Swing is a component-based framework, whose components are all ultimately derived from the

JComponent

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 JavaBeans specification.

Configurable[edit]

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[edit]

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 AWT container, since (Swing’s)

JComponent

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

JComponent

model.

Loosely coupled and MVC[edit]

The Swing library makes heavy use of the model–view–controller software design pattern,[12] 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 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

JComponent

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 DAO and/or 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 specialization into a meaningful event for the GUI component.

For example, the

JTable

has a model called

TableModel

that describes an interface for how a table would access tabular data. A default implementation of this operates on a two-dimensional 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 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 Mixing AWT and Swing components).

Finally, in terms of visual composition and management, Swing favors 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 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.)

Relationship to AWT[edit]

Since early versions of Java, a portion of the Abstract Window Toolkit (AWT) has provided platform-independent APIs for user interface components. In AWT, each component is rendered and controlled by a native peer component specific to the underlying windowing system.

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.[13]

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 (

JApplet

,

JDialog

,

JFrame

, and

JWindow

) extend an AWT top-level container. Prior to 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.

This section may contain material not related to the topic of the article. (May 2012)

Relationship to SWT[edit]

The Standard Widget Toolkit (SWT) is a competing toolkit originally developed by IBM and now maintained by the Eclipse 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 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.[14] A fairly thorough set of benchmarks in 2005 concluded that neither Swing nor SWT clearly outperformed the other in the general case.[15]

Java GUI Tutorial - Make a GUI in 13 Minutes #99
Java GUI Tutorial – Make a GUI in 13 Minutes #99

Hướng dẫn học lập trình Java Swing từ A đến Z

Dưới đây là một số ví dụ đơn giản để tạo GUI bằng Swing trong Java:

JButton Class – Lớp JButton

Nó được dùng để tạo ra một nút (button) có tên.

Việc sử dụng ActionListener sẽ dẫn đến một số hành động khi nút được nhấn.

Nó kế thừa lớp AbstractButton và độc lập với nền tảng.

Ví dụ:

1

10

11

12

import javax.swing.*;

public class example{

public static void main(String args[]) {

JFrame a = new JFrame(“example”);

JButton b = new JButton(“click me”);

b.setBounds(40,90,85,20);

a.add(b);

a.setSize(300,300);

a.setLayout(null);

a.setVisible(true);

Output:

Một nút button có tên

JTextField Class – Lớp JTextField

Nó kế thừa lớp JTextComponent và dùng để cho phép chỉnh sửa dòng đơn

Ví dụ:

1

10

11

12

import javax.swing.*;

public class example{

public static void main(String args[]) {

JFrame a = new JFrame(“example”);

JTextField b = new JTextField(“edureka”);

b.setBounds(50,100,200,30);

a.add(b);

a.setSize(300,300);

a.setLayout(null);

a.setVisible(true);

Output:

JTextField Class

JScrollBar Class – lớp JScrollBar

Dùng để thêm thanh cuộn (cả ngang và dọc)

Ví dụ:

1

10

11

12

13

14

15

import javax.swing.*;

class example{

example(){

JFrame a = new JFrame(“example”);

JScrollBar b = new JScrollBar();

b.setBounds(90,90,40,90);

a.add(b);

a.setSize(300,300);

a.setLayout(null);

a.setVisible(true);

public static void main(String args[]){

new example();

Output:

JScrollBar Class

JPanel Class – Lớp JPanel

Kế thừa lớp JComponent, cung cấp không gian cho một ứng dụng (có thể đính kèm bất kỳ thành phần nào khác).

1

10

11

12

13

14

15

16

17

18

19

20

import java.awt.*;

import javax.swing.*;

public class Example{

Example(){

JFrame a = new JFrame(“example”);

JPanel p = new JPanel();

p.setBounds(40,70,200,200);

JButton b = new JButton(“click me”);

b.setBounds(60,50,80,40);

p.add(b);

a.add(p);

a.setSize(400,400);

a.setLayout(null);

a.setVisible(true);

public static void main(String args[])

new Example();

Output:

Panel Class

JMenu Class – Lớp JMenu

Kế thừa lớp JMenuItem, là một thành phần menu kéo xuống (hiển thị từ thanh menu).

1

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

import javax.swing.*;

class Example{

JMenu menu;

JMenuItem a1,a2;

Example()

JFrame a = new JFrame(“Example”);

menu = new JMenu(“options”);

JMenuBar m1 = new JMenuBar();

a1 = new JMenuItem(“example”);

a2 = new JMenuItem(“example1”);

menu.add(a1);

menu.add(a2);

m1.add(menu);

a.setJMenuBar(m1);

a.setSize(400,400);

a.setLayout(null);

a.setVisible(true);

public static void main(String args[])

new Example();

Output:

Lớp JMenu

JList Class – Lớp JList

Kế thừa lớp JComponent, đối tượng của lớp Jlist đại diện cho danh sách các mục văn bản.

Next

1

10

11

12

13

14

15

16

17

18

19

20

import javax.swing.*;

public class Example

Example(){

JFrame a = new JFrame(“example”);

DefaultListModel

l = new DefaultListModel< >();

l.addElement(“first item”);

l.addElement(“second item”);

JList

b = new JList< >(l);

b.setBounds(100,100,75,75);

a.add(b);

a.setSize(400,400);

a.setVisible(true);

a.setLayout(null);

public static void main(String args[])

new Example();

Output:

Lớp JList

JLabel Class – Lớp JLabel

Được dùng để đặt văn bản trong vùng chứa, lớp JLabel cũng kế thừa lớp JComponent.

1

10

11

12

13

14

import javax.swing.*;

public class Example{

public static void main(String args[])

JFrame a = new JFrame(“example”);

JLabel b1;

b1 = new JLabel(“edureka”);

b1.setBounds(40,40,90,20);

a.add(b1);

a.setSize(400,400);

a.setLayout(null);

a.setVisible(true);

Output:

Lớp JLabel

JComboBox Class- Lớp JComboBox

Kế thừa lớp JComponent, dùng để hiển thị menu lựa chọn bật lên.

1

10

11

12

13

14

15

16

17

18

import javax.swing.*;

public class Example{

JFrame a;

Example(){

a = new JFrame(“example”);

string courses[] = { “core java”,”advance java”, “java servlet”};

JComboBox c = new JComboBox(courses);

c.setBounds(40,40,90,20);

a.add(c);

a.setSize(400,400);

a.setLayout(null);

a.setVisible(true);

public static void main(String args[])

new Example();

Output:

Lớp JComboBox

Layout Manager – Trình quản lý bố cục

Để sắp xếp các thành phần bên trong vùng chứa, chúng ta sử dụng Layout Manager.

Có một số bố cục như sau:

  1. Border layout – Bố cục đường viền
  2. Flow layout – Bố cục luồng
  3. GridBag layout – Bố cục dạng khung
Border Layout

Trình quản lý bố cục mặc định tất cả JFrame là Border Layout.

Nó đặt các thành phần ở tối đa 5 vị trí: trên, dưới, trái, phải và trung tâm.

Trình quản lý bố cục mặc định

Flow Layout

Bố cục này đặt các thành phần lần lượt vào một hàng.

Bố cục mặc định JPanel.

Đây là bố cục mặc định cho mọi JPanel.

GridBag Layout

GridBag Layout đặt các thành phần trong một lưới, nó cho phép các thành phần này trải dài hơn 1 ô.

GridBag Layout

Ví dụ: Dưới đây là một khung chat ở dạng Flow Layout

1

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

import javax.swing.*;

import java.awt.*;

class Example {

public static void main(String args[]) {

JFrame frame = new JFrame(“Chat Frame”);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(400, 400);

JMenuBar ob = new JMenuBar();

JMenu ob1 = new JMenu(“FILE”);

JMenu ob2 = new JMenu(“Help”);

ob.add(ob1);

ob.add(ob2);

JMenuItem m11 = new JMenuItem(“Open”);

JMenuItem m22 = new JMenuItem(“Save as”);

ob1.add(m11);

ob1.add(m22);

JPanel panel = new JPanel(); // the panel is not visible in output

JLabel label = new JLabel(“Enter Text”);

JTextField tf = new JTextField(10); // accepts upto 10 characters

JButton send = new JButton(“Send”);

JButton reset = new JButton(“Reset”);

panel.add(label); // Components Added using Flow Layout

panel.add(label); // Components Added using Flow Layout

panel.add(tf);

panel.add(send);

panel.add(reset);

JTextArea ta = new JTextArea();

frame.getContentPane().add(BorderLayout.SOUTH, panel);

frame.getContentPane().add(BorderLayout.NORTH, tf);

frame.getContentPane().add(BorderLayout.CENTER, ta);

frame.setVisible(true);

Output:

Khung chat ở dạng Flow Layout

Java Swing Tutorial

Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing

There are many differences between java awt and swing that are given below.

What is JFC

The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop applications.

Hierarchy of Java Swing classes

The hierarchy of java swing API is given below.

Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are given below.

Java Swing Examples

There are two ways to create a frame:

We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example

Let’s see a simple swing example where we are creating one button and adding it on the JFrame object inside the main() method.

File: FirstSwingExample.java

Example of Swing by Association inside constructor

We can also write all the codes of creating JFrame, JButton and method call inside the java constructor.

File: Simple.java

The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets the position of the button.

Simple example of Swing by inheritance

We can also inherit the JFrame class, so there is no need to create the instance of JFrame class explicitly.

File: Simple2.java

Next TopicJava JButton Class

Introduction to Java Swing

Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window Toolkit [AWT]. Java Swing offers much-improved functionality over AWT, new components, expanded components features, and excellent event handling with drag-and-drop support.

Introduction of Java Swing

Swing has about four times the number of User Interface [UI] components as AWT and is part of the standard Java distribution. By today’s application GUI requirements, AWT is a limited implementation, not quite capable of providing the components required for developing complex GUIs required in modern commercial applications. The AWT component set has quite a few bugs and does take up a lot of system resources when compared to equivalent Swing resources. Netscape introduced its Internet Foundation Classes [IFC] library for use with Java. Its Classes became very popular with programmers creating GUI’s for commercial applications.

  • Swing is a Set of API (API- Set of Classes and Interfaces)
  • Swing is Provided to Design Graphical User Interfaces
  • Swing is an Extension library to the AWT (Abstract Window Toolkit) 5:00 – 5:30 pm
  • Includes New and improved Components that have been enhancing the looks and Functionality of GUIs’
  • Swing can be used to build (Develop) The Standalone swing GUI Apps as Servlets and Applets
  • It Employs model/view design architecture.
  • Swing is more portable and more flexible than AWT, the Swing is built on top of the AWT.
  • Swing is Entirely written in Java.
  • Java Swing Components are Platform-independent, and The Swing Components are lightweight.
  • Swing Supports a Pluggable look and feel and Swing provides more powerful components.
  • such as tables, lists, Scrollpanes, Colourchooser, tabbed pane, etc.
  • Further Swing Follows MVC.
Java Calculator App Development Tutorial 1 |  Swing | GUI
Java Calculator App Development Tutorial 1 | Swing | GUI

The MVC Connection

  • In general, a visual component is a composite of three distinct aspects:

    1. The way that the component looks when rendered on the screen.
    2. The way such that the component reacts to the user.
    3. The state information associated with the component.
  • Over the years, one component architecture has proven itself to be exceptionally effective: – Model-View-Controller or MVC for short.
  • In MVC terminology, the model corresponds to the state information associated with the Component.
  • The view determines how the component is displayed on the screen, including any aspects of the view that are affected by the current state of the model.
  • The controller determines how the component reacts to the user.

The simplest Swing components have capabilities far beyond AWT components as follows:

  • Swing buttons and labels can be displaying images instead of or in addition to text.
  • The borders around most Swing components can be changed easily. For example, it is easy to put a 1-pixel border around the outside of a Swing label.
  • Swing components do not have to be rectangular. Buttons, for example, can be round.
  • Now The Latest Assertive technologies such as screen readers can easily get information from Swing components. Example: A screen reader tool can easily capture the text that is displayed on a Swing button or label.

FAQs

Here are some frequently asked questions related to Java Swing:

Q1: How is Java Swing is different from AWT?Ans: Unlike AWT, which is based on native components and has limited customization options, Swing is entirely written in Java and offers a higher degree of customization and control over the appearance and behavior of components.

Q2: What are the main components of Java Swing?Ans: Java Swing provides a wide range of components for creating GUI applications, including buttons, labels, text fields, checkboxes, radio buttons, menus, and many others.

Q3: How do I create a basic GUI application using Java Swing?Ans: To create a basic GUI application using Java Swing, you will typically create a JFrame object to serve as the main window and add various components to it using layout managers. You can then set the properties of the components and add event handlers to respond to user interactions.

Q4: How do layout managers in Java Swing work?Ans: Each layout manager in Java Swing works in a slightly different way, but they all allow you to specify the position and size of components relative to each other and to the container. For example, the BorderLayout manager arranges components in five regions (north, south, east, west, and center) and allows you to specify the preferred size of each component using the BorderLayout constants.

Tic Tac Toe | Java | GUI | Eclipse | Completely Responsive Layout
Tic Tac Toe | Java | GUI | Eclipse | Completely Responsive Layout

Swings in Java with Examples

In this article, I am going to discuss Swings in Java with Examples. Please read our previous article, where we discussed Event Handling in Java. At the end of this article, you will understand the following pointers in detail.

  1. What are Swings in Java
  2. Why do we need Swings in Java?
  3. Difference Between AWT package and SWING package
  4. Common Methods of Swing Component
  5. Understanding WindowPane & JFrame
  6. Multiple Programs to understand Swings in Java
Swings in Java:

Swings are used to develop a better efficient GUI. The Swing component is part of JFC (Java Foundation Classes) which are developed in Java. The Swing components are called lightweight components which will improve the performance of the application because the amount of resources required is very minimum. There are no peer classes for the swing components to interact with the operating system. The swing component supports a pluggable look and feels using which the component can be presented in various fat forms having the same behavior.

Note: Swing is not a replacement for AWT but is an extension of AWT.

Swing is an advanced package compared to the AWT package and also Swing doesn’t depend on peer classes. The swing package follows the MVC architecture model. Here, MVC stands for Model View Controller Architecture.

MVC architecture is for separating presentation logic from controlling and business logic. Here, business logic is nothing but a model. For example, we can take a button as an example if we click on the button the state of the button is changed, i.e. on the button, we will see dotted lines. Internally controller class is responsible to communicates with the model to change the state of the button component and it communicates with a view to updating that state. Here the view is nothing but UI (User Interface).

Difference Between AWT package and SWING package
AWT package
  1. AWT package-based classes must depend on peer classes for creating UI components.
  2. It makes Java platform-dependent.
  3. It doesn’t follow the MVC architecture pattern.
SWING package
  1. It doesn’t depend on peer classes.
  2. It makes Java platform-independent.
  3. It follows the MVC architecture style.
Features of Swing
  1. It provides a lightweight architecture.
  2. It provides support for the look and feels management.
  3. It allows us to add images to the background of UI Components.
  4. It provides advanced classes that support fro latest UI Components creation like Dialog boxes, etc.
Common Methods of Swing Component
  1. public void add(Component c): It is used to add a component to another component.
  2. public void setSize(int width, int height): It is used to set the size of the component.
  3. public void setLayout(LayoutManager m): It is used to set the layout manager for the component.
  4. public void setVisible(boolean b): It is used to set the visibility of the component. By default, the value is set to be false.
Example to understand Swings in Java:

import javax.swing.*; import java.awt.event.*; public class SwingDemo1 { public static void main (String[]args) { JFrame jf = new JFrame (); jf.setSize (100, 100); JButton jb = new JButton (“click”); jb.setMnemonic (‘C’); MyListener ob = new MyListener (); jb.addActionListener (ob); jf.add (jb); jf.setVisible (true); } } class MyListener implements ActionListener { public void actionPerformed (ActionEvent ae) { System.out.println (“Button Clicked”); } }

Output:

In the above application, we defined a keyboard shortcut key for the button component using setMnemonics().

Note: The keyboard shortcut key is an advanced feature provided by Java Swing.

WindowPane

The empty area that is available in a container is which is used for displaying the components is called WindowPane. The windowpane is internally divided into multiple panes.

  1. GlassPane: This is the first pane closer to the window(screen) and it is used for displaying foreground components.
  2. ContentPane: This pane is available behind GlassPane and is used for displaying individual components.
  3. LayeredPane: This pane is available behind the content pane and is used to display a group of components.
  4. RootPane: This pane is available behind the Layered pane and it is used to display background components.

Note: All the four panes are placed on top of one another and they are transpired All the swing components are available in javax.swing package.

JFrame

The javax.swing.JFrame class may be a sort of container which inherits the java.awt.Frame class. JFrame works just like the main window where components like labels, buttons, and text fields are added to make a GUI. Unlike Frame, JFrame has the choice to cover or close the window with the assistance of the setDefaultCloseOperation(int) method.

Syntax : JFrame jf = new JFrame();

JFrame Constructors
  1. JFrame(): It is used to construct a new Frame that is visible initially.
  2. JFrame(GraphicsConfiguration gc): It is used to create a Frame in the specified GraphicsConfiguration of a screen device and a blank title.
  3. JFrame(String title): It is used to create a new, initially invisible Frame with the specified title.
  4. JFrame(String title, GraohicsConfiguration gc): It is used to create a JFrame with the specified title and the specified GraphicsConfiguration of a screen device.
Example to understand JFrame in Java:

import javax.swing.*; public class JFrameDemo { public static void main (String[]args) { JFrame jf = new JFrame (); jf.setVisible (true); jf.setSize (400, 500); jf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); } }

Output:

In the next article, I am going to discuss Swing Controls in Java with examples. Here, in this article, I try to explain Swings in Java with Examples and I hope you enjoy this Swing in Java with Examples article.

About the Author: Pranaya Rout

Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.

See also[edit]

  • 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 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.[18]
JFrame | Java Swing Tutorial for Beginners
JFrame | Java Swing Tutorial for Beginners

Difference between Java Swing and Java AWT

There are certain points from which Java Swing is different than Java AWT as mentioned below:

Java AWT is an API to develop GUI applications in Java.

Swing is a part of Java Foundation Classes and is used to create various applications.

Components of AWT are heavy weighted.

The components of Java Swing are lightweight.

Components are platform dependent.

Components are platform independent.

Execution Time is more than Swing.

Execution Time is less than AWT.

AWT components require java.awt package.

Swing components requires javax.swing package.

To know more about the topic, refer to Java Swing vs Java AWT.

Java Swing là gì?

Java Swing là cách gọi rút gọn khi người ta nhắc đến Swing của Java Foundation (JFC). Nó là bộ công cụ GUI mà Sun Microsystems phát triển để xây dựng các ứng dụng tối ưu dùng cho window (bao gồm các thành phần như nút, thanh cuộn,…).

Swing được xây dựng trên AWT API và hoàn toàn được viết bằng Java. Tuy nhiên, nó lại khác với AWT ở chỗ bộ công cụ này thuộc loại nền tảng độc lập, bao gồm các thành phần nhẹ và phức tạp hơn AWT.

Các gói javax.swing bao gồm các lớp cho Java Swing API như JMenu, JButton, JTextField, JRadioButton, JColorChooser,…

Việc xây dựng ứng dụng sẽ trở nên dễ dàng hơn với Java Swing vì chúng ta có các bộ công cụ GUI giúp đỡ công việc.

Swing được chính thức phát hành vào tháng 3/1998. Nó đi kèm với thư viện Swing 1.0 với hơn 250 lớp, 80 giao tiếp.

Hiện nay con số này đã được tăng lên, ở phiên bản Swing 1.4 có 451 lớp và 85 giao tiếp.

Các bản phát hành Java 2 (SDK 1.2 và các phiên bản mới hơn) đều bao gồm Swing trong runtime environment.

Java GUI: Full Course ☕ (FREE)
Java GUI: Full Course ☕ (FREE)

Features Of Swing Class

  • Pluggable look and feel.
  • Uses MVC architecture.
  • Lightweight Components
  • Platform Independent
  • Advanced features such as JTable, JTabbedPane, JScollPane, etc.
  • Java is a platform-independent language and runs on any client machine, the GUI look and feel, owned and delivered by a platform-specific O/S, simply does not affect an application’s GUI constructed using Swing components.
  • Lightweight Components: Starting with the JDK 1.1, its AWT-supported lightweight component development. For a component to qualify as lightweight, it must not depend on any non-Java [O/s based) system classes. Swing components have their own view supported by Java’s look and feel classes.
  • Pluggable Look and Feel: This feature enable the user to switch the look and feel of Swing components without restarting an application. The Swing library supports components’ look and feels that remain the same across all platforms wherever the program runs. The Swing library provides an API that gives real flexibility in determining the look and feel of the GUI of an application
  • Highly customizable – Swing controls can be customized in a very easy way as visual appearance is independent of internal representation.
  • Rich controls– Swing provides a rich set of advanced controls like Tree TabbedPane, slider, colorpicker, and table controls.

Keywords searched by users: swing in advanced java

Categories: Tìm thấy 97 Swing In Advanced Java

Introduction To Java Swing - Geeksforgeeks
Introduction To Java Swing – Geeksforgeeks
Swing Components In Java | Top 13 Useful Components Of Swing In Java
Swing Components In Java | Top 13 Useful Components Of Swing In Java
Awt And Swing In Java - Javatpoint
Awt And Swing In Java – Javatpoint
Advanced Java: Swing (Gui) Programming Part 1 -- A Basic Swing Application  - Youtube
Advanced Java: Swing (Gui) Programming Part 1 — A Basic Swing Application – Youtube
Java Swing: Definition, Classes & Methods - Video & Lesson Transcript |  Study.Com
Java Swing: Definition, Classes & Methods – Video & Lesson Transcript | Study.Com
Swing (Java) - Wikipedia
Swing (Java) – Wikipedia
Java Swing Tutorial - Javatpoint
Java Swing Tutorial – Javatpoint
Gui Programming - Java Programming Tutorial
Gui Programming – Java Programming Tutorial
Advanced Java: Swing (Gui) Programming Part 3 -- Panels And Forms - Youtube
Advanced Java: Swing (Gui) Programming Part 3 — Panels And Forms – Youtube
Java Swing: Definition, Classes & Methods - Video & Lesson Transcript |  Study.Com
Java Swing: Definition, Classes & Methods – Video & Lesson Transcript | Study.Com
54 Advanced Java Tutorial | Jdbc | Swing - Awt + Jdbc | Computer Science  Project | Adv Java - Youtube
54 Advanced Java Tutorial | Jdbc | Swing – Awt + Jdbc | Computer Science Project | Adv Java – Youtube
Advanced Java: Swing (Gui) Programming Part 2 -- Adding Components - Youtube
Advanced Java: Swing (Gui) Programming Part 2 — Adding Components – Youtube
Gui Programming Part 2 - Java Programming Tutorial
Gui Programming Part 2 – Java Programming Tutorial
Swing (Java) - Wikipedia
Swing (Java) – Wikipedia
Java Swing With Examples- Scaler Topics
Java Swing With Examples- Scaler Topics
Advanced Swing Components | Java Tutorial - Youtube
Advanced Swing Components | Java Tutorial – Youtube

See more here: kientrucannam.vn

See more: https://kientrucannam.vn/vn/

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *