This document provides an overview of applet components in Java, including labels, buttons, checkboxes, choice controls, lists, scroll bars, text fields, text areas, menus, and containers. It also covers layout managers like FlowLayout, GridLayout, and BorderLayout which position components within containers. Finally, it discusses event handling using the event delegation model where sources generate events that are handled by listener interfaces like ActionListener.
Composing an App with Free Monads (using Cats)Hermann Hueck
In this talk I will explain what Free Monads are and how to use them (using the Cats implementation).
After having shown the basics I build a small app by composing several
Free Monads to a small program.
I discuss the pros and cons of this technique.
Finally I will demonstrate how to avoid some boilerplate with the FreeK library.
The document discusses various AWT components like buttons, labels, checkboxes, text fields, lists, menus and canvases. It provides code examples to demonstrate how to use these components by extending Frame class and adding the components to the frame. It also discusses different layout managers like BorderLayout, FlowLayout, CardLayout and GridLayout and provides code samples to illustrate how to use each layout manager.
The document discusses building graphical user interfaces (GUIs) in Java. It covers the Abstract Window Toolkit (AWT) and Swing frameworks, which provide components for creating GUIs. It describes common layout managers like FlowLayout, BorderLayout, and GridLayout that control how components are arranged within containers. It also explains how to add behavior to components by attaching listener objects that respond to user events like button clicks or text changes.
Most Scala developers are familiar with monadic precessing. Monads provide flatMap and hence for-comprehensions (syntactic sugar for map and flatMap).
Often we don't need Monads. Applicatives are sufficient in many cases.
In this talk I examine the differences between monadic and applicative processing and give some guide lines when to use which.
After a closer look to the Applicative trait I will contrast the gist of Either and cats.data.Validated (the latter being an Applicative but not a Monad).
I will also look at traversing and sequencing which harness Applicatives as well.
The document contains 4 code snippets demonstrating different ways to take input in Java programs:
1) Using command line arguments and the args array to print a greeting with a passed in name
2) Swapping two integers entered from the keyboard using only two variables
3) Reading input from the keyboard using InputStreamReader and BufferedReader classes
4) Taking input using the Scanner class to read an integer, string, and double from console input
Different Ways of Function Composition in Scala:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Fine-grained composability of functions is one of the core advantages of FP.
Treating "Functions as Data" means that we can store, manipulate, pass functions around and compose them in much the same way we do with data.
This talk demonstrates different ways of function composition in Scala.
The focus lies on scala.Function1, because due to tupling and currying we can regard any FunctionN (except Function0) as a Function1. Curried functions are easier to compose.
Starting with the composition methods of scala.Function1: apply, compose and andThen, we will investigate folding a Seq of functions.
We can also define a pipe operator |> as in F# in order to 'pipe' values through a pipeline of functions.
Defining a Monoid for Function1 allows us to combine two or more functions into a new one.
A function can also be seen as a Functor and a Monad. That means: Functions can be mapped and flatMapped over. And we can write for-comprehensions in a Function1 context just as we do with List, Option, Future, Either etc.
Being Monads, we can use functions in any monadic context. We will see that Function1 is the Reader Monad.
The most powerful way of function composition is Kleisli (also known as ReaderT). We will see that Kleisli (defined with the Id context) is the Reader Monad again.
The document contains 14 code examples that demonstrate how to solve various math and logic problems in Java. The examples cover topics like:
- Calculating the area and perimeter of a rectangle by taking user input for length and width.
- Adding two numbers taken as user input.
- Finding the quotient and remainder of dividing one number by another from user input.
- Calculating IGST and sale price based on a value of sale.
- Finding the power of a number using user input for the number and exponent.
- Converting seconds to hours, minutes and seconds.
- Taking two numbers as input and outputting their sum and difference.
- Determining if a character entered is a vowel or
With my simple implementation I wanted to demonstrate the basic ideas of th IO Monad.
My impl of the IO Monad is just a feasibility study, not production code!
When coding my impl of IO I was very much inspired by cats.effect.IO and monix.eval.Task which I studied at that time. Both are implementions of the IO Monad.
The API of my IO is very similar to the basics of Monix Task. This IO implementation also helped me to understand the IO Monad (of cats-effect) and Monix Task.
Interop with Future is also supported. You can convert IO to a Future. Vice versa you can convert a Future to an IO.
The development of my impl can be followed step by step in the code files in package iomonad.
Composing an App with Free Monads (using Cats)Hermann Hueck
In this talk I will explain what Free Monads are and how to use them (using the Cats implementation).
After having shown the basics I build a small app by composing several
Free Monads to a small program.
I discuss the pros and cons of this technique.
Finally I will demonstrate how to avoid some boilerplate with the FreeK library.
The document discusses various AWT components like buttons, labels, checkboxes, text fields, lists, menus and canvases. It provides code examples to demonstrate how to use these components by extending Frame class and adding the components to the frame. It also discusses different layout managers like BorderLayout, FlowLayout, CardLayout and GridLayout and provides code samples to illustrate how to use each layout manager.
The document discusses building graphical user interfaces (GUIs) in Java. It covers the Abstract Window Toolkit (AWT) and Swing frameworks, which provide components for creating GUIs. It describes common layout managers like FlowLayout, BorderLayout, and GridLayout that control how components are arranged within containers. It also explains how to add behavior to components by attaching listener objects that respond to user events like button clicks or text changes.
Most Scala developers are familiar with monadic precessing. Monads provide flatMap and hence for-comprehensions (syntactic sugar for map and flatMap).
Often we don't need Monads. Applicatives are sufficient in many cases.
In this talk I examine the differences between monadic and applicative processing and give some guide lines when to use which.
After a closer look to the Applicative trait I will contrast the gist of Either and cats.data.Validated (the latter being an Applicative but not a Monad).
I will also look at traversing and sequencing which harness Applicatives as well.
The document contains 4 code snippets demonstrating different ways to take input in Java programs:
1) Using command line arguments and the args array to print a greeting with a passed in name
2) Swapping two integers entered from the keyboard using only two variables
3) Reading input from the keyboard using InputStreamReader and BufferedReader classes
4) Taking input using the Scanner class to read an integer, string, and double from console input
Different Ways of Function Composition in Scala:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Fine-grained composability of functions is one of the core advantages of FP.
Treating "Functions as Data" means that we can store, manipulate, pass functions around and compose them in much the same way we do with data.
This talk demonstrates different ways of function composition in Scala.
The focus lies on scala.Function1, because due to tupling and currying we can regard any FunctionN (except Function0) as a Function1. Curried functions are easier to compose.
Starting with the composition methods of scala.Function1: apply, compose and andThen, we will investigate folding a Seq of functions.
We can also define a pipe operator |> as in F# in order to 'pipe' values through a pipeline of functions.
Defining a Monoid for Function1 allows us to combine two or more functions into a new one.
A function can also be seen as a Functor and a Monad. That means: Functions can be mapped and flatMapped over. And we can write for-comprehensions in a Function1 context just as we do with List, Option, Future, Either etc.
Being Monads, we can use functions in any monadic context. We will see that Function1 is the Reader Monad.
The most powerful way of function composition is Kleisli (also known as ReaderT). We will see that Kleisli (defined with the Id context) is the Reader Monad again.
The document contains 14 code examples that demonstrate how to solve various math and logic problems in Java. The examples cover topics like:
- Calculating the area and perimeter of a rectangle by taking user input for length and width.
- Adding two numbers taken as user input.
- Finding the quotient and remainder of dividing one number by another from user input.
- Calculating IGST and sale price based on a value of sale.
- Finding the power of a number using user input for the number and exponent.
- Converting seconds to hours, minutes and seconds.
- Taking two numbers as input and outputting their sum and difference.
- Determining if a character entered is a vowel or
With my simple implementation I wanted to demonstrate the basic ideas of th IO Monad.
My impl of the IO Monad is just a feasibility study, not production code!
When coding my impl of IO I was very much inspired by cats.effect.IO and monix.eval.Task which I studied at that time. Both are implementions of the IO Monad.
The API of my IO is very similar to the basics of Monix Task. This IO implementation also helped me to understand the IO Monad (of cats-effect) and Monix Task.
Interop with Future is also supported. You can convert IO to a Future. Vice versa you can convert a Future to an IO.
The development of my impl can be followed step by step in the code files in package iomonad.
The document contains code snippets from 3 weekly coding assignments:
1) A Java program to check if a string is a palindrome. It compares characters at the beginning and end of the string.
2) A Java program to sort a list of names in ascending order using string comparison and swapping.
3) A Java program to count the frequency of words in a given text by tokenizing, sorting, and printing the words.
scala.concurrent.Future is familiar to nearly all Scala devs.
This presentation first talks about referential transparency and the IO Monad in general. (Monix Task is an impl of the IO Monad.)
Then it compares Future Monix 3.x Task with their Pros and Cons.
Interop with Future: As Scala's Future is used in many environments and libraries, we look at the conversion from Task to Future and - vice versa - from Future to Task.
I will also take a look at Task evaluation, cancelation and memoization as well as tail recursive loops and asynchronous boundaries.
The presentation will include a comparative discussion on ExecutionContext (required for Future) and Scheduler (required for Task, but only to run it).
Often recurring on the valuable Monix Task doumentation at https://monix.io/docs/3x/eval/task.html the presentation can also be seen as an introduction to Monix Task.
The document provides examples of Java code demonstrating various programming concepts like loops, conditional statements, methods, arrays and string manipulation. It includes code snippets to print "Hello World", check if a number is even or odd, print multiplication tables, convert temperatures between Fahrenheit and Celsius scales, take input from the user and perform basic operations on strings. The examples illustrate the use of various loops like for, while and do-while loops, if-else statements, methods and built-in string/array methods in Java.
The document discusses Java GUI building using AWT and Swing. It explains that AWT is the original toolkit for building GUIs in Java but that Swing provides more advanced and flexible components. It outlines the basic steps for building a GUI with a container, components, layout managers, and listeners to add interactivity. Key topics covered include common components, adding components to containers, using layout managers, and implementing listeners to handle user events.
Implementation details and performance traits of generics in .NET, Java and C++. Presentation for the Jerusalem .NET/C++ User Group by Sasha Goldshtein.
The document discusses generics in C#, explaining that generics allow defining type-safe data structures without committing to actual data types, improving performance and code quality. It covers why generics are required by discussing issues with non-generic stacks, and describes generic type parameters, constraints, methods, delegates and event handling using generics.
The document provides an overview of the Swift Foundation framework. It discusses key types in Foundation like AffineTransform, CharacterSet, Data, Date, DateComponents, Decimal, FileManager, IndexPath, Measurement, Notification, NSError, URL, and URLComponents. The document also briefly mentions the purpose of each type.
This document provides a manual for a Java and J2EE lab for 5th semester computer science students. It contains 15 programs covering topics like enums, annotations, collections, strings, servlets, and database connectivity. Each program is explained and the expected output is provided. The programs demonstrate core Java concepts and commonly used APIs for collections, strings, I/O, and database access.
The document provides code examples for several basic Java programs, including:
1) A program that compares two numbers and prints which is greater.
2) A program that takes a number as input and prints all even numbers between 1 and the input.
3) Programs that calculate the area and perimeter of shapes like circles and rectangles.
4) Programs that calculate the factorial of a number and construct a triangle shape using asterisks.
5) A program that finds and lists all leap years between two given years.
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.
The document contains code for a HomeAssignment class with methods to:
1) Display a square of asterisks of a given side size
2) Display a square of any character of a given side size
3) Calculate and display the factorial of a given number
4) Check if two strings are anagrams by sorting and comparing their characters.
The main method calls each method in turn to demonstrate its functionality.
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
This document discusses concurrency, scalability, and fault tolerance using actors and software transactional memory (STM) in Akka. It describes how actors provide message-passing concurrency by isolating processes and avoiding shared state. Actors allow easy reasoning about concurrency by preventing issues like race conditions and deadlocks. The document also covers how Akka implements actors, typed actors, remote actors, supervisor hierarchies for fault tolerance, and STM for coordinating concurrent changes to shared state transactionally. Combining actors with STM results in "transactors" that allow building distributed, concurrent, and fault-tolerant applications.
This document contains instructions for several Java programming exercises involving classes, packages, inheritance, overriding, exceptions, and threads. It outlines code for programs that demonstrate concepts like classes and objects, command line arguments, bitwise operators, method overriding, and packages. For each exercise, it provides the aim, algorithm, sample code, input/output, and result to verify the output. The exercises are intended to help students learn and practice core Java programming concepts.
Video and more content at fsharpforfunandprofit.com/pbt
"The lazy programmer's guide to writing 1000's of tests: An introduction to property based testing"
We are all familiar with example-based testing, as typified by TDD and BDD. Property-based testing takes a very different approach, where a single test is run hundreds of times with randomly generated inputs.
Property-based testing is a great way to find edge cases, and also helps you to understand and document the behaviour of your code under all conditions.
This talk will introduce property-based testing and show how it works, and why you should consider adding it to your arsenal of testing tools.
Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/254wkpw.
Aaron Bedra focuses on describing a system as a series of models that can be used to systematically and automatically generate input data and ensure that a code is behaving as expected. Bedra discusses property based testing and how it can help one build more resilient systems and even reduce the time needed to maintain a test suite. Filmed at qconlondon.com.
Aaron Bedra is Chief Security Officer at eligible.com. He is the creator of Repsheet, an open source threat intelligence framework. Bedra is the co-author of Programming Clojure, 2nd Edition and a frequent contributor to open source software.
Java supports generics as of version 1.5 to allow type-safe operations on parameterized types like List<String>. Generics eliminate the need for explicit casting when adding and retrieving elements. Wildcard types like List<?> provide flexibility but are more limited than specific types. Generic methods allow algorithms to operate on types in a generic way through type parameters.
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.
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.
The document contains code snippets from 3 weekly coding assignments:
1) A Java program to check if a string is a palindrome. It compares characters at the beginning and end of the string.
2) A Java program to sort a list of names in ascending order using string comparison and swapping.
3) A Java program to count the frequency of words in a given text by tokenizing, sorting, and printing the words.
scala.concurrent.Future is familiar to nearly all Scala devs.
This presentation first talks about referential transparency and the IO Monad in general. (Monix Task is an impl of the IO Monad.)
Then it compares Future Monix 3.x Task with their Pros and Cons.
Interop with Future: As Scala's Future is used in many environments and libraries, we look at the conversion from Task to Future and - vice versa - from Future to Task.
I will also take a look at Task evaluation, cancelation and memoization as well as tail recursive loops and asynchronous boundaries.
The presentation will include a comparative discussion on ExecutionContext (required for Future) and Scheduler (required for Task, but only to run it).
Often recurring on the valuable Monix Task doumentation at https://monix.io/docs/3x/eval/task.html the presentation can also be seen as an introduction to Monix Task.
The document provides examples of Java code demonstrating various programming concepts like loops, conditional statements, methods, arrays and string manipulation. It includes code snippets to print "Hello World", check if a number is even or odd, print multiplication tables, convert temperatures between Fahrenheit and Celsius scales, take input from the user and perform basic operations on strings. The examples illustrate the use of various loops like for, while and do-while loops, if-else statements, methods and built-in string/array methods in Java.
The document discusses Java GUI building using AWT and Swing. It explains that AWT is the original toolkit for building GUIs in Java but that Swing provides more advanced and flexible components. It outlines the basic steps for building a GUI with a container, components, layout managers, and listeners to add interactivity. Key topics covered include common components, adding components to containers, using layout managers, and implementing listeners to handle user events.
Implementation details and performance traits of generics in .NET, Java and C++. Presentation for the Jerusalem .NET/C++ User Group by Sasha Goldshtein.
The document discusses generics in C#, explaining that generics allow defining type-safe data structures without committing to actual data types, improving performance and code quality. It covers why generics are required by discussing issues with non-generic stacks, and describes generic type parameters, constraints, methods, delegates and event handling using generics.
The document provides an overview of the Swift Foundation framework. It discusses key types in Foundation like AffineTransform, CharacterSet, Data, Date, DateComponents, Decimal, FileManager, IndexPath, Measurement, Notification, NSError, URL, and URLComponents. The document also briefly mentions the purpose of each type.
This document provides a manual for a Java and J2EE lab for 5th semester computer science students. It contains 15 programs covering topics like enums, annotations, collections, strings, servlets, and database connectivity. Each program is explained and the expected output is provided. The programs demonstrate core Java concepts and commonly used APIs for collections, strings, I/O, and database access.
The document provides code examples for several basic Java programs, including:
1) A program that compares two numbers and prints which is greater.
2) A program that takes a number as input and prints all even numbers between 1 and the input.
3) Programs that calculate the area and perimeter of shapes like circles and rectangles.
4) Programs that calculate the factorial of a number and construct a triangle shape using asterisks.
5) A program that finds and lists all leap years between two given years.
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.
The document contains code for a HomeAssignment class with methods to:
1) Display a square of asterisks of a given side size
2) Display a square of any character of a given side size
3) Calculate and display the factorial of a given number
4) Check if two strings are anagrams by sorting and comparing their characters.
The main method calls each method in turn to demonstrate its functionality.
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
This document discusses concurrency, scalability, and fault tolerance using actors and software transactional memory (STM) in Akka. It describes how actors provide message-passing concurrency by isolating processes and avoiding shared state. Actors allow easy reasoning about concurrency by preventing issues like race conditions and deadlocks. The document also covers how Akka implements actors, typed actors, remote actors, supervisor hierarchies for fault tolerance, and STM for coordinating concurrent changes to shared state transactionally. Combining actors with STM results in "transactors" that allow building distributed, concurrent, and fault-tolerant applications.
This document contains instructions for several Java programming exercises involving classes, packages, inheritance, overriding, exceptions, and threads. It outlines code for programs that demonstrate concepts like classes and objects, command line arguments, bitwise operators, method overriding, and packages. For each exercise, it provides the aim, algorithm, sample code, input/output, and result to verify the output. The exercises are intended to help students learn and practice core Java programming concepts.
Video and more content at fsharpforfunandprofit.com/pbt
"The lazy programmer's guide to writing 1000's of tests: An introduction to property based testing"
We are all familiar with example-based testing, as typified by TDD and BDD. Property-based testing takes a very different approach, where a single test is run hundreds of times with randomly generated inputs.
Property-based testing is a great way to find edge cases, and also helps you to understand and document the behaviour of your code under all conditions.
This talk will introduce property-based testing and show how it works, and why you should consider adding it to your arsenal of testing tools.
Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/254wkpw.
Aaron Bedra focuses on describing a system as a series of models that can be used to systematically and automatically generate input data and ensure that a code is behaving as expected. Bedra discusses property based testing and how it can help one build more resilient systems and even reduce the time needed to maintain a test suite. Filmed at qconlondon.com.
Aaron Bedra is Chief Security Officer at eligible.com. He is the creator of Repsheet, an open source threat intelligence framework. Bedra is the co-author of Programming Clojure, 2nd Edition and a frequent contributor to open source software.
Java supports generics as of version 1.5 to allow type-safe operations on parameterized types like List<String>. Generics eliminate the need for explicit casting when adding and retrieving elements. Wildcard types like List<?> provide flexibility but are more limited than specific types. Generic methods allow algorithms to operate on types in a generic way through type parameters.
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.
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.
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.
- Applets are small Java applications that run within web browsers. They are embedded in HTML pages and can interact with the user.
- Applets follow an event-driven model where the AWT notifies the applet of user interactions. The applet then takes action and returns control to the AWT.
- The applet lifecycle includes init(), start(), stop(), and destroy() methods that are called at different points as the applet loads and runs within the browser.
El documento describe las applets de Java, incluyendo su estructura de ciclo de vida con los métodos init(), start(), stop(), destroy(), y paint(). También discute las ventajas de las applets como ser multiplataforma y cargarse rápidamente, así como las desventajas como requerir el plugin de Java y tener acceso limitado al sistema. Finalmente, muestra un ejemplo básico de una applet que dibuja una línea roja.
This document provides information about applet programming in Java. It discusses that applets are small Java programs used primarily for internet computing. Applets can perform tasks like displaying graphics, playing sounds, and accepting user input. Key differences between applets and standalone applications include applets not having a main method, needing to be embedded in an HTML page, and having restrictions on file/network access. The document also covers the applet lifecycle, writing applet code, and using HTML tags to embed applets in web pages.
Java applets allow Java programs to run in a web browser. Applets are downloaded and run similarly to web pages. When a web page containing an applet tag is loaded, the browser downloads the applet class file from the web server and executes it within the browser's context on the client host. Applets are subject to security restrictions that prevent them from accessing local files or making network connections except back to the host from which they were downloaded.
Java applets are small Java programs that can be embedded within HTML pages. When a user views a page containing an applet, the applet code is transferred to their system and executed by the Java Virtual Machine within their browser. Applets allow for interactive features on web pages like capturing mouse input and including buttons or checkboxes. They can also play media formats not natively supported by browsers. Applets are embedded using the applet or object tags, which can specify the applet's location and download any necessary Java plugins.
This document provides an overview of applet programming in Java. It discusses what applets are, how they are executed, their lifecycle methods, and how to pass parameters to applets. It also covers how to request repainting of an applet window, use the status window, and transfer control to other URLs using the AppletContext interface and showDocument method. Key aspects of the APPLET tag for embedding applets in HTML are also explained.
This document provides information on various AWT components including text areas, checkboxes, radio buttons, lists, and images. It describes the different constructors for text areas and how to add text, select text, and edit text within a text area. It also outlines how to create checkboxes individually and in groups, as well as how to create radio buttons, lists, and display images using methods like drawImage().
Complete the classes shown below 1. The MinHeap Class Write necessa.pdfamericanopticalscbe
Complete the classes shown below: 1. The MinHeap Class Write necessary code in the method
buildMinHeap, downHeap and upHeap. Add your necessary changes in the section where this
block of code is written: /*** *** Write YOUR CODE HERE *** ***/ The driver generates a
Sorted List of decreasing order using HeapSort after the specified heap operations are performed.
The details of these methods are given below, also additional hints are provided in the code as
comments. Also we have added helper methods for generating output. Do not edit any helper
methods, they are necessary for Gradescope. Complete the code before the due date. Submit the
completed MinHeap.java file via Gradescope module in folio. Details of Methods:
buildMinHeap: Given an array of N elements, stored from indices 1 thru N, build a min-heap
using bottom-up construction. The helper functions in the DriverPA2.java file read the size and
populate the input array before calling on your buildMinHeap operation. downHeap: downHeap
is an operation that is used to maintain the heap property after removing the root node from a
heap. When the root node is removed, the last node in the heap is moved to the root position, and
the downHeap operation is applied to this node to restore the heap property During downHeap,
the node is compared with its children, and if its value is greater than the value of its children , it
is swapped with the child that has the lowest value. This process is repeated until the heap
property is restored. downHeap will restore the heap-order property by swapping key k along a
downward path from the root. You need to maintain the Min Heap properties within the reduced
size of the array. upHeap: upHeap is an operation that is used to maintain the heap property after
inserting a new node into the heap. When a new node is inserted, it is placed at the bottom of the
heap and the upHeap operation is applied to this node to restore the heap property. During
upHeap, the node is compared with its parent, and if its value is less than the value of its parent ,
it is swapped with its parent. This process is repeated until the heap property is restored. upHeap
will restore the heap-order property by swapping k along an upward path from the insertion
node. During each insertion process, you need to ensure the MinHeap property is maintained.
Input File Structure: Example: minheap0.txt 7 // Input array size(size_n) 21 16 13 12 9 7 3 //
Input Array for MinHeap build (int[] minHeap) 10 30 20 5 15 // Integer array to be inserted in
the MinHeap(int[] newelements) Sample Output in DriverPA2: Result after buildheap: 3 9 7 12
16 21 13 Removed Elements: 3 7 9 12 13 HeapSort result: 30 21 20 16 15 10 5 We have added 5
more input files, you can test them as well changing the file name in the Driver.java main
method. These are the files: minheap1.txt minheap2.txt minheap3.txt minheap4.txt minheap5.txt
Additional Notes: We have allocated the size of the Input Array more than enough capacity f.
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docxbradburgess22840
In Class Assignmetz/CST280W13a-1.pdf
CST 280 In-Class Practice – Week 13
Manually determine the configuration of the priority queue (stored as a heap) created
by the following operations. Trace the following logic and define the output:
enqueue(7);
enqueue(17);
enqueue(2);
enqueue(5);
enqueue(22);
enqueue(19);
enqueue(6);
enqueue(11);
enqueue(13);
write the queue contents
dequeue and write front item
enqueue(15);
enqueue(8);
dequeue and write front item
dequeue and write front item
enqueue(24);
enqueue(14);
write the queue contents
Part 2
Then, verify the output by implementing the algorithm by rewriting the priority
queue demonstration program discussed in class. Files needed:
testPQueue.cpp pqType.h heap.cpp
Deliverables
• This cover sheet (with your names on it)
• Driver source code and output for verification program exectution.
In Class Assignmetz/CST280W13b.pdf
CST 280 In-Class Practice – Week 13
Use this page as a worksheet to sketch the progression of the elements up to the first
split for the QuickSort algorithm. Use the middle array element as the split value:
15 34 99 42 11 41 66 23 55 93 48
Next, access the file quickSort.cpp from the course web page. Tailor the program
by entering the array values above in place of the integer values used for an in-class
demonstration. Be sure to adjust the index range to match the size of this array.
Remember that the parameters to the QuickSort algorithm are starting and ending index
values, not the size of the array.
Next, insert code to demonstrate the state of the array after the first split. This should
verify what you did by hand above. Insert the following code at various points within
the partition function to “see” the array at various stages of processing:
for (int i = start; i <= end; i++) // <== ADD
cout << set[i] << ' ';
cout << endl;
Insert the code at these positions:
int partition(int set[], int start, int end)
{
int pivotValue, pivotIndex, mid;
mid = (start + end) / 2;
swap(set[start], set[mid]);
pivotIndex = start;
pivotValue = set[start];
ç HERE
for (int scan = start + 1; scan <= end; scan++)
{
if (set[scan] < pivotValue)
{
pivotIndex++;
swap(set[pivotIndex], set[scan]);
}
ç HERE
}
swap(set[start], set[pivotIndex]);
ç HERE
return pivotIndex;
}
Finally, identify the line that matches what you concluded above.
Deliverables:
Deliver the following for this assignment:
• This work sheet with a sketch of the array first split
• Program source code with required change
• Program output demonstrating array configuration after first split .
This document provides information about various Java Abstract Window Toolkit (AWT) components. It describes AWT components like Button, Label, TextField, TextArea, Checkbox, CheckboxGroup, Choice, List, Scrollbar, MenuBar and Menu. For each component, it discusses the class, constructors, methods and provides examples of how to create and use the component. The document gives an overview of the AWT component hierarchy and how different components like containers, panels and frames are related. It explains how to create graphical user interfaces in Java using these basic AWT components.
Write a program that will test a name) method no sorting routine from.docxajoy21
The document describes a Java program that uses an ArrayList to test a selection sort algorithm. It prompts the user to enter a number, fills the ArrayList with that many randomly generated integers from 1 to 50, prints the original ArrayList, calls a selection sort method to sort the ArrayList, and prints the sorted ArrayList. The selection sort method uses nested for loops to find the minimum element in the unsorted section and swap it with the current element being considered.
This document describes a Java program to implement a stack data structure using both an array and linked list. It defines a Stack interface and ArrayStack and LinkedListStack classes that implement the stack. The ArrayStack uses an array to store elements while LinkedListStack uses linked list nodes. Methods like push(), pop(), top(), and topAndPop() are implemented to add/remove elements from the stack. Exception handling is included for empty stack cases. Sample code tests inserting characters and numbers into both stack implementations.
The document discusses different implementations of stacks and queues using linked lists and arrays. It describes how stacks can be implemented using a linked list, with push and pop operations adding and removing nodes from the head of the list. Queues can also be implemented with linked lists or arrays, but arrays require additional logic to maintain first-in, first-out order efficiently. Common applications of stacks and queues include evaluating expressions, checking for balanced brackets, and managing tasks in operating systems and server requests.
The document discusses the Abstract Window Toolkit (AWT) classes in Java, which allow developers to create graphical user interfaces. It describes key AWT classes like Component, Container, Window, Frame, and Panel. It also covers common AWT controls like labels, buttons, checkboxes, scrollbars, choice boxes, lists, text fields, and text areas. Finally, it briefly introduces layout managers for positioning UI components.
Using the code below Part 1 Write a static method called L.pdfpicscamshoppe
Using the code below:
Part 1: Write a static method called LinkedListToStack that takes a Node reference as a parameter
(which represents a linked list). Add every element in the linked list to a stack and return the stack.
Part 2: Write a static method called avgOfNumbersInStack that takes a stack of Integer as a
parameter. It will return a double value which is the average of all the numbers in the stack.
package activity9;
import java.util.Scanner;
import java.util.*;
public class StackPractice {
public static Node listGenerator(int input)
{
int n;
int count = 0;
Random rand = new Random();
n = rand.nextInt(100);
Node head = null;
head = new Node(n);
count++;
while(count < input) {
Node t1 = new Node(n = rand.nextInt(100), head);
head = t1;
count++;
}
return head;
}
public static void printLinkedList(Node input) {
Node curr = input;
while(curr != null) {
System.out.println(curr.item);
curr = curr.next;
}
}
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int input = 0;
System.out.print("Please enter the starting integer: ");
input = Integer.parseInt(kbd.nextLine());
listGenerator(input);
printLinkedList(listGenerator(input));
}
}.
The document discusses stacks and their implementation in Java using BlueJ. It explains what BlueJ is and how stacks can be implemented using static or dynamic data structures. It then provides code for a Stack class that implements a stack using an array to store objects. Methods like push(), pop(), isEmpty() etc are included. It also provides code for a StackTester class to demonstrate how the Stack class can be used by adding and removing integers. Exercises are included to modify StackTester to use strings instead of integers and to use a stack to check bracket balancing in code.
The document contains code examples demonstrating different Java AWT components including frames, panels, labels, and applets. The frame examples show how to create basic frames and add window listeners. The panel example shows how to add a panel to a frame. The label example demonstrates adding labels and text fields to a frame. The applet examples show the applet lifecycle methods and how to use strings and scrolling text in applets.
The program defines a jagged array with 3 inner arrays of unspecified length. It initializes the inner arrays. It then iterates through the jagged array and sums all elements of the inner arrays. The total sum is returned.
Stack is an abstract data type that serves as a linear collection of elements. It has two main operations: push, which adds an element to the top of the stack, and pop, which removes the top element. A stack follows last-in, first-out (LIFO) order, meaning the last element added is the first removed. Common real-world examples of stacks include piles of plates and books.
Hello. I need help fixing this Java Code on Eclipse. Please fix part.pdfflashfashioncasualwe
Hello. I need help fixing this Java Code on Eclipse. Please fix parts indicated as \"//Fix\" or
\"//Fill-in\". The code given is the first image. Thank you! Sample outputs are given below along
with what the code is required to do. import java til. Random import java til. Scanner public class
GenCheeseShopv2 public static void intro (Stringt] names, double []prices int amounts Fill-in
public static void getAmount (Scanner input, String[] names, int[] amounts) public static void
itemizedList (String[] names, double Prices int[] amounts) Fill-i public static double
calcSubTotal (double prices, int amounts return 0; pub. lic static int discount (double subTotal
return 0; pub. lic static oid print Total (double subTotal int discount) Fill-in public static void mi
args final int MAXCH EESEE DO NOT CHANGE ANYTHING BELOW String[] names new
String CMAXCH EESE double[] prices new double EESE] int[] amounts new int
[MAXCHEESEJ Scanner input new Scanner (Syste intro names, prices, amounts get Amo unt
input, names, amounts double total calcSubTotal (prices, amounts if EESEE 0) System. out print
Display the itemized list? (1 for yes) int itemized input-nex if item 1) itemized List (names,
prices, amounts); System. out. println(); print Total(total, discount total));
Solution
import java.util.Random;
import java.util.Scanner;
public class GenCheeseShopv2 {
public static void intro(String[] names, double[] prices,int[] amounts){
System.out.println(\"We sell \"+names.length+\" kinds of cheese\");
for(int i=0;i0)
System.out.println(amounts[i]+\" lbs of \"+names[i]+\" @ \"+prices[i]+\" =
$\"+(amounts[i]*prices[i]));
}
}
public static double calcSubTotal( double[] prices,int[] amounts){
double subTotal=0;
for(int i=0;i100)
return 10;
else if(subTotal > 50)
return 25;
else
return 0;
}
public static void printTotal(double subTotal,int discount){
System.out.println(\"Sub Total : $\"+subTotal);
System.out.println(\"-Discount : $\"+discount);
System.out.println(\"Total : $\"+(subTotal-discount));
}
public static void main(String[] args){
final int MAXCHEESES=4;
String[] names = new String[MAXCHEESES];
double[] prices = new double[MAXCHEESES];
int[] amounts = new int[MAXCHEESES];
Scanner input = new Scanner(System.in);
intro(names, prices, amounts);
getAmount(input, names, amounts);
double total = calcSubTotal(prices, amounts);
if(MAXCHEESES>0){
System.out.println(\"Display the itemized list? (1 for yes)\");
int itemized = input.nextInt();
if(itemized==1){
itemizedList(names, prices, amounts);
}
}
System.out.println();
printTotal(total, discount(total));
}
}.
The document discusses stacks and their implementation. It defines stacks as ordered collections where insertions and deletions occur at one end. Common stack operations like push and pop are described. Stacks can be implemented using arrays or linked lists. Various stack applications are mentioned like checking balanced symbols.
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdfinfo114
Need done for Date Structures please!
4.18 LAB: Sorted number list implementation with linked lists
Step 1: Inspect the Node.h file
Inspect the class declaration for a doubly-linked list node in Node.h. Access Node.h by clicking
on the orange arrow next to main.cpp at the top of the coding window. The Node class has three
member variables:
a double data value,
a pointer to the next node, and
a pointer to the previous node.
Each member variable is protected. So code outside of the class must use the provided getter and
setter member functions to get or set a member variable.
Node.h is read only, since no changes are required.
Step 2: Implement the Insert() member function
A class for a sorted, doubly-linked list is declared in SortedNumberList.h. Implement the
SortedNumberList class's Insert() member function. The function must create a new node with
the parameter value, then insert the node into the proper sorted position in the linked list. Ex:
Suppose a SortedNumberList's current list is 23 47.25 86, then Insert(33.5) is called. A new node
with data value 33.5 is created and inserted between 23 and 47.25, thus preserving the list's
sorted order and yielding: 23 35.5 47.25 86
Step 3: Test in develop mode
Code in main() takes a space-separated list of numbers and inserts each into a SortedNumberList.
The list is displayed after each insertion. Ex: If input is
then output is:
Try various program inputs, ensuring that each outputs a sorted list.
Step 4: Implement the Remove() member function
Implement the SortedNumberList class's Remove() member function. The function takes a
parameter for the number to be removed from the list. If the number does not exist in the list, the
list is not changed and false is returned. Otherwise, the first instance of the number is removed
from the list and true is returned.
Uncomment the commented-out part in main() that reads a second input line and removes
numbers from the list. Test in develop mode to ensure that insertion and removal both work
properly, then submit code for grading. Ex: If input is
then output is:
main.cpp
#include <iostream>
#include <string>
#include <vector>
#include "Node.h"
#include "SortedNumberList.h"
using namespace std;
void PrintList(SortedNumberList& list);
vector<string> SpaceSplit(string source);
int main(int argc, char *argv[]) {
// Read the line of input numbers
string inputLine;
getline(cin, inputLine);
// Split on space character
vector<string> terms = SpaceSplit(inputLine);
// Insert each value and show the sorted list's contents after each insertion
SortedNumberList list;
for (auto term : terms) {
double number = stod(term);
cout << "List after inserting " << number << ": " << endl;
list.Insert(number);
PrintList(list);
}
/*
// Read the input line with numbers to remove
getline(cin, inputLine);
terms = SpaceSplit(inputLine);
// Remove each value
for (auto term : terms) {
double number = stod(term);
cout << "List after removing " << number << ": " << endl;
list.Remove(number.
1. Generics in Java allow types (like lists and stacks) to operate on multiple type parameters, providing compile-time type safety without sacrificing performance.
2. Using generics avoids casting and reduces errors by catching type problems at compile time rather than runtime. It produces more readable and maintainable code.
3. The document demonstrates how to define a generic Stack class that works for any type rather than just Integers, avoiding code duplication and future bugs.
OrderTest.javapublic class OrderTest { Get an arra.pdfakkhan101
OrderTest.java
public class OrderTest {
/**
* Get an array of specified size and pass it to Order.order().
* Report the results.
*/
public static void main(String[] args) {
if (args.length != 1) {//1
System.out.println(\"Usage: java OrderTest sizeOfArray\ \"
+ \"\\tor\ \\tjava OrderTest arrayFile\");
System.exit(1);
}
// create or read the int[]
int size = 0;
int[] array = new int[0];//5
try {
size = Integer.parseInt(args[0]);
array = ArrayOfInts.randomizedArray(size);
} catch (NumberFormatException nfe) {//8
try {
array = ArrayOfInts.arrayFromFile(args[0]);
size = array.length;
} catch (Exception e) {
System.err.println(\"unable to read array from \" + args[0]);
System.exit(1);//14
}
}
System.out.println(\"before:\");//15
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? \" %d\" : \" %d\ \", array[i]);//1
}
int myNum = Order.order(array); //this is the call we want to measure
System.out.println(\"\ after:\");//18
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? \" %d\" : \" %d\ \", array[i]);
}
System.out.println(myNum);
}
}
ArrayOfInts.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ArrayOfInts {
/**
* Returns an array of consecutive ints from 1 to size.
*/
public static int[] orderedArray(int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = i+1;
}
return a;
}
/**
* Returns a randomized array containing ints from 1 to size.
*/
public static int[] randomizedArray(int size) {
ArrayList aL = new ArrayList();
for (int i = 0; i < size; i++) {
aL.add(i+1);
}
Collections.shuffle(aL);
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = aL.get(i);
}
return a;
}
/**
* Writes an int[] to a plain-text file with ints separated by spaces.
* Useful for creating input files for repeatable tests.
*/
public static void arrayToFile(int[] array, String outfile) {
try {
FileWriter fw = new FileWriter(outfile);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
for (int i : array) {
outFile.print(i + \" \");
}
outFile.close();
} catch (IOException e) {
System.err.println(\"Could not write to \" + outfile + \"\ \" + e);
}
}
/**
* Read ints from a file and return them in an int[]
*/
public static int[] arrayFromFile(String infile) throws FileNotFoundException,
InputMismatchException {
Scanner scan = new Scanner(new File(infile));
ArrayList aL = new ArrayList();
while (scan.hasNext()) {
aL.add(scan.nextInt());
}
scan.close();
int[] a = new int[aL.size()];
for (int i = 0; i < a.length; i++) {
a[i] = aL.get(i);
}
return a;
}
}
Order.java
public class Order {
/**
* Take an int[] and reorganize it so they are in ascending order.
*/
public static int order(int[] array) .
3. Applet Component
Label :-
Constructor:-
new Label( ) throws HeadLessException
new Label(String str) throws HeadlessException
new Label(String str,int how) throws HeadlessException
how=Label.LEFT or Label.RIGHT or Label.CENTER
Methods:-
void setText(String str)
String getText();
void setAlignment(int how)
int getAlignment();
4. Applet Component
import java.awt.*;
import java.applet.*;
public class MyApp extends Applet
{
Label L1,L2;
public void init()
{
L1=new Label();
L1.setText(“ABCD”);
L2=new Label();
add(L1);
add(L2);
}
}
5. Applet Component
Button :-
Constructor:-
new Button() throws HeadlessException
new Button(String str) throws
HeadlessException
Methods:-
void setLabel(String str); //label for the
buttons.
String getLabel();
6. Applet Component
import java.awt.*;
import java.applet.*;
public class MyApp extends Applet
{
Button b1,b2;
public void init()
{
b1=new Button();
b1.setText(“PUSH”);
L2=new Button();
add(b1);
add(b2);
}
}
7. Applet Component
Check Boxes
Constructor :-
new Checkbox()throws HeadlessException // blank checkbox unchecked
new Checkbox(String )throws
HeadlessException// create a named checkbox
new Checkbox(String ,boolean ) throws
HeadlessException // create a named checkbox if true checkbox is
checked othewise it is false
new Checkbox(String,boolean,CheckboxGroup) throws
HeadlessException
new Checkbox(String,CheckboxGroup,boolean) throws
HeadlessException
//create a named checkbox with initial stateeither true or false depend on boolean value
, and
also declare that check box is a part of checkbox group or not.
Method:-
boolean getState();
void setState(String str);
String getLabel();
9. Applet Component
CheckboxGroup:- radiobutton only one checkboc at a time .
Constructor:-
new CheckboxGroup();
Method:-
Checkbox getSelectedCheckbox();
void setSelectedCheckbox(Checkbox which)
11. Applet Component
Choice Controls:- Popup list of item which the
user may choose.
Constructor :-
new Choice();
Methods:-
void add(String name)
String getSelectedItem();
int getSelectedIndex();// index start from 0.
void select(int index);
void select (String name) ;
String getItem(int index) ;
12. Applet Component
import java.awt.*;
import java.applet.*;
public class MyApp extends Applet
{
Choice c1;
public void init()
{
Choice c1=new Choice();
c1.add(“WIN95”);
c1.add(“WIN98”);
c1.add(“WINXP”);
add(c1);
}
}
13. Applet Component
Lists :- Multiple choice scroll selection list.
Constructor :-
new List();
new List(int numrows);
new List(int numrows,boolean multiselect)
Method:-
void add(String name);
void add(String name,int index); // index start from 0.
index=-1 it means add the
item at the end of the list.
String getSelectedItem(); // index of selected item.
int getSelectedIndex(); //index start from 0. if more then
one item is selected or no
selection is made -1 is returned.
String [ ] getSelectedItems() ;//names of selcted items
int [ ] getSelectedIndexes() ; //indexes of selected items.
14. Applet Component
import java.awt.*;
import java.applet.*;
public class MyApp extends Applet
{
List l1;
public void init()
{
l1=new List(5, true);
l1.add(“WIN95”);
l1.add(“WIN98”);
l1.add(“WINXP”);
l1.add(“WINVISTA”);
l1.add(“WIN&”);
add(l1);
}
}
15. Applet Component
Scroll Bar :- Used to select continuous values between
a specified minimum and maximum .
Constructor:-
new Scrollbar() // horiozontal scrollbar
new Scrollbar(int style) //style=Scrollbar.Horizontal
Scrollbar.Vertical
new Scrollbar(int style,int initialvalue,int
thumbsize,int min,int max);
//initialvalue of the scroolbar, thumbsize represent the no of
represent by the height of the thumb . minimumn and maximum
value of scrollbar is represented by min and max .
16. Applet Component
Scrollbar:-
Methods :-
void setValues(int initval,int thumbsize,int max,int min);
int getValue();// To retrieve the current value
void setValue(int newvalue);// To set the new value of
scrollbar.
int getMinimum();
int getMaximum();
void setUnitIncrement(int newincr);
void setBlockedIncrement(int newincr);
// each time the 1 is incremented from the scroll bar each time it is scrolled
up or down one line. By default pageup and pagedown value are 10 we
can change it by above two methods.
17. Applet Component
import java.awt.*;
import java.applet.*;
public class MyApp extends Applet
{
Scrollbar hsb,vsb;
public void init()
{
hsb=new Scrollbar(Scrollbar.Horizontal,0,1,0,50);
vsb=new Scrollbar(Scrollbar.Vertical,0,1,0,50)
add(hsb);
add(vsb);
}
}
18. Applet Component
TextField:-
Costructor:-
new TextField();
new TextField(int numchar);// create a textfield numchar
wide
new TextField(String str); // create a text field with str.
new TextField(String str,int numchar); //create a textfield
sets with str and numchar set its width;
Methods:-
String getText();
void setText(String str);
String getSelectedText();
void select(int startindex,int endindex);//select at startindex and ending at endindex-
1
void setEditable();
boolean isEditable();
20. Applet Component
TextField:-
Costructor:-
new TextArea();
new TextArea(int numline,int numchar);
new TextArea(String str);
new TextField(String str,int numline,int numchar);
new TextField(String str,int numline,int numchar,int sbars);// bars= SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
Methods:-
String getText();
void setText(String str);
String getSelectedText();
void select(int startindex,int endindex);//select at startindex and ending at endindex-1
void setEditable();
boolean isEditable();
21. Applet Component
TextField:-
Methods:-
void append(String str); // append the string
specified by str
void insert(String str,int index);//pass the string
str at specified
by the index
void replaceRange(String str,int
startind,int end ind); // replace the
characters from
startindex to
endIndex-1
22. Applet Component
( MenuBar,Menu,MenuItem)
Constructors:-
MenuBar :-
new MenuBar();
Menu:-
new Menu();
new Menu(String optionname);
MenuItem:-
new MenuItem();
new MenuItem(String str);
new MenuItem( String str,MenuShortcut keyAccel);
25. Applet Component
Container:-
1) Inherit the Component class .
2) It has additional method that allow other component object to
be nested within it.
3)Container object contain other Container object. This makes
multilevel containment system.
4)Conatianer is responsible for laying out(positioning) any
component that it contain.It does this through the
layout managers.
methods:-
void add(Component cmp);
void remove(Component cmp);
26. Layout Manager
Every Component that we place in the Container
has a size and location in Container.This size and
location of the component in the Container is
managed by the LayoutManager. Following are the
types of LayoutManagers
FlowLayoutManager
GridLayoutManager
BorderLayoutManager
CardLayoutManager
27. Layout Manager
Methods:-
void setLayout(LayoutManager layoutobj);
// layoutobj is the object of LayoutManager
class.if we pass null then we disable the
layout manager and determine the shape and
position manually using setBound() defined
by Component class.
28. Layout Manager
FlowLayoutManager :-
new FlowLayout(); // maintain the space of 5 pixels between each
component.
new FlowLayout(int how) // how specify
alignment of component
how=FlowLayout.LEFT
FlowLayout.RIGHT
FlowLayout.CENTER
new FlowLayout(int how,int horz, int vert )
// horz & vert specify horizontal and vertical space left between each component .
30. Layout Manager
GridLayoutManager:-
new GridLayoutManager( ); //create a grid of
single row
and single
column .
new GridLayoutManager(int row, int col);
new GridLayoutManager(int row, int col,int
horz,int col);
32. Layout Manager
BorderLayoutManager :-
It has four narrow fixed width components at the edges and one large area in the
center ,The four sides is referred to as north, south,east,west and middle are is referred as center.
BorderLayout reffers the following constant that specify the regions.
BorderLayout.CENTER
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.SOUTH
BorderLayout.NORTH
All the regions specify with the Component when we add that component in that
Container.
void add(Component compobj , Object region);
36. Event Handling
Event:-
It can be generated as a consequence of
person interacting with the elements in a gui.
Some of the activities that cause events to be
generated are pressing a button ,entring a
character via a keyboard , selecting a list etc.
“ In the Event Delegation model,an Event is an
object that describes a state change in a source.
”
37. Event Handling
To process the events we need to identify this
events and then take some action. This is known as event
handling. The modern approach to handling an event is
based on “Event Delegation Model”. In this model we
have 3 following entities .
Source
Event
Handler or Listenr
38. Event Handling
Event Delegation Model :-
(Delegation Event Model)
Source generates Events
Handeled by
register
Handler
39. Event Handling
Source :- Source is used to generate the event and it
is mainly a Component.Examples Button,TextField
etc. Every source and component has the
predefined .
Event :- An Event can be generated by the source.It
can possible that the same events are generated by
different sources. Events are represented by classes .
Handler or Listener:- To handle the event handlers
are used . Every event is a predefined handler. The
event can be generated by any source but the
handler is always be same. Handlers are represented
by or interfaces.
40. Event Handling
ActionEvent is an event is generated when we
click on button ar press the enter key in TextField
. And this ActionEvent is handled by
ActionListener interface.
Button onclick ActionEvent handled by ActionListener
on enter
TextField
41. Event Handling
ActionListener is an interface which contains
the following method.
public void actionPerformed(ActionEvent ae)
When the ActionEvent is generated the
ActionListener’s actionPerformed method get
executed . The operation that we want to
perform on the click of Button should be put
within the actionPerformed method.
42. Event Handling
For the event handling we need to create the handler class. The class will be
handler class when it implement the appropriate listener and override the
methods of interface.
Ex:-
public class A implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
--------------
--------------
--------------
--------------
}
}
43. Event Handling
Handler 1:-
public class A implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
--------------
--------------
--------------
--------------
}
}
Handler 2:-
public class B implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
--------------
--------------
--------------
--------------
}
}
44. Event Handling(ActionEvent)
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class MyApp extends Applet
{
public TextField t1,t2,t3;
Button b1;
FlowLayout fl;
public void init()
48. Event Handling(ActionEvent)
public void actionPerformed(ActionEvent ae)
{
int i=Integer.parseInt(th1.getText());
int j=Integer.parseInt(th2.getText());
String s1=i+j+ "";
th3.setText(s1);
}
}
49. Event Handling
Once the handler is created it should be registered with source without
which eventhandling is not possible it is necessary otherwise we don’t
know which handler handle the event.
To register the handler with the source th methods are provided in the
source.
Registration methods of Button and Textfield source is following .
void addActionListener(ActionListner al)
// al represent the object of that class which implement the
ActionListener interface. Method belonging to Button and Textfield
class.
50. Event Handling
Action Event- 1)button is clicked.
2) list item is double clicked.
3)menu item is selected.
4) txt field is entered.
ActionListener :-
public void actionPerformed(ActionEvent ae)
51. Event Handling
ItemEvent:- 1) checkbox or list item is
selected .
2) choice selection is made
3)Checkable menu item is
selected or deselected.
ItemListener:-
public void itemStateChanged(ItemEvent ie)
52. Event Handling
AdjustmentEvent :-Scroll bar is manipulated .
AdjustementListener:-
void adjustmentValueChanged(
AdjustmentEvent e);
53. Event Handling
ComponentEvent:- when a component is
hidden moved resized or
become visible.
ComponentListener:-
void ComponentResized(ComponentEvevnt ce);
void ComponentMoved(ComponentEvevnt ce);
void ComponentShown(ComponentEvevnt ce);
void ComponentHidden(ComponentEvevnt ce);
63. Inner class
Classes which is defined within another class.
class A
{
Class B
{
}
}
A is container class or top level class. B is inner class.
One class can contain any no of inner class./Inner
classs can contain inner class and this can go upto
any level.
64. Inner class
Inner classes are of 4 types.
1)Static inner class
2)Non static inner class
3)Local inner class
4) Anonymous inner class
65. Inner class
Non static inner class:- This class ork as the
member of class like
static inner class they can have any type of
accessibility (public/private/protected/default)
,but like static inner class they can not have static members .
Because the non static class is the member of top level class and
non static member exist when its object is created .The non static
inner class doesn’t exist until the object of top level class created.
A non static inner class is always associated within the object of
top level class and therefore it has the special privilege it can
access any member(static/non static) of its top level class . So
that non static inner class is used for event handling.
66. Panel
A Component which is used as a Container. It
is used for physically grouping of Component.
Constructor:-
new Panel(); // Create the panel with Flow
layout Manager.
new Panel(LayoutManager lm); // Create
the panel with
same
layoutManager by
which is pass as the parameter
in the panel.
68. Standalone application
To cretae a stand alone application we ned to create a class which will
inherit Frame class . To run it we don’t need html ,this type of
application has it ‘s own window. And this type of application created
just like console based application.
Features of stand alone application.
1) Standalone application is also called
Frame.
2)Frame provide the outlaw of window we only need to place the
components on window.
3)Frame has the same applarcchitecture and structure as the applet and
therefore GUI application and the event handling will be same as applet.
4)Like applet it doesn’t have init,start,stop,destroy,paint methods and
therefore instead of initialize the applet we need we need to define the
constructor of that class which inherit the Frame class.
5)To display standalone applicatio we need main method.just like console
based application
69. Standalone application
Import java.awt.*;
Impoort java.applet.*;
Import java.awt.event.*;
public class Hobby extends Frame implements ItemListener
{
---------------
--------------
public Hobbbby( )
{
-----------------
------------------
------------------ same as init
}
74. Standalone application
public void actionPerformed(ActionEvent ae)
{
int i=Integer.parseInt(t1.getText());
int j=Integer.parseInt(t2.getText());
t3.setText(i+j+"");
}
}
75. Standalone application
public class MyWindow
{
public static void main(String arg[])
{
MyFrame mf=new MyFrame();
mf.setSize(300,300);
mf.setVisible(true);
}
}
76. Standalone application
Some issues on Window:- When w click on crossbar th window
doesn’t terminate and still on RAM to close it we have to close the
DOS prompt because the event is generated by Frame we have
to handle the event of Frame. There are 7 state of Frame when it
generate event. In all 7 state it generate the WindowEvent .
To handle the 7 state of Frame WindowListener
interface provide 7 different methods.When we implement the
WindowListener we need to override the all 7 methods.
void windowActivated(WindowEvent we);
void windowClosed(WindowEvent we);
void windowClosing(WindowEvent we);
78. Standalone application
1) windowOpened is called after the application
display on the screen . It called only once .It is used to initialize the
application.
2)windowIconified is called when window is minimized .
3) windowDeiconified is called when window is maximized .
4) winowActivate is called when the application get the focus.
5)windowDeactvate is called when the application lost the focus.
6)windowClosed is called when we click on cross button .
7)windowClosing
dispose():- is called to terminate the application
System.exit(0) :-is called to terminate the dos prompt or to
terminate the JVM.
79. Standalone application
windowClosing is called when the application
is dispose.It is used to save the state of
application.This is called only once but closed
is not called untill dispose is called .
Registration method :-
void addindowListner(WindowEvent we)
89. Adapter class
---------------------
}
public class MyWindowAdapter
{
public static void main(String arg[])
{
-------------------
-------------------
---------------------
}
}
90. Adapter class
All listener those contain more than one
methods have Adapter classs.
WindowListener .
KeyListener
MouseListener
MouseMotionListener.