SWING USING JAVA WITH VARIOUS COMPONENTS

785 views 33 slides Dec 13, 2023
Slide 1
Slide 1 of 33
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33

About This Presentation

This presentation contains the following topics.,
Introduction to Swing; MVC; Events and Listeners; Adapters; Text
Components; Look and feel; Swing Components; JTextField, JLabel,
JButton, JScrollBar, JSlider, JProgressBar, JList, JComboBox; Containers
and Frames; Layout Managers; Menus and To...


Slide Content

SWING

Introduction to Swing 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. The javax.swing package provides classes for java swing API such as JButton , JTextField , JTextArea , JRadioButton , JCheckbox , JMenu , JColorChooser etc . Putting together all these components makes a graphical user interface It is build on top of the AWT API and entirely written in  java .

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.

Swing Events  Events are generated as a result of user interaction with the graphical user interface components . For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from the list, and scrolling the page are the activities that causes an event to occur.

Types of Swing Events Action Events : These events are triggered by user actions like button clicks and menu selections. They are typically used to perform specific tasks or actions. Mouse Events : These events are triggered by mouse actions such as clicks, movements, and drags. They are useful for creating interactive graphics and handling mouse-based interactions. Key Events : Key events are generated when the user interacts with the keyboard. You can capture and respond to keystrokes like key presses and releases. Window Events : Window events are associated with the JFrame and include actions like opening, closing, resizing, and moving the window. These events are important for managing the application's user interface.

Event Listeners and Handling Event Listeners : In Swing, event listeners are responsible for monitoring specific components and reacting to events. Common event listener interfaces include ActionListener , MouseListener , and KeyListener . Registering Event Listeners : To handle events, you need to register listeners with the components that generate events. For example, to handle a button click, you would register an ActionListener with the button.

Swing Adapters Swing Adapters are classes provided by Swing to simplify event listener implementation. They act as intermediary classes that provide default implementations for various listener interfaces, allowing developers to override only the specific methods they need.

Types of Swing Adapters Adapter Classes : Swing provides adapter classes for various listener interfaces. Some common adapter classes include: MouseAdapter : Provides default implementations for mouse-related events (e.g., mouseClicked , mousePressed ). KeyAdapter : Offers default implementations for keyboard-related events (e.g., keyPressed , keyReleased ). WindowAdapter : Simplifies window-related events (e.g., windowOpened , windowClosing ). FocusAdapter : Deals with focus-related events (e.g., focusGained , focusLost ). Custom Adapter Classes : Developers can also create their custom adapter classes by extending the adapter classes provided by Swing and overriding specific methods as needed.

import javax.swing .*; import java.awt.event.MouseAdapter ; import java.awt.event.MouseEvent ; public class SwingAdapterExample { public static void main(String[] args ) { JFrame frame = new JFrame ("Swing Adapter Example"); JButton button = new JButton ("Click Me "); button.addMouseListener (new MouseAdapter () { @Override public void mouseClicked ( MouseEvent e) { JOptionPane.showMessageDialog (frame, "Button Clicked!"); } }); frame.add (button ); frame.setSize (300, 200); frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ); frame.setVisible (true); } }

Hierarchy of Java Swing classes

Text Components in Swing : Swing provides a variety of text components that allow you to work with text, both for displaying and editing purposes .

Common Swing Text Components JTextField - Single-Line Text Input JTextField : This component is used for single-line text input fields. It's ideal for short text input, such as usernames and search queries. You can add event listeners to respond to user input. JTextArea - Multi-Line Text Input JTextArea : Use this component when you need multi-line text input and display. It's suitable for text fields that may contain paragraphs or longer descriptions. You can control scrolling and set word wrap preferences. JTextPane and JEditorPane - Rich Text Editing JTextPane and JEditorPane : These components support rich text formatting, including bold, italics, underline, and the display of inline images. JTextPane is designed for plain text with formatting. JEditorPane can handle HTML content in addition to plain text.

import javax.swing .*; import java.awt .*; public class SwingTextComponentExample { public static void main(String[] args ) { JFrame frame = new JFrame ("Swing Text Components"); JTextArea textArea = new JTextArea (10, 30); JScrollPane scrollPane = new JScrollPane ( textArea ); frame.add ( scrollPane ); frame.setSize (400, 300); frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ); frame.setVisible (true); } }

Swing components Swing components are the building blocks of graphical user interfaces (GUIs) in Java. They provide a variety of widgets, such as buttons, text fields, labels, menus, and tables, that can be used to create rich and interactive interfaces.

Swing components-Look and feel Swing components are all subclasses of the JComponent class, which provides a common set of methods and properties for all Swing components. For example, all Swing components can be resized, moved, and added to other Swing components.

Swing component classes

Common Swing Components JFrame : JFrame is the top-level container for a Swing application, serving as the main window for your application. JPanel : JPanel is a lightweight container used to group and organize other components, providing layout flexibility. JButton : JButton is a basic button component that responds to user clicks. JLabel : JLabel is used for displaying non-editable text or images. JTextField : JTextField is a single-line text input field for user data entry. JTextArea : JTextArea is a multi-line text input and display area. JCheckBox and JRadioButton : These components are used for making selections in the form of checkboxes and radio buttons. JComboBox : JComboBox is a drop-down list or combo box for selecting items from a list. JSlider : JSlider allows users to select a value from a range by moving a slider. JTable : JTable is used to display and edit tabular data. JFileChooser : JFileChooser provides a dialog for selecting files and directories.

