Chuyển tới nội dung
Home » Java Swing Simple Program | Ứng Dụng Của Java Swing

Java Swing Simple Program | Ứng Dụng Của Java Swing

Swing application to add two numbers using Java using IntellIj | Java GUI

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.

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ó.

Swing application to add two numbers using Java using IntellIj | Java GUI
Swing application to add two numbers using Java using IntellIj | Java GUI

Display the Current Date and Time

The “Date” class is used to read the date and time values. Create a Java file with the following code that displays the current date and time in the dialog box:

import java.text.*;

import java.util.*;

class SwingExample8 {

public static void main(String[] args) {

//Declare frame object

JFrame win = new JFrame();

//Set the title

win.setTitle(“Java Swing Example-8”);

//Set the window size

win.setSize(350, 150);

//Disable the resize option

win.setResizable(false);

//Set window position

win.setLocationRelativeTo(null);

//Define a format object

SimpleDateFormat formatDate = new SimpleDateFormat(“dd MMMM yyyy HH:mm:ss z”);

//Declare the date object

Date dt = new Date();

//Create a label object, set the position, and add to the frame

JLabel lbl = new JLabel(formatDate.format(dt), JLabel.CENTER);

lbl.setBounds(80,20,100,20);

win.add(lbl);

//Make the window visible

win.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file:

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.
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:

Java GridBagLayout

It is the more sophisticated of all layouts. It aligns components by placing them within a grid of cells, allowing components to span more than one cell.

Step 8) Create chat frameHow about creating a chat frame like below?

Try to code yourself before looking at the program below.

//Usually you will require both swing and awt packages // even if you are working with just swings. import javax.swing.*; import java.awt.*; class gui { public static void main(String args[]) { //Creating the Frame JFrame frame = new JFrame(“Chat Frame”); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 400); //Creating the MenuBar and adding components JMenuBar mb = new JMenuBar(); JMenu m1 = new JMenu(“FILE”); JMenu m2 = new JMenu(“Help”); mb.add(m1); mb.add(m2); JMenuItem m11 = new JMenuItem(“Open”); JMenuItem m22 = new JMenuItem(“Save as”); m1.add(m11); m1.add(m22); //Creating the panel at bottom and adding components 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(tf); panel.add(send); panel.add(reset); // Text Area at the Center JTextArea ta = new JTextArea(); //Adding Components to the frame. frame.getContentPane().add(BorderLayout.SOUTH, panel); frame.getContentPane().add(BorderLayout.NORTH, mb); frame.getContentPane().add(BorderLayout.CENTER, ta); frame.setVisible(true); } }

Java is a versatile programming language. Many types of applications can be developed easily using this language. The Java Swing toolkit is used to develop desktop applications. Java Swing contains all GUI components to implement the Graphical User Interface (GUI) for the desktop application. The Abstract Window Toolkit (AWT) was used in the earlier version of Java to develop GUI for the desktop application. But AWT contains only the basic GUI components such as labels, textboxes, buttons, etc. for designing the interface of desktop applications. Many advanced-level GUI components such as tab pane, menus, table, scroll bar, etc. have been added to the Java Swing toolkit. The “java.swing” package contains all the components and classes of the Java Swing toolkit. The most basic uses of the Java swing controls to develop the desktop applications are shown in this tutorial using 15 Java swing examples.

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

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.

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.

Display the Tabular Data

The JTable class is used to display the tabular output in Java. Create a Java file with the following code to display the data of a two-dimensional array in tabular form. The JTableHeader class is used here to format the table header.

import java.awt.Color;

import java.awt.Font;

import javax.swing.*;

import javax.swing.table.JTableHeader;

class SwingExample12 {

public static void main(String[] args) {

//Declare the JFrame object

JFrame frame = new JFrame(“Java Swing Example-12”);

//Declare an array of objects

Object[][] Sales = {

{“January”, “Dhanmondi”, 120, 20000},

{“February”, “Mirpur”, 340, 50000},

{“March”, “Mogbazar”, 502, 60793},

{“April”, “Jatrabari”, 444, 55000},

{“May”, “Malibagh”, 390, 48000}

};

//Declare an array to store the table heading

String[] colHeader = {“Month”, “Branch”, “Sales items”, “Sales amount” };

//Declare the JTable object

JTable table = new JTable(Sales, colHeader);

//Set the font color of the table

table.setForeground(Color.GREEN);

//Set the table viewpoint height

table.setFillsViewportHeight(true);

//Declare JTableHeading object

JTableHeader tableHeader = table.getTableHeader();

//Set the background color of the table heading

tableHeader.setBackground(Color.CYAN);

//Set the font color of the table heading

tableHeader.setForeground(Color.blue);

//Declare the label to display table caption

JLabel tblCaption = new JLabel(“Sales details Information”);

//Set font setting for the table caption

tblCaption.setFont(new Font(“Times New Roman”,Font.TRUETYPE_FONT,25));

tblCaption.setForeground(Color.darkGray);

//Declare the JScrollPane object

JScrollPane scrollPane = new JScrollPane(table);

//Set the layout and add the table caption and scroll into the frame content

frame.getContentPane().setLayout(new BorderLayout());

frame.getContentPane().add(tblCaption,BorderLayout.PAGE_START);

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

//Set the width and height of the frame

frame.setSize(500, 175);

//Disable the resize option

frame.setResizable(false);

//Set window position

frame.setLocationRelativeTo(null);

//Make the frame visible

frame.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file:

JAVA - How To Design Login And Register Form In Java Netbeans
JAVA – How To Design Login And Register Form In Java Netbeans

Working with Image

The ImageIcon class is used to add the image in different Java Swing Controls. Create a Java file with the following code that adds the image in the label and display the label with the image in the output.

import javax.swing.*;

class SwingExample13 {

public static void main(String[] args) {

//Declare a Frame object

JFrame frame = new JFrame();

//Declare a label object

JLabel lbl = new JLabel();

//Set the image for the label using ImageIcon

lbl.setIcon(new ImageIcon(“/home/fahmida/eclipse-workspace/JavaSwingExamples/src/images/flower.jpeg”));

//Declare a dimension object

Dimension size = lbl.getPreferredSize();

//Set the position of the label

lbl.setBounds(50, 30, size.width, size.height);

//Add label to the frame

frame.add(lbl);

//Set the frame title

frame.setTitle(“Java Swing Example-13”);

//Disable the default layout

frame.setLayout(null);

//Set the frame size

frame.setSize(400, 300);

//Disable the resize option

frame.setResizable(false);

//Set frame position

frame.setLocationRelativeTo(null);

//Make the frame visible

frame.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file. The “follower.jpeg” image file is added to the label:

Display a Simple Window

The JFrame is used to create the GUI-based applications in Java. It is used to display the output in a dialog box. Create a Java file with the following code that displays a dialog with the title, “Java Swing Example-1”, at the center of the screen.

class SwingExample1 {

public static void main(String[] args) {

//Declare JFrame object

JFrame frame = new JFrame();

//Set the title

frame.setTitle(“Java Swing Example-1”);

//Set the frame size

frame.setSize(350, 150);

//Disable the resize option

frame.setResizable(false);

//Set frame position to the center of the screen

frame.setLocationRelativeTo(null);

//Make the frame visible

frame.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file:

Senior Programmers vs Junior Developers #shorts
Senior Programmers vs Junior Developers #shorts

How to Make a GUI in Java with Example

Now in this Java GUI Tutorial, let’s understand how to create a GUI in Java with Swings in Java examples.

Step 1) Copy code into an editorIn first step Copy the following code into an editor.

import javax.swing.*; class gui{ public static void main(String args[]){ JFrame frame = new JFrame(“My First GUI”); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); JButton button = new JButton(“Press”); frame.getContentPane().add(button); // Adds Button to content pane of frame frame.setVisible(true); } }

Step 2) Run the codeNext step, Save, Compile, and Run the code

Step 3) Copy following code into an editorNow let’s Add a Button to our frame. Copy following code into an editor from given Java UI Example

import javax.swing.*; class gui{ public static void main(String args[]){ JFrame frame = new JFrame(“My First GUI”); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); JButton button1 = new JButton(“Press”); frame.getContentPane().add(button1); frame.setVisible(true); } }

Step 4) Execute the code

Next, Execute the code. You will get a big button.

Step 5) Add two buttonsHow about adding two buttons? Copy the following code into an editor.

import javax.swing.*; class gui{ public static void main(String args[]){ JFrame frame = new JFrame(“My First GUI”); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); JButton button1 = new JButton(“Button 1”); JButton button2 = new JButton(“Button 2”); frame.getContentPane().add(button1); frame.getContentPane().add(button2); frame.setVisible(true); } }

Step 6) Save & Run the programNext, Save, Compile, and Run the program.

