This document provides an overview of Swing components for creating graphical user interfaces in Java. It discusses top-level containers like JFrame and JDialog, general purpose containers like JPanel and JScrollPane, basic controls for user input like JTextField and JButton, components for displaying information like JLabel and JTable, and various layout managers including FlowLayout, BorderLayout, GridLayout, BoxLayout, and GridBagLayout. It also covers using borders with components and implementing listeners for text fields. The document is intended to teach what is needed to create full-featured GUIs with Swing.
The wrapper classes in Java are used to convert primitive data types like int and float into objects. There are eight wrapper classes that correspond to the eight primitive types. Wrapper classes allow primitive types to be used in contexts that require objects, like collections. They provide methods to convert between primitive types and their corresponding wrapper class objects.
This document provides an overview of Java Swing components. It defines Swing as a GUI toolkit built on top of AWT that provides platform-independent and lightweight components. It describes common Swing components like JButton, JTextField, JTextArea and their usage. It also compares AWT and Swing, explaining how Swing components are more powerful and support pluggable look and feel while AWT is platform-dependent. Examples are given to demonstrate creating and using Swing components like JButton, JTextField, JTextArea etc.
Java Swing is a GUI toolkit that is used to create window-based applications. It is built on top of AWT and provides more powerful and lightweight components like tables, lists, scroll panes etc. Swing components are platform-independent and follow the MVC architecture. Common Swing components include JButton, JTextField, JTextArea and common layouts include FlowLayout, BorderLayout, GridLayout etc. Menus in Swing can support keyboard navigation using mnemonics and shortcuts using accelerators.
The document discusses various event handling classes in Java including ActionEvent, KeyEvent, MouseEvent, MouseMotionEvent, FocusEvent, WindowEvent, and ItemEvent. It provides examples of how to use each event class by implementing the appropriate listener interface and defining event handling methods. Key points covered include common event handling terms like event, event source, and event listener. It also summarizes the typical methods provided by each event class.
Servlet is java class which extends the functionality of web server by dynamically generating web pages.
Servlet technology is used to create Dynamic web application. Servlet technology is robust and scalable. init() and service() methods are more important in life cycle of a servlet. doGet() and doPost() are methods used under service() method.
This document provides an overview of Applets and Java GUI programming. It discusses Applets, their life cycle, how to run Applets using AppletViewer and HTML, and classes used in Applet programming like Applet, Graphics, Color, Font, and AWT components. It also covers Swing components like JApplet, JComponent, JLabel, JTextField, JButton, and JRadioButton. Code examples and demonstrations are provided for many of the concepts discussed.
Object-oriented programming Undergraduate Course Presentations
java.io streams and files in Java
University of Vale do Itajaí
Univali
Incremental Tecnologia
English version
The wrapper classes in Java are used to convert primitive data types like int and float into objects. There are eight wrapper classes that correspond to the eight primitive types. Wrapper classes allow primitive types to be used in contexts that require objects, like collections. They provide methods to convert between primitive types and their corresponding wrapper class objects.
This document provides an overview of Java Swing components. It defines Swing as a GUI toolkit built on top of AWT that provides platform-independent and lightweight components. It describes common Swing components like JButton, JTextField, JTextArea and their usage. It also compares AWT and Swing, explaining how Swing components are more powerful and support pluggable look and feel while AWT is platform-dependent. Examples are given to demonstrate creating and using Swing components like JButton, JTextField, JTextArea etc.
Java Swing is a GUI toolkit that is used to create window-based applications. It is built on top of AWT and provides more powerful and lightweight components like tables, lists, scroll panes etc. Swing components are platform-independent and follow the MVC architecture. Common Swing components include JButton, JTextField, JTextArea and common layouts include FlowLayout, BorderLayout, GridLayout etc. Menus in Swing can support keyboard navigation using mnemonics and shortcuts using accelerators.
The document discusses various event handling classes in Java including ActionEvent, KeyEvent, MouseEvent, MouseMotionEvent, FocusEvent, WindowEvent, and ItemEvent. It provides examples of how to use each event class by implementing the appropriate listener interface and defining event handling methods. Key points covered include common event handling terms like event, event source, and event listener. It also summarizes the typical methods provided by each event class.
Servlet is java class which extends the functionality of web server by dynamically generating web pages.
Servlet technology is used to create Dynamic web application. Servlet technology is robust and scalable. init() and service() methods are more important in life cycle of a servlet. doGet() and doPost() are methods used under service() method.
This document provides an overview of Applets and Java GUI programming. It discusses Applets, their life cycle, how to run Applets using AppletViewer and HTML, and classes used in Applet programming like Applet, Graphics, Color, Font, and AWT components. It also covers Swing components like JApplet, JComponent, JLabel, JTextField, JButton, and JRadioButton. Code examples and demonstrations are provided for many of the concepts discussed.
Object-oriented programming Undergraduate Course Presentations
java.io streams and files in Java
University of Vale do Itajaí
Univali
Incremental Tecnologia
English version
The document discusses key concepts in Java including classes, objects, methods, and command line arguments. A class defines common properties and behaviors for objects through fields and methods. Objects are instantiated from classes and can access fields and methods using dot notation. Command line arguments allow passing data into a Java application and are accessed through the args parameter in the main method.
This document provides an overview of GUI programming in Java, including basic concepts, AWT vs Swing frameworks, common control components, layout managers, and event handling. It discusses the key differences between AWT and Swing, describes common control components in both frameworks, explains different types of layout managers like flow, border, and grid layouts, and lists additional references for further reading.
Wrapper classes allow primitive data types to be used as objects. Wrapper classes include Integer, Double, Boolean etc. Strings in Java are immutable - their values cannot be changed once created. StringBuffer and StringBuilder can be used to create mutable strings that can be modified. StringTokenizer can split a string into tokens based on a specified delimiter.
String Function
1. charAt():
This method returns the character from the specified index.Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a string called stringName is stringName.length - 1.
Syntax:
string.charAt(index);
Return Value:
Returns the character from the specified index.
Example:
<html>
<head>
<title>JavaScript String charAt() Method</title>
</head>
<body>
</body>
</html>
Output:
str.charAt(0) is:T
2. concat():
Description:
This method adds two or more strings and returns a new single string.
Syntax:
string.concat(string2, string3[, ..., stringN]);
parameters:
string2...stringN : These are the strings to be concatenated.
Return Value:
Returns a single concatenated string.
Example:
<html>
<head>
<title>JavaScript String concat() Method</title>
</head>
<body>
</body>
</html>
Output:
Concatenated String :This is string oneThis is string two.
3. indexOf():
Description:
This method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex or -1 if the value is not found.
Syntax:
string.indexOf(searchValue[, fromIndex])
Parameters:
searchValue : A string representing the value to search for.
fromIndex : The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0.
Return Value:
Returns the index of the found occurrence otherwise -1 if not found.
Example:
<html>
<head>
<title>JavaScript String indexOf() Method</title>
</head>
<body>
<br />");
var index = str1.indexOf( "one" );
document.write("indexOf found String :" + index );
</body></html>
Oputput:
indexOf found String :8
indexOf found String :15
4. lastIndexOf():
Description:
This method returns the index within the calling String object of the last occurrence of the specified value, starting the search at fromIndex or -1 if the value is not found.
Syntax:
string.lastIndexOf(searchValue[, fromIndex])
Parameters:
searchValue : A string representing the value to search for.
fromIndex : The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0.
Return Value:
Returns the index of the last found occurrence otherwise -1 if not found.
Example:
<html>
<head>
<title>JavaScri
This document discusses data types and variables in Java. It explains that there are two types of data types in Java - primitive and non-primitive. Primitive types include numeric types like int and float, and non-primitive types include classes, strings, and arrays. It also describes different types of variables in Java - local, instance, and static variables. The document provides examples of declaring variables and assigning literals. It further explains concepts like casting, immutable strings, StringBuffer/StringBuilder classes, and arrays.
Structures allow grouping of related data and can be used to represent records. A structure defines a template for the format of its members. Structures can contain basic data types and arrays. Structure variables can be initialized, and members accessed using dot operator. Arrays of structures can be used to represent tables of related data. Unions share the same storage location for members, allowing only one member to be active at a time. Both structures and unions can be used as function parameters.
Hashtable is a legacy implementation of a map or key-value pairs in Java. It uses a hash table to store keys and values, where the key is used to find the corresponding value. Hashtable does not allow null keys or values. It is synchronized, which makes it slower than newer implementations like HashMap. Hashtable uses separate chaining to handle collisions when multiple keys hash to the same bucket.
This document discusses arrays in Java programming. It covers defining and creating single and multi-dimensional arrays, accessing array elements using indexes and loops, and performing operations like sorting and finding maximum/minimum values. Examples are provided for different array types like integer, string and character arrays, and operations like input/output, break/continue statements, and star patterns. Homework involves writing a program to produce a given output pattern.
A thread is an independent path of execution within a Java program. The Thread class in Java is used to create threads and control their behavior and execution. There are two main ways to create threads - by extending the Thread class or implementing the Runnable interface. The run() method contains the code for the thread's task and threads can be started using the start() method. Threads have different states like New, Runnable, Running, Waiting etc during their lifecycle.
This document discusses implementation of inheritance in Java and C#. It covers key inheritance concepts like simple, multilevel, and hierarchical inheritance. It provides examples of inheritance in Java using keywords like extends, super, this. Interfaces are discussed as a way to achieve multiple inheritance in Java. The document also discusses implementation of inheritance in C# using concepts like calling base class constructors and defining virtual methods.
The document discusses Java AWT (Abstract Window Toolkit). It describes that AWT is an API that allows developing GUI applications in Java. It provides classes like TextField, Label, TextArea etc. for building GUI components. The document then explains key AWT concepts like containers, windows, panels, events, event handling model, working with colors and fonts.
The document discusses arrays in Java, including how to declare and initialize one-dimensional and two-dimensional arrays, access array elements, pass arrays as parameters, and sort and search arrays. It also covers arrays of objects and examples of using arrays to store student data and daily temperature readings from multiple cities over multiple days.
String is a non-primitive and immutable data type in Java that represents a sequence of characters. It is stored in the String Constant Pool in the heap memory. Methods like equals(), concat(), contains(), indexOf() etc. are used to perform operations on strings. String is immutable to prevent unexpected behavior if the contents of a string are changed.
Creating a frame within an applet involves:
1. Creating a subclass of Frame
2. Overriding window methods like init(), start(), stop(), and paint()
3. Implementing the windowClosing() method to call setVisible(false) when the window closes
An example program creates a SampleFrame subclass, instantiates it in the applet's init() method, and overrides start() and stop() to show/hide the frame. The frame is given a size and title and made initially invisible, later being set to visible.
The document discusses Swing, the graphical user interface (GUI) toolkit for Java. It introduces Swing as a replacement for the original Abstract Window Toolkit (AWT) that improved on AWT's weaknesses. Key points covered include:
- Swing was introduced in 1997 as part of the Java Foundation Classes to address AWT's limitations. It uses lightweight components instead of relying on native platform components.
- Swing supports pluggable look-and-feel and is based on the model-view-controller architecture. It includes a variety of common GUI components like tables, trees, sliders.
- Layout managers like FlowLayout, GridLayout, BorderLayout, and BoxLayout are used to position and
Threads allow multiple tasks to run concurrently within a single Java program. A thread represents a separate path of execution and threads can be used to improve performance. There are two main ways to create threads: by extending the Thread class or implementing the Runnable interface. Threads transition between different states like new, runnable, running, blocked, and terminated. Synchronization is needed to prevent race conditions when multiple threads access shared resources simultaneously. Deadlocks can occur when threads wait for each other in a circular manner.
Collections Framework is a unified architecture for managing collections, Main Parts of Collections Framework
1. Interfaces :- Core interfaces defining common functionality exhibited by collections
2. Implementations :- Concrete classes of the core interfaces providing data structures
3. Operations :- Methods that perform various operations on collections
This document provides an overview of threads in Java, including:
- Threads allow for multitasking by executing multiple processes simultaneously. They are lightweight processes that exist within a process and share system resources.
- Threads can be created by extending the Thread class or implementing the Runnable interface. The run() method defines the code executed by the thread.
- Threads transition between states like new, runnable, running, blocked, and dead during their lifecycle. Methods like start(), sleep(), join(), etc. impact the thread states.
- Synchronization is used to control access to shared resources when multiple threads access methods and data outside their run() methods. This prevents issues like inconsistent data.
Hibernate is an object-relational mapping tool that allows developers to more easily write applications that interact with relational databases. It does this by allowing developers to map Java classes to database tables and columns, so that developers can interact with data through Java objects rather than directly with SQL statements. Hibernate handles the conversion between Java objects and database rows behind the scenes. Some key benefits of using Hibernate include faster data retrieval, avoiding manual database connection management, and easier handling of database schema changes.
This document provides information on two spring training courses offered by YAAZLI INTERNATIONAL: Spring Core and Spring Web.
The Spring Core training covers topics related to the core Spring framework including configuration, dependency injection, the bean lifecycle, data access, transactions, and Spring Boot.
The Spring Web training focuses on building web applications with Spring MVC and covers topics such as configuration, form handling, security, testing, and Spring Boot.
Both courses are 32 hours and include daily, weekend, and crash class options in Chennai, India. The target audience includes web developers and the prerequisite is Java knowledge. Contact details are provided at the end.
Based on chapter 2 of the textbook "Building Java Programs", 3rd edition. Covers primitive data types, variables, operators, ASCII values for chars, operator precedence, String concatenation, casting, for loops, nested for loops, and class constants.
See a video presentation of this slideshow on my YouTube channel JavaGoddess, at https://www.youtube.com/watch?v=N7SBkMY65gc&t=4s
The document discusses key concepts in Java including classes, objects, methods, and command line arguments. A class defines common properties and behaviors for objects through fields and methods. Objects are instantiated from classes and can access fields and methods using dot notation. Command line arguments allow passing data into a Java application and are accessed through the args parameter in the main method.
This document provides an overview of GUI programming in Java, including basic concepts, AWT vs Swing frameworks, common control components, layout managers, and event handling. It discusses the key differences between AWT and Swing, describes common control components in both frameworks, explains different types of layout managers like flow, border, and grid layouts, and lists additional references for further reading.
Wrapper classes allow primitive data types to be used as objects. Wrapper classes include Integer, Double, Boolean etc. Strings in Java are immutable - their values cannot be changed once created. StringBuffer and StringBuilder can be used to create mutable strings that can be modified. StringTokenizer can split a string into tokens based on a specified delimiter.
String Function
1. charAt():
This method returns the character from the specified index.Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a string called stringName is stringName.length - 1.
Syntax:
string.charAt(index);
Return Value:
Returns the character from the specified index.
Example:
<html>
<head>
<title>JavaScript String charAt() Method</title>
</head>
<body>
</body>
</html>
Output:
str.charAt(0) is:T
2. concat():
Description:
This method adds two or more strings and returns a new single string.
Syntax:
string.concat(string2, string3[, ..., stringN]);
parameters:
string2...stringN : These are the strings to be concatenated.
Return Value:
Returns a single concatenated string.
Example:
<html>
<head>
<title>JavaScript String concat() Method</title>
</head>
<body>
</body>
</html>
Output:
Concatenated String :This is string oneThis is string two.
3. indexOf():
Description:
This method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex or -1 if the value is not found.
Syntax:
string.indexOf(searchValue[, fromIndex])
Parameters:
searchValue : A string representing the value to search for.
fromIndex : The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0.
Return Value:
Returns the index of the found occurrence otherwise -1 if not found.
Example:
<html>
<head>
<title>JavaScript String indexOf() Method</title>
</head>
<body>
<br />");
var index = str1.indexOf( "one" );
document.write("indexOf found String :" + index );
</body></html>
Oputput:
indexOf found String :8
indexOf found String :15
4. lastIndexOf():
Description:
This method returns the index within the calling String object of the last occurrence of the specified value, starting the search at fromIndex or -1 if the value is not found.
Syntax:
string.lastIndexOf(searchValue[, fromIndex])
Parameters:
searchValue : A string representing the value to search for.
fromIndex : The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0.
Return Value:
Returns the index of the last found occurrence otherwise -1 if not found.
Example:
<html>
<head>
<title>JavaScri
This document discusses data types and variables in Java. It explains that there are two types of data types in Java - primitive and non-primitive. Primitive types include numeric types like int and float, and non-primitive types include classes, strings, and arrays. It also describes different types of variables in Java - local, instance, and static variables. The document provides examples of declaring variables and assigning literals. It further explains concepts like casting, immutable strings, StringBuffer/StringBuilder classes, and arrays.
Structures allow grouping of related data and can be used to represent records. A structure defines a template for the format of its members. Structures can contain basic data types and arrays. Structure variables can be initialized, and members accessed using dot operator. Arrays of structures can be used to represent tables of related data. Unions share the same storage location for members, allowing only one member to be active at a time. Both structures and unions can be used as function parameters.
Hashtable is a legacy implementation of a map or key-value pairs in Java. It uses a hash table to store keys and values, where the key is used to find the corresponding value. Hashtable does not allow null keys or values. It is synchronized, which makes it slower than newer implementations like HashMap. Hashtable uses separate chaining to handle collisions when multiple keys hash to the same bucket.
This document discusses arrays in Java programming. It covers defining and creating single and multi-dimensional arrays, accessing array elements using indexes and loops, and performing operations like sorting and finding maximum/minimum values. Examples are provided for different array types like integer, string and character arrays, and operations like input/output, break/continue statements, and star patterns. Homework involves writing a program to produce a given output pattern.
A thread is an independent path of execution within a Java program. The Thread class in Java is used to create threads and control their behavior and execution. There are two main ways to create threads - by extending the Thread class or implementing the Runnable interface. The run() method contains the code for the thread's task and threads can be started using the start() method. Threads have different states like New, Runnable, Running, Waiting etc during their lifecycle.
This document discusses implementation of inheritance in Java and C#. It covers key inheritance concepts like simple, multilevel, and hierarchical inheritance. It provides examples of inheritance in Java using keywords like extends, super, this. Interfaces are discussed as a way to achieve multiple inheritance in Java. The document also discusses implementation of inheritance in C# using concepts like calling base class constructors and defining virtual methods.
The document discusses Java AWT (Abstract Window Toolkit). It describes that AWT is an API that allows developing GUI applications in Java. It provides classes like TextField, Label, TextArea etc. for building GUI components. The document then explains key AWT concepts like containers, windows, panels, events, event handling model, working with colors and fonts.
The document discusses arrays in Java, including how to declare and initialize one-dimensional and two-dimensional arrays, access array elements, pass arrays as parameters, and sort and search arrays. It also covers arrays of objects and examples of using arrays to store student data and daily temperature readings from multiple cities over multiple days.
String is a non-primitive and immutable data type in Java that represents a sequence of characters. It is stored in the String Constant Pool in the heap memory. Methods like equals(), concat(), contains(), indexOf() etc. are used to perform operations on strings. String is immutable to prevent unexpected behavior if the contents of a string are changed.
Creating a frame within an applet involves:
1. Creating a subclass of Frame
2. Overriding window methods like init(), start(), stop(), and paint()
3. Implementing the windowClosing() method to call setVisible(false) when the window closes
An example program creates a SampleFrame subclass, instantiates it in the applet's init() method, and overrides start() and stop() to show/hide the frame. The frame is given a size and title and made initially invisible, later being set to visible.
The document discusses Swing, the graphical user interface (GUI) toolkit for Java. It introduces Swing as a replacement for the original Abstract Window Toolkit (AWT) that improved on AWT's weaknesses. Key points covered include:
- Swing was introduced in 1997 as part of the Java Foundation Classes to address AWT's limitations. It uses lightweight components instead of relying on native platform components.
- Swing supports pluggable look-and-feel and is based on the model-view-controller architecture. It includes a variety of common GUI components like tables, trees, sliders.
- Layout managers like FlowLayout, GridLayout, BorderLayout, and BoxLayout are used to position and
Threads allow multiple tasks to run concurrently within a single Java program. A thread represents a separate path of execution and threads can be used to improve performance. There are two main ways to create threads: by extending the Thread class or implementing the Runnable interface. Threads transition between different states like new, runnable, running, blocked, and terminated. Synchronization is needed to prevent race conditions when multiple threads access shared resources simultaneously. Deadlocks can occur when threads wait for each other in a circular manner.
Collections Framework is a unified architecture for managing collections, Main Parts of Collections Framework
1. Interfaces :- Core interfaces defining common functionality exhibited by collections
2. Implementations :- Concrete classes of the core interfaces providing data structures
3. Operations :- Methods that perform various operations on collections
This document provides an overview of threads in Java, including:
- Threads allow for multitasking by executing multiple processes simultaneously. They are lightweight processes that exist within a process and share system resources.
- Threads can be created by extending the Thread class or implementing the Runnable interface. The run() method defines the code executed by the thread.
- Threads transition between states like new, runnable, running, blocked, and dead during their lifecycle. Methods like start(), sleep(), join(), etc. impact the thread states.
- Synchronization is used to control access to shared resources when multiple threads access methods and data outside their run() methods. This prevents issues like inconsistent data.
Hibernate is an object-relational mapping tool that allows developers to more easily write applications that interact with relational databases. It does this by allowing developers to map Java classes to database tables and columns, so that developers can interact with data through Java objects rather than directly with SQL statements. Hibernate handles the conversion between Java objects and database rows behind the scenes. Some key benefits of using Hibernate include faster data retrieval, avoiding manual database connection management, and easier handling of database schema changes.
This document provides information on two spring training courses offered by YAAZLI INTERNATIONAL: Spring Core and Spring Web.
The Spring Core training covers topics related to the core Spring framework including configuration, dependency injection, the bean lifecycle, data access, transactions, and Spring Boot.
The Spring Web training focuses on building web applications with Spring MVC and covers topics such as configuration, form handling, security, testing, and Spring Boot.
Both courses are 32 hours and include daily, weekend, and crash class options in Chennai, India. The target audience includes web developers and the prerequisite is Java knowledge. Contact details are provided at the end.
Based on chapter 2 of the textbook "Building Java Programs", 3rd edition. Covers primitive data types, variables, operators, ASCII values for chars, operator precedence, String concatenation, casting, for loops, nested for loops, and class constants.
See a video presentation of this slideshow on my YouTube channel JavaGoddess, at https://www.youtube.com/watch?v=N7SBkMY65gc&t=4s
This document outlines an Angular.io training course that provides 40 hours of instruction over 8 days. The course covers key Angular concepts and features through 20 sections, including components, templates, data binding, routing, and HTTP client. It is aimed at UI/UX developers and targets HTML, CSS, and JavaScript knowledge. The training has regular daily classes from 8am to 1pm and 2pm to 7pm, as well as weekend crash classes. For more information, contact Arjun Sridhar on the provided phone number or website.
The document outlines a web project workshop hosted by Yaazli International that provides training on project management, full stack development, and placement assistance. The workshop covers methodologies like PMBOK and SCRUM and technologies like Java, PHP, and UI/UX design. Participants will work in minimum 2-4 member groups on a real client project using SCRUM methodology over 2-4 months of 8 hour daily sessions. The workshop aims to help participants find jobs and also provides technical and HR interview preparation assistance.
This document provides an overview of basic Java programming concepts including:
- Java programs require a main method inside a class and use print statements for output.
- Java has primitive data types like int and double as well as objects. Variables are declared with a type.
- Control structures like if/else and for loops work similarly to other languages. Methods can call themselves recursively.
- Basic input is done through dialog boxes and output through print statements. Formatting is available.
- Arrays are objects that store multiple values of a single type and know their own length. Strings are immutable character arrays.
The Toolbar is a view introduced in Android Lollipop that is easier to customize and position than the ActionBar. It can be used on lower Android versions by including the AppCompat support library. To use the Toolbar as an ActionBar, disable the theme-provided ActionBar, add the Toolbar to the activity layout, and include dependencies for AppCompat and Design support libraries.
This document provides an overview of the topics covered in a Core Java online training course. The course consists of 12 modules that cover Java fundamentals, OOP concepts, collections, files and I/O, threads, exceptions, JDBC and more. Each module includes topics to be covered and programming sessions to apply the concepts learned through examples and exercises.
Exception handling in Java provides a robust way to handle errors and exceptions that occur during program execution. The try-catch block allows code to be wrapped in a try block to protect it, while catch blocks handle any exceptions. Multiple catch blocks can be used to handle different exception types. The throw keyword is used to manually throw an exception, while throws is used to indicate unhandled exceptions in a method signature. Finally, the finally block is used for cleanup and always executes regardless of exceptions.
This document discusses adopting better driving habits by using an application that identifies bad driving behaviors and translates any mishaps into donations to charitable causes, with the goal of making roads safer through self-awareness and investing in goals that motivate safer driving. The application tracks driving habits, notes any issues, and converts incidents into donations, hopefully encouraging improved behaviors and contributing to positive outcomes even if not.
Final year M.E IEEE PROJECTS TITLES 2014-2015 Final year IEEE PROJECTS TITLES 2014-2015 Final year M.TECH IEEE PROJECTS TITLES 2014-2015 Final year B.E IEEE
This document provides information about a Hibernate training course offered by YAAZLI INTERNATIONAL. The 16-hour course covers topics like configuring JPA/Hibernate, mapping objects and relationships, transactions, retrieving and manipulating persistent objects. It is offered in daily 2-hour crash classes, 4-hour weekend batches, or regular 3-day-a-week classes. The course is aimed at web app developers, enterprise app developers, and SQL developers who have prior Java knowledge.
- The document discusses event handling in Java GUI programs.
- It explains the Java AWT event delegation model where event sources generate events that are passed to registered listener objects.
- An example program is shown where a button generates an ActionEvent when clicked, which is handled by a listener class that implements the ActionListener interface.
- The AWT event hierarchy and common event types like KeyEvents and MouseEvents are described. Individual events provide information about user input.
- Adapter classes are mentioned which provide default empty implementations of listener interfaces to simplify coding listeners.
Java provides operators to manipulate variables including arithmetic operators for mathematical expressions like algebra, relational operators to test relations between entities and typically evaluate to true or false, and assignment operators to set values.
Final year M.E, IEEE PROJECTS, TITLES, 2014-2015 Final year IEEE PROJECTS, TITLES 2014-2015, Final year M.TECH IEEE PROJECTS TITLES, 2014-2015 Final, year B.E, ieee project,
Esoft Metro Campus - Diploma in Web Engineering - (Module IX) Using Extensions and Image Manipulation
(Template - Virtusa Corporate)
Contents:
Image Manipulation with PHP
GD Library
ImageCreate()
ImageColorAllocate()
Drawing shapes and lines
imageellipse()
imagearc()
imagepolygon()
imagerectangle()
imageline()
Creating a new image
Using a Color Fill
imagefilledellipse()
imagefilledarc()
imagefilledpolygon()
imagefilledrectangle()
Basic Pie Chart
3D Pie Chart
Modifying Existing Images
imagecreatefrompng()
imagecolortransparent()
imagecopymerge()
Creating a new image…
Stacking images…
Imagestring()
Draw a string
The singleton pattern ensures that only one instance of a class is created. It involves a class that instantiates itself and makes sure no other instances are created, providing a global point of access to the sole instance. Examples of where the singleton pattern is commonly used include logger classes, configuration classes, accessing shared resources, and singleton factories.
Esoft Metro Campus - Diploma in Web Engineering - (Module II) Multimedia Technologies
(Template - Virtusa Corporate)
Contents:
What are Graphics ?
Digital Image Concepts
Pixel
Resolution of Images
Resolution of Devices
Color Depth
Color Palette
Dithering
Bitmap and Vector Graphics
Bitmap Graphics
Vector Graphics
Comparison
Graphics File Formats
Bit Map
Tagged Image File Format
Graphical Interchange Format
Join Picture Expert Group
Portable Network Graphics
Multi-image Network Graphics
Multimedia on Web
Animations
Rollovers
Animated GIF
Flash Files
Audio
Audio on Web Sites
Audio File Formats
MIDI
WAVE
MP3
AU
AIFF
Video
Video File Formats
AVI
ASF
MPEG
QuickTime
RealVideo
Copyrights of Web Content
The document provides information about Java training courses offered by YaaZli International. The Core Java Training course covers topics like Java building blocks, operators, statements, core APIs, methods, encapsulation and class design over 15 daily sessions. The Advanced Java Training course covers advanced class design, design patterns, generics, collections, functional programming, dates, strings, localization, concurrency and IO over 15 daily sessions. Both courses are aligned with Oracle certification exams. The courses have a duration of 32 hours and are offered in regular, crash and weekend batches in Chennai, India. Contact details and website links are provided for more information.
Java GUI Programming for beginners-graphics.pdfPBMaverick
This document provides an overview of Java graphics and GUI programming using the Swing and AWT libraries. It discusses why GUIs are important to study, the key components and containers in the Swing/AWT hierarchy like JFrame and JPanel. It also covers graphics drawing, layout managers that position components, and event-driven programming. The document is intended as an introduction to working with Java GUIs and graphics.
This document discusses event-driven programming and graphical user interfaces (GUIs) using Swing/AWT in Java. It provides an overview of key GUI concepts like components, containers, layout managers, and events. It explains how to create basic GUI elements like frames and buttons. It also demonstrates how to write an event listener as a nested class to handle button click events and update the GUI in response.
The document discusses different layout managers in Java including FlowLayout, BorderLayout, and GridLayout. It also discusses using panels as containers. Specifically:
1) FlowLayout arranges components from left to right in the order they are added and wraps to the next line when no more space on current line.
2) BorderLayout divides the container into five regions (north, south, east, west, center) with different expansion behaviors.
3) GridLayout places components into an equal-sized grid with a fixed number of rows and columns.
4) Panels can be used as containers within frames to group and layout components, with different panels using different layouts and the panels arranged within the frame
The document discusses 4 common layout managers in AWT: FlowLayout, GridLayout, BorderLayout, and BoxLayout. It provides details on how each layout manager arranges and positions components within a container. Code examples are given to demonstrate implementing each layout manager. The document is intended to help students understand how to define and use layout managers to structure the UI design of an AWT application.
This document discusses graphical user interface (GUI) components in Java and layout managers. It provides descriptions of common GUI components like JLabel, JTextField, JButton, JCheckBox, and JComboBox. It then explains several layout managers - BorderLayout, CardLayout, FlowLayout, GridLayout, GridBagLayout, GroupLayout, and SpringLayout - and provides their class declarations.
The document discusses different layout managers in Java including BorderLayout, GridLayout, FlowLayout, BoxLayout, CardLayout, GridBagLayout, SpringLayout, and GroupLayout. It provides details on the constructors and commonly used methods of each layout manager, along with examples of how to use each one. Key information covered includes how each layout positions and sizes components within a container.
This document provides an overview of Java GUI libraries and Swing programming. It discusses key Swing components like JButton, JTextField, JLabel and how to add them to containers using layout managers. It also covers more advanced topics like JTable, JTree, event handling and creating custom Swing components. The document is a useful reference for learning how to build graphical user interfaces in Java using the Swing toolkit.
This document provides an overview of getting started with GUI programming in Java. It discusses creating frames as windows to contain other components. Common GUI components like labels, text fields, buttons and checkboxes are demonstrated. Layout managers like FlowLayout, GridLayout, and BorderLayout are explained for arranging components within containers. The use of panels as sub-containers is also covered. Finally, basic concepts of events, adding event listeners, and getting/setting text in components are introduced.
Swing is a Java GUI widget toolkit that improves upon the older AWT toolkit. It includes common GUI components like JFrame, JPanel, and JLabel. JFrame represents a window, JPanel is used to group and layout components, and JLabel displays text. These components have constructors and methods to create, configure, add, and listen to GUI elements. Layout managers automatically position components and should be used for most applications.
Graphical User Interface (GUI) in Java uses classes from the javax.swing and java.awt packages to implement GUI programs. Swing classes provide greater compatibility across operating systems compared to AWT classes. Common Swing components include JButton, JLabel, JTextField, JTextArea, JCheckBox, JRadioButton, JComboBox, JList, JSlider and more. GUI programs require containers like JFrame and JPanel to hold components. Layout managers determine how components are arranged in containers. Common layouts include FlowLayout, BorderLayout and GridLayout. Menus are implemented using JMenuBar, JMenu and JMenuItem classes.
This document discusses layout managers in AWT. It describes four common layout managers: FlowLayout, which arranges components horizontally from left to right; GridLayout, which divides a container into a grid of equal rows and columns; BorderLayout, which divides a container into five regions (north, south, east, west, center); and BoxLayout, which arranges components vertically or horizontally within a container. It provides code examples of using each layout manager.
This document discusses various layout managers in Java for arranging components in windows. It describes common layout managers like FlowLayout, BorderLayout, GridLayout, CardLayout, and GridBagLayout. It provides examples of how to use each layout manager and explains strategies for using multiple layout managers together to achieve complex component arrangements. The document also discusses manually positioning components by disabling the layout manager.
This document discusses various AWT components in Java including:
1. Canvas - A lightweight component for drawing that does not use a layout manager.
2. Panel - A container that uses FlowLayout by default to organize child components.
3. Frame - A top-level window with a title bar, border, and menu bar that uses BorderLayout by default.
4. Components like Button, Checkbox and other basic controls are also discussed. Event handling, serialization, and best practices for adding components to containers are covered.
This document discusses graphical user interfaces in Java. It covers using layout managers like BorderLayout and GridLayout to position components in containers. Common components like text fields, text areas, radio buttons, check boxes, and menus are described. Handling user input through action listeners is also covered. The document provides examples of creating a GUI with menus to change the font style of sample text.
The document discusses various Java layout managers including FlowLayout, BorderLayout, CardLayout, GridLayout, and GridBagLayout. It provides details on their constructors, methods, and usage. FlowLayout is the default layout that arranges components from left to right, top to bottom. BorderLayout divides a container into five regions. CardLayout switches between panels like cards. GridLayout evenly divides space into a grid of rows and columns. GridBagLayout is more flexible than GridLayout and allows control of component size and position with GridBagConstraints.
AWT (Abstract Window Toolkit) is a collection of classes and methods that allows creation and management of windows. It provides support for applets and contains support for window-based graphical user interfaces. Different window classes defined by AWT add functionality, with Component and Container being the base classes. Layout managers determine how components are arranged in frames using algorithms. Common layout managers include FlowLayout, BorderLayout, and GridLayout. Graphics methods allow for drawing shapes and text to windows.
This document provides an overview of the AWT and Swing toolkits in Java for building graphical user interfaces (GUIs). It describes the key classes in AWT like Component, Container, and Window. It also discusses limitations of AWT and how Swing addresses these by providing more versatile components that are rendered independently of the underlying platform. The document gives examples of common Swing components like buttons, text fields, lists, and how to add listeners and handle events.
This document provides an overview of the Abstract Windowing Toolkit (AWT) and Swing GUI frameworks in Java. It discusses the similarities and differences between AWT and Swing, the fundamental AWT components like frames and panels, graphics drawing, additional AWT components, common layout managers, and how to set up top-level containers and examples using Swing components like JFrames and JOptionPanes. The key topics covered include the fundamentals of building graphical user interfaces in Java.
The document discusses Java GUI components from the Abstract Window Toolkit (AWT) and Swing toolkit. It defines AWT as a set of APIs used to create GUI objects like buttons and windows. It describes common AWT containers like Frame, Panel, Dialog and Applet. It then introduces Swing as an enhanced GUI toolkit and lists some common Swing components in packages like javax.swing. The document provides examples of creating and using common Swing components like JFrame, JLabel, JButton, JCheckBox.
The document discusses Java GUI components from the Abstract Window Toolkit (AWT) and Swing toolkit. It defines AWT as a set of APIs used to create GUI objects like buttons and windows. It describes common AWT containers like Frame, Panel, Dialog and Applet. It then introduces Swing as an enhanced GUI toolkit and lists some common Swing components in packages like javax.swing. The document provides examples of creating and using common Swing components like JFrame, JLabel, JButton, JCheckBox.
This document provides an overview of connecting to and interacting with databases using JDBC. It begins with database basics, explaining concepts like tables, records, queries, and SQL. It then covers connecting to a database with JDBC, including registering drivers and obtaining a connection. Finally, it discusses querying and manipulating databases with JDBC through executing SQL statements and processing result sets. Examples are provided to demonstrate selecting, updating, and inserting data into databases using JDBC.
This document provides an overview of networking concepts in Java including:
1) It outlines topics on networking basics like IP addresses, ports, protocols and client-server interactions.
2) It describes how to write networking clients and servers using sockets.
3) It provides an example of writing a simple ICQ client-server application to demonstrate sockets.
4) It discusses communicating with web servers by retrieving and sending information using URLs and URLConnections.
This document provides an introduction to multithreading concepts. It discusses using multiple threads to allow a bouncing ball animation program to start new balls even while others are still bouncing. It covers the basics of creating and running threads, including defining a runnable class and starting new threads. It also discusses key threading issues like thread states, scheduling, synchronization, and suspending/stopping threads.
This document provides an overview of applets, including:
- Applets are Java programs that run within web browsers. Examples include interactive scientific visualizations and real-time satellite trackers.
- Applets have a lifecycle controlled by the browser via init(), start(), stop(), and destroy() methods. They are also subject to security restrictions since they are downloaded from the web.
- Resources like images, audio, and text files can be accessed from the home server hosting the applet. Communication between the applet and browser is also possible using the AppletContext interface.
1) The document discusses the basics of GUI programming using Swing in Java, including creating frames, panels, and displaying text, shapes, colors, fonts, and images.
2) It explains how to create a JFrame window, add JPanels, and override the paintComponent method in custom JPanel classes to draw desired graphics.
3) Specific examples are provided for displaying text by drawing strings, using different fonts, colors, and measuring text widths using FontMetrics.
This document discusses exceptions in Java. It covers Java exception classes like Error, RuntimeException, IOException which are unchecked and checked exceptions. It explains how to deal with exceptions by throwing exceptions from methods using throws and catching exceptions using try-catch blocks. Finally, it discusses concepts like multiple catch blocks, finally clause, and exception handling mechanism in Java.
This document provides an overview of input and output (I/O) in Java, including reading and writing local files. It discusses Java streams for reading input and writing output, and the classes for character-based and byte-based streams. The document outlines connecting to files, reading and writing characters and objects to files, and file management tasks like creating directories and deleting files.
This document provides an overview of inheritance in Java. It begins with an introduction to inheritance concepts like superclass, subclass, overriding methods, and polymorphism. It then covers deriving a subclass, including subclass fields, constructors, and methods. It discusses using subclasses and notes on this, super, and protected access. It concludes with special class types like abstract classes, which can contain abstract methods, and final classes/methods, which cannot be overridden.
Classes and objects are the main building blocks in object-oriented programming. A class acts as a blueprint that defines the attributes and behaviors of objects. It contains fields to represent an object's state, methods to represent its behaviors, and constructors to initialize new objects. Methods can be used to encapsulate an object's state through getter and setter accessors. Classes allow for code reuse through inheritance and polymorphism. Packages are used to organize related classes and avoid naming collisions.
This document provides an overview of advanced programming techniques in Java. It begins by comparing Java to C and C++, noting how Java simplified aspects of these languages while adding object-oriented features. It then outlines several advantages of Java, such as its simplicity, object-oriented design, platform independence, and robustness. The document also discusses Java's extensive standard libraries, known as packages, and how they provide powerful functionality and handle platform-specific details. It notes that Java is well-suited for networked and distributed applications, especially on the internet, due to its portability, multithreading, and networking capabilities. The course will cover fundamental Java concepts like classes, objects, inheritance and exceptions, as well as components, mult
This presentation was provided by Steph Pollock of The American Psychological Association’s Journals Program, and Damita Snow, of The American Society of Civil Engineers (ASCE), for the initial session of NISO's 2024 Training Series "DEIA in the Scholarly Landscape." Session One: 'Setting Expectations: a DEIA Primer,' was held June 6, 2024.
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPRAHUL
This Dissertation explores the particular circumstances of Mirzapur, a region located in the
core of India. Mirzapur, with its varied terrains and abundant biodiversity, offers an optimal
environment for investigating the changes in vegetation cover dynamics. Our study utilizes
advanced technologies such as GIS (Geographic Information Systems) and Remote sensing to
analyze the transformations that have taken place over the course of a decade.
The complex relationship between human activities and the environment has been the focus
of extensive research and worry. As the global community grapples with swift urbanization,
population expansion, and economic progress, the effects on natural ecosystems are becoming
more evident. A crucial element of this impact is the alteration of vegetation cover, which plays a
significant role in maintaining the ecological equilibrium of our planet.Land serves as the foundation for all human activities and provides the necessary materials for
these activities. As the most crucial natural resource, its utilization by humans results in different
'Land uses,' which are determined by both human activities and the physical characteristics of the
land.
The utilization of land is impacted by human needs and environmental factors. In countries
like India, rapid population growth and the emphasis on extensive resource exploitation can lead
to significant land degradation, adversely affecting the region's land cover.
Therefore, human intervention has significantly influenced land use patterns over many
centuries, evolving its structure over time and space. In the present era, these changes have
accelerated due to factors such as agriculture and urbanization. Information regarding land use and
cover is essential for various planning and management tasks related to the Earth's surface,
providing crucial environmental data for scientific, resource management, policy purposes, and
diverse human activities.
Accurate understanding of land use and cover is imperative for the development planning
of any area. Consequently, a wide range of professionals, including earth system scientists, land
and water managers, and urban planners, are interested in obtaining data on land use and cover
changes, conversion trends, and other related patterns. The spatial dimensions of land use and
cover support policymakers and scientists in making well-informed decisions, as alterations in
these patterns indicate shifts in economic and social conditions. Monitoring such changes with the
help of Advanced technologies like Remote Sensing and Geographic Information Systems is
crucial for coordinated efforts across different administrative levels. Advanced technologies like
Remote Sensing and Geographic Information Systems
9
Changes in vegetation cover refer to variations in the distribution, composition, and overall
structure of plant communities across different temporal and spatial scales. These changes can
occur natural.
Strategies for Effective Upskilling is a presentation by Chinwendu Peace in a Your Skill Boost Masterclass organisation by the Excellence Foundation for South Sudan on 08th and 09th June 2024 from 1 PM to 3 PM on each day.
The simplified electron and muon model, Oscillating Spacetime: The Foundation...RitikBhardwaj56
Discover the Simplified Electron and Muon Model: A New Wave-Based Approach to Understanding Particles delves into a groundbreaking theory that presents electrons and muons as rotating soliton waves within oscillating spacetime. Geared towards students, researchers, and science buffs, this book breaks down complex ideas into simple explanations. It covers topics such as electron waves, temporal dynamics, and the implications of this model on particle physics. With clear illustrations and easy-to-follow explanations, readers will gain a new outlook on the universe's fundamental nature.
A review of the growth of the Israel Genealogy Research Association Database Collection for the last 12 months. Our collection is now passed the 3 million mark and still growing. See which archives have contributed the most. See the different types of records we have, and which years have had records added. You can also see what we have for the future.
Main Java[All of the Base Concepts}.docxadhitya5119
This is part 1 of my Java Learning Journey. This Contains Custom methods, classes, constructors, packages, multithreading , try- catch block, finally block and more.
বাংলাদেশের অর্থনৈতিক সমীক্ষা ২০২৪ [Bangladesh Economic Review 2024 Bangla.pdf] কম্পিউটার , ট্যাব ও স্মার্ট ফোন ভার্সন সহ সম্পূর্ণ বাংলা ই-বুক বা pdf বই " সুচিপত্র ...বুকমার্ক মেনু 🔖 ও হাইপার লিংক মেনু 📝👆 যুক্ত ..
আমাদের সবার জন্য খুব খুব গুরুত্বপূর্ণ একটি বই ..বিসিএস, ব্যাংক, ইউনিভার্সিটি ভর্তি ও যে কোন প্রতিযোগিতা মূলক পরীক্ষার জন্য এর খুব ইম্পরট্যান্ট একটি বিষয় ...তাছাড়া বাংলাদেশের সাম্প্রতিক যে কোন ডাটা বা তথ্য এই বইতে পাবেন ...
তাই একজন নাগরিক হিসাবে এই তথ্য গুলো আপনার জানা প্রয়োজন ...।
বিসিএস ও ব্যাংক এর লিখিত পরীক্ষা ...+এছাড়া মাধ্যমিক ও উচ্চমাধ্যমিকের স্টুডেন্টদের জন্য অনেক কাজে আসবে ...
2. Objective and Outline
• Objective:
– What else do you need to know in order to create a
full-featured GUI?
• Outline:
– Overview of Swing components
– Layout management
– Using Swing components
• Text input, Buttons, ComboBox, Menus, Dialogs
3. Overview of Swing Components
http://java.sun.com/docs/books/tutorial/uiswing/components/components.html
Top-Level Containers
Windows: JFrame class
Dialog boxes: JOptionPane,JDialog *,
JFileChooser classes
Applets: JApplet * class
v2: covered in volume 2, *: will discuss
4. Overview of Swing Components
General-Purpose containers for laying out components.
JPanel class
JScrollPane * class provides a
scrollable view of components.
JSplitPane v2 displays two groups of
components, either side by side or
one on top of the other.
5. Overview of Swing Components
Basic control: Components for getting user input
Textfields: JTextField *,
JPasswordField *, JTextArea *
Buttons: JButton *, JCheckBox *,
JRadioButton *, …
6. Overview of Swing Components
Basic control: Components for getting user input
JMenu *, JMenuItem *
JSlider v2, JScrollbar
JComboBox *
JSpinner
7. Overview of Swing Components
non-editable components for information display
Jlabel * class can display
non-selectable text and images.
JProgressBar v2 class displays
progress of a job.
Tool Tips v2: created using JComponent
8. Overview of Swing Components
Editable components for information display
JTable v2 class can display and edit
tables of data,
Texts *:
JTree v2 class can display
hierarchical data
File Chooser
JColorChooser class to provide users
with a palette of colors to choose from.
11. Layout Management
Layout management determines the size and
position of components.
Each container has a default layout manager.
Can be changed using the method: setLayout
Generally, need to set the layout manager of two
types of containers:
content panes (which use BorderLayout by
default) and
JPanels (which use FlowLayout by default).
13. Layout Management
• Component size
– Default/natural minimum/preferred sizes
calculated by the LayoutManager interface, which
is implemented by all layout management classes
• Dimension minimumLayoutSize(Container parent)
• Dimension preferredLayoutSize(Container parent)
– Can be changed using methods of JComponent
• voidsetMaximumSize(Dimension maximumSize)
• voidsetMinimumSize(Dimension minimumSize)
• voidsetPreferredSize(Dimension preferredSize)
14. Flow Layout
FlowLayout class
FlowLayout arranges components in a left-to-right flow, much like
lines of text in a paragraph.
Components sized at their preferred size.
If the horizontal space in the container is too small,
FlowLayout uses multiple rows.
Within each row, components are centered (the default), left-
aligned, or right-aligned as specified when the FlowLayout is
created.
Default layout manager of JPanel : typically used to arrange buttons
in a panel
16. FlowLayout class constructors:
FlowLayout( int align, int hgap, int
vgap)
1. align: FlowLayout.LEFT,
FlowLayout.CENTER, FlowLayout.RIGHT
2. hgap: horizontal gap in pixels between components
3. vgap: vertical gap in pixels between components
FlowLayout( int align)
FlowLayout( )
Flow Layout
17. Border Layout
• BorderLayout:
– Has five areas
• Specify area for a component using one of the constants: NORTH, SOUTH,
EAST, WEST, and CENTER.
– Size of components determined by
• Their preferred sizes and the constraints of the container's size.
• The NORTH and SOUTH components may be stretched horizontally; the
EAST and WEST components may be stretched vertically; the CENTER
component may stretch both horizontally and vertically to fill any space
left over.
– Default for contentPane
19. BorderLayout class constructors:
BorderLayout( int hgap, int vgap)
1. hgap: horizontal gap in pixels between
components
2. vgap: vertical gap in pixels between components
BorderLayout( )
Border Layout
20. Grid Layout
GridLayout: places components in a grid of cells.
Each component takes all the available space within
its cell. Each cell is exactly the same size.
Number of columns ignored when number of rows
set to non-zero
Example:
21. Container contentPane = getContentPane();
contentPane.setLayout(new GridLayout(0,2));
//construct an instance of GridLayout that has two
// columns and as many rows as necessary.
contentPane.add(new JButton("Button 1"));
contentPane.add(new JButton("2"));
contentPane.add(new JButton("Button 3"));
contentPane.add(new JButton("Long-Named Button 4"));
contentPane.add(new JButton("Button 5"));
// GridWindow.java
22. GridLayout class constructors:
GridLayout(int rows, int columns,
int hgap, int vgap)
1. hgap: horizontal gap in pixels between
components
2. vgap: vertical gap in pixels between components
GridLayout(int rows, int columns )
Grid Layout
23. Box Layout
• BoxLayout: places components in a single row or column
– Attempt to arrange components at their preferred widths (for
horizontal layout) or heights (for vertical layout).
• For a horizontal layout, if not all the components are the same height,
BoxLayout attempts to make all the components as high as the highest
component.
• For a vertical layout, BoxLayout attempts to make all components in the
column as wide as the widest component. If that fails, it aligns them
horizontally according to their X alignments.
24. Box Layout
• Instead of using BoxLayout directly, many programs use the
Box class.
• The Box class is a lightweight container that uses a BoxLayout.
• It also provides handy methods to help you use BoxLayout
well.
• Adding components to multiple nested boxes is a powerful
way to get the arrangement you want.
25. Box class methods: all static
Factory methods:
createHorizontalBox(),
createVerticalBox()
If all the components your Box contains have a fixed size, you
might want to use a glue component to control the components'
positions.
createHorizontalGlue(),
createVerticalGlue,
createGlue():
//push components as far away as possible
Box Layout
26. For a fixed amount of space between two components,
try using a strut & rigid area
createHorizontalStrut(int),
createVecticalStrut(int)
createRigidArea( Dimension )
//BoxLayoutTest.java
Box Layout
27. // construct the top horizontal box
JLabel label1 = new JLabel("Name:");
JTextField textField1 = new JTextField(10);
textField1.setMaximumSize(textField1.getPreferredSize());
Box hbox1 = Box.createHorizontalBox();
hbox1.add(label1);
// separate with a 10-pixel strut
hbox1.add(Box.createHorizontalStrut(10));
hbox1.add(textField1);
// construct the middle horizontal box
JLabel label2 = new JLabel("Password:");
JTextField textField2 = new JTextField(10);
textField2.setMaximumSize(textField2.getPreferredSize());
Box hbox2 = Box.createHorizontalBox();
hbox2.add(label2);
// separate with a 10-pixel strut
hbox2.add(Box.createHorizontalStrut(10));
hbox2.add(textField2);
28. // construct the bottom horizontal box
JButton button1 = new JButton("Ok");
JButton button2 = new JButton("Cancel");
Box hbox3 = Box.createHorizontalBox();
hbox3.add(button1);
// use "glue" to push the two buttons apart
hbox3.add(Box.createGlue());
hbox3.add(button2);
// add the three horizontal boxes inside a vertical box
Box vbox = Box.createVerticalBox();
vbox.add(hbox1);
vbox.add(hbox2);
vbox.add(Box.createGlue());
vbox.add(hbox3);
Container contentPane = getContentPane();
contentPane.add(vbox, BorderLayout.CENTER);
29. GridBag Layout
GridBagLayout:
The most sophisticated, flexible layout manager the Java platform
provides.
It aligns components by placing them within a grid of cells, allowing
some components to span more than one cell.
The rows in the grid aren't necessarily all the same height;
similarly, grid columns can have different widths.
30. Layout Management
Hierarchy of containers for achieving better layout:
Containers inside other containers
Each has a potentially a different layout manager
Allows you to create sophisticated layout with simple
layout managers
//CombineTest.java
31. // create vertical box
Box b = Box.createVerticalBox();
// create top panel (FlowLayout)
JPanel p1 = new JPanel();
p1.add( new JButton("Button 1"));
p1.add( new JButton("2"));
p1.add( new JButton("Button 3"));
b.add(p1);
// create Scrollable text area
JTextArea t = new JTextArea(200, 50);
JScrollPane sp = new JScrollPane( t );
b.add(sp);
// create bottom panel (right-aligned FlowLayout)
JPanel p2 = new JPanel();
p2.setLayout( new FlowLayout( FlowLayout.RIGHT ));
p2.add( new JButton("OK"));
b.add( p2 );
Container cp = getContentPane();
cp.add( b ); //CombineTest.java
32. Borders for Components
JComponents can have borders
Create Border objects using static methods of
BorderFactory class:
createLineBorder, createMatteBorder,
createEmptyBorder createEtchedBorder, ….
Set border using the setBorder method of Jcomponent
Example: BorderTest.java
This example also demonstrate the use of
JRadioButton, which will be discussed later
33. public BorderFrame()
{
setTitle("BorderTest");
setSize(WIDTH, HEIGHT);
demoPanel = new JPanel();
buttonPanel = new JPanel();
group = new ButtonGroup();
addRadioButton("Lowered bevel",
BorderFactory.createLoweredBevelBorder());
addRadioButton("Raised bevel",
BorderFactory.createRaisedBevelBorder());
addRadioButton("Etched",
BorderFactory.createEtchedBorder());
addRadioButton("Line",
BorderFactory.createLineBorder(Color.blue));
addRadioButton("Matte",
BorderFactory.createMatteBorder(
10, 10, 10, 10, Color.blue));
addRadioButton("Empty",
BorderFactory.createEmptyBorder());
37. Text Input
JTextField, JPasswordField: one line.
JTextArea: A multi-line area that displays plain
text.
JEditorPane: A text component to edit various kinds
of content, plain text, html, rtf.
Can be monitored using either CaretListener or
DocumentListener
Check Documentation of JTextComponent
38. • JTextField also produces ActionEvent
when ”return” is pressed.
• Let’s make use of this to write a program:
Text1.java.
• Next, show how to make it better using
DocumentListener (Text.java)
Text Input
40. Model-View-Controller Design Pattern
• Model
– represents the state and low-level behavior of the component.
– manages the state and conducts all transformations on that state.
– system itself maintains links between model and views and notifies
the views when the model changes state.
– Example: ButtonModel
• Query internal state
• Manipulate internal state
• Add and remove event listeners
• Fire events
41. Model-View-Controller Design Pattern
• view:
– manages the visual display of the state represented by the model.
• controller
– manages user interaction with the model. It provides the mechanism
by which changes are made to the state of the model.
• Example: ButtonUI
– Paint
– Return geometric information
– Handle AWT events
42. Model-View-Controller Design Pattern
• The component class JButton acts as the glue, or scaffolding, that holds the MVC
triad together
• Programmers do not typically work with model and view/controller classes
directly
• Example about what you can do using MVC:
http://www.developer.com/java/ent/article.php/3336761
43. Text Input
Model for all text components, including TextField, JPasswordField,
JTextArea are described by Document Interface.
Text component generates DocumentEvents when its content is changed.
To listen to such events, register a DocumentListener with the text
component
textComponent.getDocument()
.addDocumentListener(listener);
Check Documentation of JTextComponent
44. Text Input
The DocumentListener has three methods
void insertUpdate(DocumentEvent e)
void removeUpdate(DocumentEvent e)
void changeUpdate(DocumentEvent e)
// Gives notification that an attribute or set of attributes
changed.
No adapter class.
45. class TextTestFrame extends JFrame
{ public TextTestFrame()
{ setTitle("TextTest");
setSize(WIDTH, HEIGHT);
Container contentPane = getContentPane();
DocumentListener listener =
new ClockFieldListener();
// add a panel with text fields
JPanel panel = new JPanel();
hourField = new JTextField("12", 3);
panel.add(hourField);
hourField.getDocument().addDocumentListener(listener);
minuteField = new JTextField("00", 3);
panel.add(minuteField);
minuteField.getDocument().addDocumentListener(listener);
contentPane.add(panel, BorderLayout.SOUTH);
// add the clock
clock = new ClockPanel();
contentPane.add(clock, BorderLayout.CENTER);
} //TextTest.java.
46. Text Input/JTextField
private class ClockFieldListener implements
DocumentListener
{
public void insertUpdate(DocumentEvent e)
{ setClock(); }
public void removeUpdate(DocumentEvent e)
{ setClock(); }
public void changedUpdate(DocumentEvent e) {}
}
}
47. Text Input/JTextField
class TextTestFrame extends JFrame
{ public TextTestFrame()
{ …}
public void setClock() // retrieving from both fields
{ int hours =
Integer.parseInt(hourField.getText().trim());
int minutes =
Integer.parseInt(minuteField.getText().trim());
clock.setTime(hours, minutes);
}
……
}
Will change clock without pressing “Return”
50. Buttons
All button classes descend from AbstractButton
JButton: A common button.
JCheckBox: For “yes” or “no” input.
JRadioButton: For exclusive choices among a
group. If one button is pushed, all other buttons in the
group depressed.
51. JCheckBox
Use a check box to collect yes/no input. The user checks/ the box by
clicking inside it and turns off the check mark by clinking it again.
Check boxes need a label next to them to identify their purpose.
Bold = new JCheckBox(“Bold”);
Use the setSelected method to turn a check box on or off
Bold.setSelected(true);
The isSelected method then retrieves the current state of each check
box. It is false if unchecked; true if checked.
When the user clicks on a check box, an action event is triggered. As
always, you attach an action listener.
ActionListener listener = …
Bold.addActionListener(listener)
52. class CheckBoxFrame extends JFrame
{ public CheckBoxFrame()
{ ……
ActionListener listener = new ActionListener()
{ public void actionPerformed(Actionevent event)
{ int mode = 0;
if (bold.isSelected()) mode +=Font.BOLD;
if (italic.isSelected()) mode +=Font.ITALIC;
label.setFont(new Font(“Serif”, mode, FONTSIZE));
}
}
JPanel buttonPanel = new JPanel();
bold = new JCheckBox( "Bold");
bold.addActionListener(listener);
buttonPanel.add(bold);
italic = new JCheckBox("Italic");
italic.addActionListener(listener);
buttonPanel.add(italic);
getContentPane().add(buttonPanel, BorderLayout.South);
…} // CheckBoxTest.java
53. Buttons/Radio Buttons
Radio buttons group are groups of buttons in which
only one button at a time can be selected.
The Swing release supports radio buttons with the
JRadioButton and ButtonGroup classes
Example: Choosing pets
(RadioButtonDemo.java)
54. // Create the radio buttons.
JRadioButton birdButton = new JRadioButton(birdString);
birdButton.setMnemonic('b'); // Enable ALT+b
// this is to be used together with getActionCommand
birdButton.setActionCommand(birdString);
birdButton.setSelected(true); // birButton selected
JRadioButton catButton = new JRadioButton(catString);
catButton.setMnemonic('c');
catButton.setActionCommand(catString);
// Note catButton not selected
// dogButton, RabbitButton, PigButton
55. // Group the radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(birdButton);
group.add(catButton);
group.add(dogButton);
group.add(rabbitButton);
group.add(pigButton);
// now one of those buttons can be selected
56. // Register a listener for the radio buttons.
RadioListener myListener = new RadioListener();
birdButton.addActionListener(myListener);
catButton.addActionListener(myListener);
...
class RadioListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
picture.setIcon(new ImageIcon("images/“
+ e.getActionCommand()
+ ".gif"));
}
Get this string set by
setActionCommand
images/cat.gif
images/bird.gif
…
58. JComboBox
A JComboBox looks like a text field with an
arrow next to it. If you click on the arrow,
the list of possible values is displayed.
If the Jcombobox is set to be editable, then
you can edit the current selection as if it
was a text field.
Only one item can be selected at a time.
You can retrieve it by calling:
getSelectedItem method.
Add the choice items to the end of the list
with the addItem method.
59. JComboBox
Insert new items anywhere in the list with the insertItemAt :
faceCombo.insertItemAt(“Monospaced”, 0) //add at head
Remove items at run time by using removeItem or removeItemAt
faceCombo.removeItem(“Monospaced”);
faceCombo.removeItemAt(0); // remove first item
or
removeAllItems to remove all items at once
When an item is selected, the combo box generates an ActionEvent.
Call getSource on the event to get a reference to the combo box that
sent the event. Then call getSelectedItem to retrieve the selected
item.
//see ComboBoxTest.java
60. class ComboBoxFrame extends JFrame
{
public ComboBoxFrame()
{ setTitle("ComboBoxTest");
setSize(WIDTH, HEIGHT);
Container contentPane =
getContentPane();
// add the sample text label
label = new JLabel(
"The quick brown fox jumps over the lazy dog.");
label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
contentPane.add(label, BorderLayout.CENTER);
// make a combo box and add face names
faceCombo = new JComboBox();
faceCombo.setEditable(true);
faceCombo.addItem("Serif");
faceCombo.addItem("SansSerif");
faceCombo.addItem("Monospaced");
faceCombo.addItem("Dialog");
faceCombo.addItem("DialogInput");
61. // the combo box listener changes the label font to the
// selected face name
faceCombo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
label.setFont(new Font(
(String)faceCombo.getSelectedItem(),
Font.PLAIN, DEFAULT_SIZE));
}
});
//add combo box to a panel at the frame's souther
JPanel comboPanel = new JPanel();
comboPanel.add(faceCombo);
contentPane.add(comboPanel, BorderLayout.SOUTH);
}
63. Menus
Inheritance hierarchy of menu-related classes.
A menu bar contains one or more menus, placed onto a
frame.
A menu contains one or more menu items, which can be
menus themselves.
64. Menus/Creating Menus
1. Create JMenus
2. Create JmenuItems and associate
Actions with them
3. Add those JmenuItems to the Jmenu
4. When user selects a JmenuItem , an
Action is triggered.
5. Create a JMenuBar and place it onto a
frame
6. Add the JMenus to the JMenuBar
65. public class MenuTest extends JFrame …
{ public MenuTest()
{ …
JMenu fileMenu = new JMenu("File");
JMenuItem newItem = fileMenu.add(new TestAction("New"));
JMenuItem openItem = fileMenu.add(new TestAction(“Open”));
JMenuItem saveItem = fileMenu.add(new TestAction("Save"));
JMenuItem saveAsItem =fileMenu.add(new TestAction("Save As"));
….
JMenuBar mbar = new JMenuBar();
setJMenuBar(mbar); // add menu bar to the frame
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(helpMenu);
….
}
//MenuTest.java
66. Menus/Mnemonics and Accelerators
Keyboard Mnemonics are set by using setMnemonic
method
fileMenu.setMnemonic('F');
openItem.setMnemonic('O');
Accelerators are keyboard shortcuts (CTR+S, CTR+O)
openItem.setAccelerator
(KeyStroke.getKeyStroke(KeyEvent.VK_O,
InputEvent.CTRL_MASK));
saveItem.setAccelerator
(KeyStroke.getKeyStroke(KeyEvent.VK_S,
InputEvent.CTRL_MASK));
67. Menus/Menu Item Events
When user selects a menu item, an Action is triggered.
class TestAction extends AbstractAction
{
public TestAction(String name){super(name);}
public void actionPerformed(ActionEvent event)
{
System.out.println(getValue(Action.NAME) +
“ selected.”);
}
}
68. Menus/Menu Events
When user selects a menu, an MenuEvent is triggered.
MenuListener interface has three method
void menuSelected(MenuEvent )
// called before display menu
void menuDeselected(MenuEvent )
void menuCanceled(MenuEvent )
// called before menu selection is canceled, e.g.
// by clicking outside menu
69. Menus/Enable & Disabling Menu Items
Do this with setEnabled method.
saveItem.setEnabled( false);
saveAsItem.setEnabled( true );
Good time to enable and disable menu items: right before displaying, i.e.
within MenuListener
private class FileMenuListener implements MenuListener
{ …
public void menuSelected(MenuEvent evt)
{ saveItem.setEnabled(!readonlyItem.isSelected());
saveAsItem.setEnabled(!readonlyItem.isSelected());
}
This enables or disables saveItem and saveAsItem depending on
whether readonlyItem is selected.
70. Menus
Can have submenus, menu within menu. Inheritance
hierarchy of menu-related classes.
Can have check boxes, radio buttons as menu items
(JCheckBoxItem, JRadioButtonItem)
Can have popup menus.
MenuTest.java
72. Dialogs
Classes for specific dialogs
ProgressMonitor
JColorChooser
JFilerChooser
Class for standard dialogs
JOptionPane
Class for custom dialogs
JDialog
73. Dialogs
Every dialog box is a dependant of a parentComponent (frame).
parentComponent determines location of dialog box.
When that parentComponent is destroyed, so are its dependent
dialogs.
modal dialog box, when visible, blocks user input to all other windows
in the program. The dialogs that JOptionPane provides are modal.
A modeless dialog box lets the user enter information in both the
dialog box and the remainder of the application.
To create a modeless dialog, you must use the JDialog class
directly.
JDialog is a subclass of the AWT java.awt.Dialog
Using JDialog directly is very similar to using JFrame directly.
74. Option Dialogs
Commonly used methods of
JOptionPane
ShowMessageDialog
Show a message and wait for user
to click OK
ShowConfirmDialog
Show a message and get a
confirmation(Yes/No/Cancel)
ShowOptionDialog
Show a message and get a user
option from a set of options.
ShowInputDialog
Show a message and get one line
of user input.
//show DialogTest.java
75. Option Dialogs
Every Dialog has: an icon, a message , one or more option buttons.
icon type: ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE,
QUESTION_MESSAGE, PLAIN_MESSAGE
Message can be:
A String: Draw the string
Icon: Show the icon
Component: Show the component
Object[]: Show all objects in the array, stacked on top of each other.
Option buttons are:
DEFAULT_OPTION
YES_NO_OPTION
YES_NO_CANCEL_OPTION
OK_CANCEL_OPTION
Return value: An integer representing the chosen option
or a string that the user supplied or selected
76. Step to Create Option Dialogs
1. Choose the dialog type (message, confirmation, option or input),
2. Choose the icon(error, information, warning, question, none or custom).
3. Choose the message (string, icon, custom component, or a stack of
them).
4. For a confirmation dialog, choose the option type (default, yes/No,
Yes/No/Cancel, or OK/Cancel).
5. For an option dialog, choose the options (strings, icons, or custom
components ) and the default option.
6. For an input dialog, choose between a text field and a combo box.
7. Locate the appropriate method to call in the JOptionPane API.
77. Creating Dialogs
You can also create a dialog box by deriving a class from JDialog:
1. In the constructor of your dialog box, call the constructor of the base class
JDialog. You will need to tell it the owner frame (the frame window over
which the dialog pops up), the title of the dialog frame, and a Boolean flag to
indicate if the dialog box is modal or modeless.
2. Add the user interface components to the dialog box.
3. Add the event handlers.
4. Set the size for the dialog box.
//DialogTest.java
78. Data Exchange
The most common reason to put up a dialog box is to get information
from the user.
Your dialog box should provide methods to set default data:
public void setUser(User u)
{
username.setText(u.getName());
}
Then you can show the dialog such as the following:
boolean showDialog()
{
ok = false;
show();
return ok; //OK button sets the ok flag to true
}
79. Data Exchange
You should test the return value of the showDialog. If it is true, then
you can retrieve the user input by:
Public User getUser()
{
return new User (username.getText(),
password.getPassword());
}
80. private class ConnectAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
// if first time, construct dialog
if (dialog == null)
dialog = new PasswordChooser();
// set default values
dialog.setUser(new User("yourname", null));
// pop up dialog
if(dialog.showDialog(DataExchangeFrame.this, "Connect"))
{
// if accepted, retrieve user input
User u = dialog.getUser();
textArea.append(
"user name = " + u.getName() + ", password = "
+ (new String(u.getPassword())) + "n");
}
}
} //DataExchangeTest.java