import javax.swing .*; import java.awt .*; public class SwingComponentsExample { public static void main(String[] args ) { JFrame frame = new JFrame ("Swing Components Example"); JPanel panel = new JPanel (); JButton button = new JButton ("Click Me"); JLabel label = new JLabel ("Hello, Swing !"); panel.add (label); panel.add (button); frame.add (panel); frame.setSize (300, 200); frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ); frame.setVisible (true); } }

Containers and Frames Understanding Containers : In graphical user interface (GUI) programming, containers are essential components that hold and organize other graphical elements, such as buttons, labels, and text fields. Containers provide structure and layout for GUI components. The Role of Frames : A frame is a top-level container in Swing. It represents the main window of a GUI application. Frames serve as the outermost structure for organizing and displaying various components.

Types of Containers JFrame : The JFrame class is used to create the main application window. It is a top-level container that typically contains all other GUI components. You can set attributes such as the window's title, size, and close operation. JPanel : The JPanel class is a lightweight container that can be used within a JFrame or other containers. It is often used to group related components and provides layout flexibility. Content Pane : The content pane is a container that resides within the JFrame . It is where most GUI components are add ed . The content pane allows you to arrange components using layout managers.

Frames and Containers in Swing Applications Creating a Frame : To create a frame, you instantiate a JFrame object, set its attributes, and add components to it. Adding Components : Use the add() method to add components like buttons, labels, and text fields to containers, such as the content pane of a JFrame . Layout Managers : Layout managers are used to control the arrangement and positioning of components within containers. Common layout managers include FlowLayout , BorderLayout , and GridLayout . Event Handling : Implement event listeners to make the GUI components interactive. For instance, use an ActionListener to handle button clicks.

import javax.swing .*; import java.awt .*; public class SwingContainerExample { public static void main(String[] args ) { JFrame frame = new JFrame ("Swing Container Example"); JPanel panel = new JPanel (); JButton button = new JButton ("Click Me"); JLabel label = new JLabel ("Hello, Swing!"); panel.add (label); panel.add (button); frame.add (panel); frame.setSize (300, 200); frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ); frame.setVisible (true); } }

Swing menus and toolbars Swing tables and trees are essential components in Java for creating structured, data-rich graphical user interfaces (GUIs). Tables are used for displaying data in rows and columns, while trees are employed for hierarchical data representation.

Tables and Trees JTable : JTable is a Swing component for displaying tabular data in a grid format. It's ideal for structured and spreadsheet-like data presentation . JTree : JTree , on the other hand, is used to display hierarchical data, such as file systems, organization charts, or nested categories.

Creating JTables Creating a Basic JTable : You can create a simple JTable by instantiating the JTable class and providing it with a TableModel to define the data structure. TableModel : The TableModel interface is responsible for managing and retrieving the data to be displayed in the JTable . You can use default implementations like DefaultTableModel or create custom models. Customizing JTable : You can customize JTables by defining custom cell renderers and editors to format and handle cell contents.

import java.awt.FlowLayout ; import java.awt.GridLayout ; import java.awt.event.WindowAdapter ; import java.awt.event.WindowEvent ; import javax.swing.JFrame ; import javax.swing.JLabel ; import javax.swing.JPanel ; import javax.swing.JScrollPane ; import javax.swing.JTable ; public class SwingTester { private JFrame mainFrame ; private JLabel headerLabel ; private JLabel statusLabel ; private JPanel controlPanel ;

public SwingTester (){ prepareGUI (); } public static void main(String[] args ){ SwingTester swingControlDemo = new SwingTester (); swingControlDemo.showTableDemo (); } private void prepareGUI (){ mainFrame = new JFrame ("Java Swing Examples"); mainFrame.setSize (500,400); mainFrame.setLayout (new GridLayout (3, 1)); mainFrame.addWindowListener (new WindowAdapter () { public void windowClosing ( WindowEvent windowEvent ){ System.exit (0); } }); headerLabel = new JLabel ("", JLabel.CENTER ); statusLabel = new JLabel ("", JLabel.CENTER ); statusLabel.setSize (350,100);

controlPanel = new JPanel (); controlPanel.setLayout (new FlowLayout ()); mainFrame.add ( headerLabel ); mainFrame.add ( controlPanel ); mainFrame.add ( statusLabel ); mainFrame.setVisible (true); } private void showTableDemo (){ headerLabel.setText ("Control in action: JTable "); String[] columnNames = {"Name", "Salary"}; Object[][] data = { {"Ramesh Raman", 5000}, {" Shabbir Hussein", 7000} }; JTable table = new JTable (data, columnNames ); JScrollPane scrollPane = new JScrollPane (table); scrollPane.setSize (300, 300); table.setFillsViewportHeight (true); controlPanel.add ( scrollPane ); mainFrame.setVisible (true); } }

Creating JTrees Creating a Basic JTree : JTrees require a TreeModel to define the structure. You can create a simple JTree by setting up a DefaultTreeModel . TreeNode : JTree nodes are represented by the TreeNode interface, allowing for a flexible hierarchical structure. Customizing JTree : You can customize JTrees by creating custom cell renderers, editors, and custom icons for nodes.

We are using the following APIs . JTree (root)  − To create a tree. DefaultMutableTreeNode ()  − To create a tree node. DefaultMutableTreeNode ().add(node)  − To add a tree node to a tree node.