Step 7) Check outputUnexpected output =? Buttons are getting overlapped.

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é!

Create your First Java Frame using Visual Studio Code | Create Java GUI Forms using VS Code
Create your First Java Frame using Visual Studio Code | Create Java GUI Forms using VS Code

Develop a Simple Login System

Create a Java file with the following code that displays a login form to take the username and password from the user and check whether the user credentials are correct or incorrect. If the “admin” value is taken as the username and the “password” value is taken as the password, the “Authenticated” message is printed. Otherwise, the “Not Authenticated” message is printed. The “Login” button is used to take the input values and the “Cancel” button is used to terminate the program.

import javax.swing.*;

class SwingExample15 {

public static void main(String[] args) {

//Declare frame object

JFrame frame = new JFrame();

//Set the title

frame.setTitle(“Java Swing Example-15”);

//Set the window size

frame.setSize(370, 200);

/*Create a label object, set the position, and add to the frame*/

JLabel lbl1 = new JLabel(“Username:”, JLabel.LEFT);

lbl1.setBounds(50,20,100,20);

frame.add(lbl1);

/*Create text object, set the position, and add to the frame*/

JTextField username = new JTextField();

username.setBounds(150,20,150,20);

frame.add(username);

//Create label object, set the position and add to the frame

JLabel lbl2 = new JLabel(“Password:”, JLabel.LEFT);

lbl2.setBounds(50,60,100,20);

frame.add(lbl2);

/*Create password text object, set the position and add to the frame*/

JPasswordField password = new JPasswordField();

password.setBounds(150,60,150,20);

frame.add(password);

/*Create a button, set the position, and add to the frame */

JButton btn1 = new JButton(“Login”);

btn1.setBounds(120, 100, 90, 30);

frame.add(btn1);

/*Create a button, set the position, and, add to the frame*/

JButton btn2 = new JButton(“Cancel”);

btn2.setBounds(215, 100, 100, 30);

frame.add(btn2);

//Set window position

frame.setLocationRelativeTo(null);

//Disable the default layout of the frame

frame.setLayout(null);

//Make the window visible

frame.setVisible(true);

//Handle the login information

btn1.addActionListener((ActionEvent e) -> {

String un = username.getText();

String ps = new String(password.getPassword());

if(un.equals(“admin”) && ps.equals(“secret”))

JOptionPane.showMessageDialog(null, “Authenticated.”);

else

JOptionPane.showMessageDialog(null, “Not Authenticated.”);

});

//Terminate from the program

btn2.addActionListener((ActionEvent e) -> {

System.exit(0);

});

Output:

The following dialog box will appear after executing the Java class file:

If the “Login” button is pressed by keeping the username and password fields empty or by taking invalid values in these fields, the following output will appear:

If the “Login” button is pressed by taking the valid values in the username and password fields, the following output will appear:

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.
Learn Java in 14 Minutes (seriously)
Learn Java in 14 Minutes (seriously)

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

Simple Form Design with Label and Button

The JLabel class is used to create a label and the JButton class is used to create a button in Java. Create a Java file with the following code to display a dialog box with a label and a button. The title of the dialog box is “Java Swing Example-2”. The value of the label is “Simple Java Swing application” with a blue font color. The caption of the button is “Close”.

import javax.swing.*;

class SwingExample2 {

public static void main(String[] args) {

//Declare frame object

JFrame win = new JFrame();

//Set the title

win.setTitle(“Java Swing Example-2”);

//Set the window size

win.setSize(400, 200);

//Create label object

JLabel lbl = new JLabel(“Simple Java Swing application”);

//Set label font color

lbl.setForeground(Color.blue);

//Set the label position

lbl.setBounds(100,20,250,100);

//Add label to frame

win.add(lbl);

//Create a button

JButton btn = new JButton(“Close”);

//Set the button position

btn.setBounds(150, 100, 80, 30);

//Add button to frame

win.add(btn);

//Set window position

win.setLocationRelativeTo(null);

//Disable default layout of the frame

win.setLayout(null);

//Make the window visible

win.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file:

Supermarket management System full project(Java Swing)
Supermarket management System full project(Java Swing)

Conclusion

Any desktop application can be developed easily using both Java AWT and Java Swing toolkits. The most commonly used Swing controls to develop the desktop applications are used in 15 examples of this tutorial. This tutorial will help the new Java programmers to learn the method of developing the desktop applications using the Java Swing controls from the basic.

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don’t take advantage of improvements introduced in later releases and might use technology no longer available.See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

Also known as The Swing Tutorial

This trail tells you how to create graphical user interfaces (GUIs) for applications and applets, using the Swing components. If you would like to incorporate JavaFX into your Swing application, please see Integrating JavaFX into Swing Applications.

Getting Started with Swing is a quick start lesson. First it gives you a bit of background about Swing. Then it tells you how to compile and run programs that use Swing components.

Learning Swing with the NetBeans IDE is the fastest and easiest way to begin working with Swing. This lesson explores the NetBeans IDE’s GUI builder, a powerful feature that lets you visually construct your Graphical User Interfaces.

Using Swing Components tells you how to use each of the Swing components buttons, tables, text components, and all the rest. It also tells you how to use borders and icons.

Concurrency in Swing discusses concurrency as it applies to Swing programming. Information on the event dispatch thread and the SwingWorker class are included.

Using Other Swing Features tells you how to use actions, timers, and the system tray; how to integrate with the desktop class, how to support assistive technologies, how to print tables and text, how to create a splash screen, and how to use modality in dialogs.

Laying Out Components Within a Container tells you how to choose a layout manager, how to use each of the layout manager classes the Java platform provides, how to use absolute positioning instead of a layout manager, and how to create your own layout manager.

Modifying the Look and Feel tells you how to specify the look and feel of Swing components.

Drag and Drop and Data Transfer tells you what you need to know to implement data transfer in your application.

Writing Event Listeners tells you how to handle events in your programs.

Performing Custom Painting gives you information on painting your own Swing components. It discusses painting issues specific to Swing components, provides an overview of painting concepts, and has examples of custom components that paint themselves.

Although this is the main trail for learning about GUIs, it isn’t the only trail with UI-related information.

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
LOGIN Form with MYSQL Database JDBC | JAVA SWING GUI
LOGIN Form with MYSQL Database JDBC | JAVA SWING GUI

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.

Prerequisites:

You have to complete the following task before practicing the examples of this tutorial.

A. Install JDK.Download the latest version of JDK from the following URL address:

https://www.oracle.com/in/java/technologies/downloads/B. Download and install a popular Java editor.Different types of editors exist to write and execute the Java code such as Eclipse, Netbeans, etc. The Eclipse editor is used here. You can check this tutorial to install the Eclipse editor.

JTable in JAVA Swing | ADD Data into JTable
JTable in JAVA Swing | ADD Data into JTable

Form Validation

The form validation is a very important part of the desktop application. Create a Java file with the following code to show the simple form validation task in Java. Here, the form has two fields. The first field takes a string value and the second field takes a numeric value. If the valid data are provided in both fields, a message box with input values is printed in the output.

import javax.swing.*;

class SwingExample5 {

public static void main(String[] args) {

//Declare frame object

JFrame win = new JFrame();

//Set the title

win.setTitle(“Java Swing Example-5”);

//Set the window size

win.setSize(500, 200);

/*Create a label object, set the position, and add to the frame*/

JLabel lbl1 = new JLabel(“Book Name:”, JLabel.LEFT);

lbl1.setBounds(80,20,100,20);

win.add(lbl1);

/*Create text object, set the position, and add to the frame*/

JTextField bname = new JTextField();

bname.setBounds(200,20,200,20);

win.add(bname);

/*Create a label object, set the position, and add to the frame */

JLabel lbl2 = new JLabel(“Book Price:”, JLabel.LEFT);

lbl2.setBounds(80,50,100,20);

win.add(lbl2);

/*Create text object, set the position, and add to the frame*/

JTextField bprice = new JTextField();

bprice.setText(“0.00”);

bprice.setBounds(200,50,50,20);

win.add(bprice);

/*Create a button, set the position, and add to the frame */

JButton btn = new JButton(“Submit”);

btn.setBounds(200, 100, 100, 30);

win.add(btn);

//Set window position

win.setLocationRelativeTo(null);

//Disable the default layout of the frame

win.setLayout(null);

//Make the window visible

win.setVisible(true);

//Check whether the input values are valid or invalid

btn.addActionListener((ActionEvent e) -> {

int valid =1;

String title = bname.getText();

float cost = 0;

if(title.equals(“”))

JOptionPane.showMessageDialog(null, “Book name can’t be empty”);

valid = 0;

try {

cost = Float.parseFloat(bprice.getText());

catch (NumberFormatException eg) {

JOptionPane.showMessageDialog(null, “Price must be a number.”);

valid=0;

if(valid == 1)

String values = “Book Name: ” + title + “\nBook Price: $” + cost;

JOptionPane.showMessageDialog(null, values);

});

Output:

The following dialog box will appear after executing the Java class file:

If the user provides the valid data for both fields, the following similar output will appear:

Create a Popup Menu

The JPopupMenu class is used to create the popup menu in Java. Create a Java file with the following code that displays a popup menu of three items. The menu items are “New file”, “Open file”, and “Save file”. The action listener method is added here to display a message based on the selected menu item.

import java.awt.event.*;

class SwingExample10 {

public static void main(String[] args) {

//Declare JFrame object

JFrame frame = new JFrame();

//Set the title

frame.setTitle(“Java Popup Menu Example”);

//Set the window size

frame.setSize(350, 250);

//Disable the resize option

frame.setResizable(false);

//Define a JPopupMenu object

JPopupMenu popup = new JPopupMenu();

//Define the first menu item

JMenuItem menuItem = new JMenuItem(“New File”);

//Add listener code for the first menu item

menuItem.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(frame, “New file is clicked!”);

});

//Add the first menu item to the popup menu

popup.add(menuItem);

//Define the second menu item

menuItem = new JMenuItem(“Open File”);

//Add listener code for the second menu item

menuItem.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(frame, “Open File is clicked!”);

});

//Add the second menu item to the popup menu

popup.add(menuItem);

//Define the third menu item

menuItem = new JMenuItem(“Save File”);

//Add listener code for the third menu item

menuItem.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(frame, “Save File is clicked!”);

});

//Add the third menu item to the popup menu

popup.add(menuItem);

//Add mouse listener for the JFrame

frame.addMouseListener(new MouseAdapter() {

@Override

public void mousePressed(MouseEvent e) {

showPopup(e);

@Override

public void mouseReleased(MouseEvent e) {

showPopup(e);

private void showPopup(MouseEvent e) {

if (e.isPopupTrigger()) {

popup.show(e.getComponent(), e.getX(), e.getY());

});

//Set window position

frame.setLocationRelativeTo(null);

//Make the window visible

frame.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file and pressing the right button of the mouse:

The following output will appear if the user selects the “New File” menu item from the popup menu:

Java KeyListener 🚀
Java KeyListener 🚀

Create a Simple Menu Bar

The JMenu and the JMenuItem are used to create a menu bar in Java. Create a Java file with the following code to create a Menu bar with three items and two sub-items. The “File” menu contains three items. These are “Open”, “Save”, and “Recent” files. The last menu item contains two sub-items. These are “File 1” and “File 2”.

class SwingExample9 {

public static void main(String[] args) {

//Declare JFrame object

JFrame frame= new JFrame(“Menu Example”);

//Set the window size

frame.setSize(350, 150);

//Disable the resize option

frame.setResizable(false);

//Declare JMenu objects

JMenu menuItem, submenuItem;

//Declare JMenuItem objects

JMenuItem itm1, itm2, itm3, itm4;

//Initialize the JMenuItem objects

itm1=new JMenuItem(“Open”);

itm2=new JMenuItem(“Save”);

itm3=new JMenuItem(“File 1”);

itm4=new JMenuItem(“File 2”);

//Define JMenubar object

JMenuBar mbar=new JMenuBar();

//Initialize the JMenu objects

menuItem=new JMenu(“File”);

submenuItem=new JMenu(“Recent Files”);

//Add menu items

menuItem.add(itm1);

menuItem.add(itm2);

submenuItem.add(itm3);

submenuItem.add(itm4);

menuItem.add(submenuItem);

//Add menu bar item

mbar.add(menuItem);

//Add menu bar to frame

frame.setJMenuBar(mbar);

//Set the window position

frame.setLocationRelativeTo(null);

//Make the window visible

frame.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file:

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.

Create your First Java Project with Netbeans 12.6 | How to Create JFrame Forms using Window Builder
Create your First Java Project with Netbeans 12.6 | How to Create JFrame Forms using Window Builder

Ứ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.

What is a Container Class?

Container classes are classes that can have other components on it. So for creating a Java Swing GUI, we need at least one container object. There are 3 types of Java Swing containers.

  1. Panel: It is a pure container and is not a window in itself. The sole purpose of a Panel is to organize the components on to a window.
  2. Frame: It is a fully functioning window with its title and icons.
  3. Dialog: It can be thought of like a pop-up window that pops out when a message has to be displayed. It is not a fully functioning window like the Frame.
#1 Java Swing Tutorial | JFrame in Java Swing
#1 Java Swing Tutorial | JFrame in Java Swing

Create a Toolbar

The JToolBar class is used to create a toolbar in the Java application. Create a Java file with the following code to create a toolbar with three toolbar buttons. Three images are used here to add the image of the toolbar button. The active listener method is created for each button.

import java.awt.event.ActionEvent;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.*;

import java.awt.event.*;

class SwingExample11 {

public static void main(String[] args) {

//Create a JFrame object

JFrame frame = new JFrame(“Java Swing Example-11”);

//Create a JToolBar object

JToolBar toolbar = new JToolBar();

//Create three toolbar buttons

JButton btnNew = new JButton(new ImageIcon(“/home/fahmida/eclipse-workspace/JavaSwingExamples/src/images/new.jpeg”));

JButton btnOpen = new JButton(new ImageIcon(“/home/fahmida/eclipse-workspace/JavaSwingExamples/src/images/open.png”));

JButton btnSave = new JButton(new ImageIcon(“/home/fahmida/eclipse-workspace/JavaSwingExamples/src/images/save.png”));

//Declare addActionListener methods for three buttons

btnNew.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(frame, “New button is pressed.”);

});

btnOpen.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(frame, “Open button is pressed.”);

});

btnSave.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(frame, “Save button is pressed.”);

});

//Add buttons to the toolbar

toolbar.add(btnNew);

toolbar.add(btnOpen);

toolbar.add(btnSave);

//Set the frame layout

frame.setLayout(new BorderLayout());

//Add toolbar to the frame at the beginning of the frame

frame.getContentPane().add(toolbar, BorderLayout.PAGE_START);

//Set the window size

frame.setSize(500, 250);

//Disable the resize option

frame.setResizable(false);

//Set window position

frame.setLocationRelativeTo(null);

//Make the window visible

frame.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file:

If the user clicks on the “New” button, the following output will appear:

What is Swing in Java?

Swing in Java is a Graphical User Interface (GUI) toolkit that includes the GUI components. Swing provides a rich set of widgets and packages to make sophisticated GUI components for Java applications. Swing is a part of Java Foundation Classes(JFC), which is an API for Java GUI programing that provide GUI.

The Java Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older, platform dependent GUI toolkit. You can use the Java simple GUI programming components like button, textbox, etc., from the library and do not have to create the components from scratch.

In this Java Swing tutorial, you will learn Java GUI basics like-

  • What is Swing in Java?
  • What is a Container Class?
  • What is GUI in Java?
  • How to Make a GUI in Java with Example
  • Java Layout Manager
  • Java BorderLayout
  • Java FlowLayout
  • Java GridBagLayout

Java Swing class Hierarchy Diagram

All components in Java Swing are JComponent which can be added to container classes.

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

Open an Existing File

The JFileChooser class is used to open an existing file or save a file. Create a Java file with the following code that opens an existing file for reading. If the selected file contains any content, the content is displayed in the console.

import javax.swing.*;

import javax.swing.filechooser.FileNameExtensionFilter;

import javax.swing.filechooser.FileSystemView;

class SwingExample6 {

public static void main(String[] args) {

//Create a JFileChooser object

JFileChooser fc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());

//Disable all file types selection

fc.setAcceptAllFileFilterUsed(false);

//Set the filter

FileNameExtensionFilter filter = new FileNameExtensionFilter(“Text Files”, “txt”);

//Apply the filter

fc.addChoosableFileFilter(filter);

//Display open dialog box

int Val = fc.showOpenDialog(null);

//Check Open button is selected or not

if (Val == JFileChooser.APPROVE_OPTION)

BufferedReader buffer = null;

try

//Read the selected file

File sFile = fc.getSelectedFile();

//Read the path

File file = new File(sFile.getAbsolutePath());

//Initialize the BufferedReader object

buffer = new BufferedReader(new FileReader(file));

//Declare variables to store the file content

String storage=””, line;

//Read the file

while ((line = buffer.readLine()) != null)

//Store the file content

storage = storage+line+”\n”;

//Print the file content in the console

System.out.println(storage);

} catch (FileNotFoundException ex) {

System.out.println(“File does not exist.”);

} catch (IOException ex) {

System.out.println(“Unable to access the file.”);

Output:

The file open dialog box will appear after executing the Java class file. Any text file can be selected by browsing the folder here:

Here, the “test.txt” file is selected and the content of this file is printed in the console:

Generate a Random Number

The “Random” class is used to generate different types of random numbers. Create a Java file with the following code that generates a random number between 1 to 100 when the button is pressed. The generated random number is displayed in a message dialog box.

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.Random;

import javax.swing.*;

class SwingExample14 {

public static void main(String[] args) {

//Declare a Frame object

JFrame frame = new JFrame();

//Disable default frame layout

frame.setLayout(null);

//Create a button object

JButton btn = new JButton(“Generate Number”);

//Set the font type of the button

btn.setFont(new Font(“Verdana”, Font.BOLD, 20));

//Set the button position

btn.setBounds(45, 50, 250, 40);

//Add button to the frame

frame.add(btn);

//Add the action listener for the button

btn.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

//Create a random object

Random num = new Random();

//Generate a random number

int n = num.nextInt(100) + 1;

//Convert integer to string

String rnum = String.valueOf(n);

//Display the random number in the message box

JOptionPane.showMessageDialog(frame, “Generated Number: ” + rnum);

});

//Set the title

frame.setTitle(“Java Swing Example-14”);

//Set the window size

frame.setSize(350, 200);

//Disable the resize option

frame.setResizable(false);

//Set window position

frame.setLocationRelativeTo(null);

//Make the window visible

frame.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file:

A new number is generated when the button is pressed and the following similar dialog box will be displayed. Here, the number 98 is generated as a random number:

Java GUI - Simple Calculator using swing and with Event Handling
Java GUI – Simple Calculator using swing and with Event Handling

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…

Java Swing Tutorial: How to Create a GUI Application in Java

Display the Different Types of Dialog Boxes

Different dialog boxes are used in Java to display the messages with different types of buttons and take input from the user. Create a Java file with the following code that displays a message box with an OK button, a message box with the Yes, No, and Cancel buttons, and an input dialog box to take input from the user.

class SwingExample4 {

public static void main(String[] args) {

//Declare a JFrame object

JFrame frame = new JFrame();

//Display a simple message dialog box with a default icon

JOptionPane.showMessageDialog(frame,”Learn Java Swing”);

//Display a simple message dialog box with a warning icon

JOptionPane.showMessageDialog(frame,”Something is missing.”,”Alert”,JOptionPane.WARNING_MESSAGE);

//Take input from the confirm dialog box

int input =JOptionPane.showConfirmDialog(frame,”Do you want to learn Java swing?”);

//Check whether the user pressed YES or not

if(input == JOptionPane.YES_OPTION){

JOptionPane.showMessageDialog(null, “Glad to hear it.”);

//Take string value from the user

String answer = JOptionPane.showInputDialog(“What is your favorite programming language? “);

//Display message with the input value

JOptionPane.showMessageDialog(null, “You like ” + answer + “!”);

Output:

Different dialog boxes will appear one after another after executing the Java class file. The first message box with the OK button appears in the output:

The second message box with an alert icon and an OK button appears in the next output:

The third message box with three buttons appears in the next output:

The following output will appear if the user will select the “Yes” button from the previous dialog box:

Next, the following input dialog box will appear to take input from the user:

The value that is taken from the user is displayed in the last message box:

Form Design with Some Basic Controls

Java has many swing controls to take input from the user. Create a Java file with the following code to know the uses of some basic swing controls. The uses of textbox, radio buttons, and text area controls are shown in this example. The textbox is used to take the product name. The radio button is used to select the product type. The text area is used to take the product description.

class SwingExample3 {

public static void main(String[] args) {

//Declare frame object

JFrame win = new JFrame();

//Set the title

win.setTitle(“Java Swing Example-3”);

//Set the window size

win.setSize(500, 320);

//Create a label object, set the position, and add to the frame

JLabel lbl1 = new JLabel(“Product Name:”, JLabel.LEFT);

lbl1.setBounds(80,20,100,20);

win.add(lbl1);

//Create text object set the position, and add to the frame

JTextField name = new JTextField();

name.setBounds(200,20,200,20);

win.add(name);

//Create a label object, set the position, and add to the frame

JLabel lbl2 = new JLabel(“Product Type:”, JLabel.LEFT);

lbl2.setBounds(80,60,100,20);

win.add(lbl2);

//Create the radio buttons, set the position, and add to the frame

JRadioButton rdbtn1 = new JRadioButton(“Local”);

rdbtn1.setActionCommand(“Local”);

JRadioButton rdbtn2 = new JRadioButton(“Foreign”);

rdbtn2.setActionCommand(“Foreign”);

rdbtn1.setBounds(200,40,80,50);

rdbtn2.setBounds(300,40,90,50);

ButtonGroup bgrp = new ButtonGroup();

bgrp.add(rdbtn1);

bgrp.add(rdbtn2);

win.add(rdbtn1);

win.add(rdbtn2);

/*Create a label object, set the position, and add to the frame */

JLabel lbl3 = new JLabel(“Desctiption:”, JLabel.LEFT);

lbl3.setBounds(80,100,120,20);

win.add(lbl3);

//Create textarea object set the position, and add to the frame

JTextArea txtArea = new JTextArea();

txtArea.setBounds(200,100,200,100);

win.add(txtArea);

//Create a button, set the position, and add to the frame

JButton btn = new JButton(“Submit”);

btn.setBounds(200, 220, 100, 30);

win.add(btn);

//Set window position

win.setLocationRelativeTo(null);

//Disable the default layout of the frame

win.setLayout(null);

//Make the window visible

win.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file:

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

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.

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.

Write a Content into a File

Create a Java file with the following code that saves the string data into a new file using the “Save” dialog box. The string data is stored in the filename that is selected by the user.

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

import javax.swing.*;

import javax.swing.filechooser.FileSystemView;

class SwingExample7 {

public static void main(String[] args) {

//Create a JFileChooser object

JFileChooser fc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());

//Open the Save dialog box

int Val = fc.showSaveDialog(null);

//Check whether the Save button is selected or not

if (Val == JFileChooser.APPROVE_OPTION)

//Set the filename taken from the Save dialog box

File sFile = fc.getSelectedFile();

//Create the path object

Path path = Paths.get(sFile.getAbsolutePath());

//Store the content that will be written in the file

String strVal = “The content of the new file”;

//Convert string to byte array

byte[] strArray = strVal.getBytes();

//Try-catch block to write into the file

try {

//Write the content into the file

Files.write(path, strArray);

catch (IOException ex) {

//Print the error message

System.out.print(“File Path does not exist.”);

Output:

The following dialog box will appear after executing the Java class file. Type the filename that will be created to store the data. Here, the “testingfile.txt” is used as the filename:

The following output shows that the file is created in the desired location:

List of Java Swing Examples

  1. Display a Simple Window
  2. Simple Form Design with Label and Button
  3. Form Design with Basic Controls
  4. Display the Different Types of Dialog Boxes
  5. Form Validation
  6. Open an Existing File
  7. Write a Content into a File
  8. Display the Current Data and Time
  9. Create a Simple Menu Bar
  10. Create a Popup Menu
  11. Create Toolbar
  12. Display Tabular Data
  13. Working with Image
  14. Generate a Random Number
  15. Develop a Simple Login System

Keywords searched by users: java swing simple program

Categories: Khám phá 31 Java Swing Simple Program

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 Tutorial - Javatpoint
Java Swing Tutorial – Javatpoint
15 Java Swing Examples
15 Java Swing Examples
Swing (Java) - Wikipedia
Swing (Java) – Wikipedia
15 Java Swing Examples
15 Java Swing Examples
Swing (Java) - Wikipedia
Swing (Java) – Wikipedia
Hello World | Java Swing Tutorial For Beginners - Youtube
Hello World | Java Swing Tutorial For Beginners – Youtube
Gui Programming - Java Programming Tutorial
Gui Programming – Java Programming Tutorial
Swing Program In Java | A Brief Overview Of Swing Program In Java
Swing Program In Java | A Brief Overview Of Swing Program In Java
Java Swing Tutorial - Javatpoint
Java Swing Tutorial – Javatpoint
Swing - Hand-Coded Gui - Java - Stack Overflow
Swing – Hand-Coded Gui – Java – Stack Overflow
How To Beautify Your Java Applications | Opensource.Com
How To Beautify Your Java Applications | Opensource.Com
Java Swing | Simple User Registration Form - Geeksforgeeks
Java Swing | Simple User Registration Form – Geeksforgeeks
Java Swing Address Book | Wideskills
Java Swing Address Book | Wideskills
Java Swing Tutorial: How To Create A Gui Application In Java
Java Swing Tutorial: How To Create A Gui Application In Java
Introduction To Java Swing - Geeksforgeeks
Introduction To Java Swing – Geeksforgeeks
Advanced Java: Swing (Gui) Programming Part 3 -- Panels And Forms - Youtube
Advanced Java: Swing (Gui) Programming Part 3 — Panels And Forms – Youtube
Java-Swing · Github Topics · Github
Java-Swing · Github Topics · Github
Swing Components In Java | Top 13 Useful Components Of Swing In Java
Swing Components In Java | Top 13 Useful Components Of Swing In Java

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 *