0% found this document useful (0 votes)
21 views

Packages and GUI

Packages allow code reuse and separate design from coding. Layouts determine how GUI components are arranged. Event handling involves defining event sources, listeners, and classes to respond to user interactions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Packages and GUI

Packages allow code reuse and separate design from coding. Layouts determine how GUI components are arranged. Event handling involves defining event sources, listeners, and classes to respond to user interactions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Packages

Day 3 - morning
Packages

• Classes in one project can be used in another project


without copying them by using packages.
• In general, packages have abstract classes.
• Packages allow,
– easy code reuse
– unique class creation in a package
– separate the design from coding
Package types

1. Java API packages


2. User Defined packages
Java API packages

• Provide large number of classes

Image is from https://www.javapoint.com/package


Java API packages (cont.)
Accessing Java API packages

1. Import package to the project


Example:
import java.awt.Color

2. Use directly
Example:
java.awt.Color
User defined packages

• Use Package keyword to declare the package


• Then define the classes in the package file
package MyPackage;
public class ClassA{
}

• Create a subdirectory MyPackage under project directory.


• Save the file under the class name .java (ClassA.java)
• Compile the file.
Add another class to the package

• Simply create a file in the package sub directory with


<className>.java
• Edit the <className>.java file
– Add package <PackageName>; line to the top of the page
– Define the class after that.
– Remember to give public access to the class.
• Compile the <className>.java file
Hide a class in the package

• In general, classes in a package are public.

• Delete the public keyword in the class definition, that will


make the class private.
Use user define package in another project

• In a simple setup, it can be imported directly since the


package sub folder is created inside the project.

• Example
– import <PackageName>;
– import <PackageName>.<ClassName>;
NetBeans package folders will be created inside src
folder.
How to import

• Set the classpath variable of the project to the targeted


package location.

• Or, do it in console mode with java command


>set -classpath=<file path to the package>
>java -classpath <projectName>

Or, Create JAR file and import it.


If multiple packages have same class?

• Compiler doesn’t know how to differentiate.


• Therefore, use unique names to identify the class from
each package with package name.
• Example
– Consider package1 and package2 has Student class. Then
instance can be created as
• package1.Student studentObj1;
• package2.Student studentObj2;
Create JAR
Add JAR to a project
Lambda Expression (intro)
Day 3 - Morning
Functional Interface

• An interface with single abstract method.

• Example
public interface MyInterface{
void PrintName();
}
Lambda Expression

• Provide definition to the abstract method


• Shorten and simplified method for definition

• Syntax
– () -> { body of the abstract method}
– (parameters) -> { body of the abstract method}

– Three parts:
• () - input parameters
• -> arrow token
• {} - abstract method definition
Regular code vs. lambda expression
public interface MyInterface { public interface MyInterface {
public void PrintHello(); public void PrintHello();
} }

public class LambdaExampleOne { public class LambdaExampleOne {

public static void main(String[] args) { public static void main(String[] args) {

MyInterface obj = new MyInterface() { MyInterface obj = () -> {


@Override System.out.println("Hello");
public void PrintHello() { };
System.out.println("Hello");
} obj.PrintHello();
}; }
}
obj.PrintHello();
}
}
Lambda with one parameter
public interface MyInterface {
public void PrintHello(String name);
}

public class LambdaExampleOne {

public static void main(String[] args) {

MyInterface obj = (name) -> {


System.out.println("Hello "+name);
};

obj.PrintHello("Randima");
}
}
Lambda with two parameters
public interface MyInterface {
public int AddTwoNumber(int a,int b);
}
public class LambdaExampleOne {

public static void main(String[] args) {

MyInterface obj = (num1, num2) -> {


return num1+num2;
};

System.out.println(“Sum of numbers =”+obj.AddTwoNumber(10,20));


}
}
Lambda expression on if condition

• Lambda expression can be implemented without


functional interface.
• An if condition can be implemented using lambda
expression.
If statement on lambda expression
String Compare(int n){
if (n>0)
return “positive”;
else if (n<0)
return “negative”;
else
return “equal”;
}

(int n) -> {return n>0? ”positive”: n<0? ”negative”:”equal”;}


Lambda expression converting forEach
import java.util.Arrays;
import java.util.List;

public class LambdaForEach {


public static void main(String[] args) {
List <Integer> array = Arrays.asList(5, 2, 3, 7, 9);

System.out.println("Regular for loop");


for(int num:array){
System.out.println(num);
}

System.out.println("For Each with Lambda");


array.forEach(n->{
System.out.print(n+" ");
});
}
}
Graphical User Interfaces
Day 3 - Afternoon
GUI

• There are two packages in Java


– AWT
– Swing (newer and an extension to the AWT)
Swing

• javax.swing is the top level class

• javax.awt.container is the super class of swing.


• javax.awt.container is extended using JComponent class.
• All the swing components are extended from the
JComponents.
Swing hierarchy
First Java GUI

import javax.swing.*;

public class GUIOneJustFrame {

public static void main(String[] args) {


JFrame frame = new JFrame();
frame.setVisible(true);
}
}
Modifying the First Java GUI
import javax.swing.*;

public class GUIOneJustFrame {

public static void main(String[] args) {


JFrame frame = new JFrame();
frame.setSize(450,250);
frame.setTitle("First Java GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.enable(true);
frame.setVisible(true);
}
}
Layouts

• Layout is the way that components of the GUI is arranged.


• Four different layout types
1. Border layout
2. Flow layout
3. Grid Bag layout
4. Grid layout
Layouts

• Border Layout
– Arrange the components to five regions in the frame
• North
• South
• West
• East
• Center
– Each region will have only one component.
Layouts

• Flow Layout
– This is the default layout arrangment
– Laying the components from left to right within the JPanel
– However, three alignments are available
• Leading
• Trailing
• Center (default)
Layouts

• Grid Layout
– Components are placed in a grid layout.
– A cell of the grid holds only one component
– Layout adds the components from left to right and top to bottom.

– new GridLayout(3,4) // 3 - rows, 4 - columns


Layouts

• Gridbag Layout
– This is just like the Gridbag layout
– Except, components can expand to multiple columns and rows
– Columns can have different widths.
Swing Component Classes
Create a component and add it to the frame

Lets add a label


//create two labels
JLabel label1 = new JLabel("Number 1");
JLabel label2 = new JLabel("Number 2");

//set the size for the label


label1.setSize(100,30);
label2.setSize(100,30);

//add the labels to the frame


frame.add(label1);
labels are appearing at same location.
frame.add(label2); No specific layout has been defined.
Give a specific location to the component

• Use setBound function


– setBount(x,y, width, height)

• Change the programme accordingly


label1.setBounds(50,50,100,30);
label2.setBounds(50,80,100,30);
Add few more components
//create text fields
JTextField text1 = new JTextField();
JTextField text2 = new JTextField();
JTextField text3 = new JTextField();

//add a button
JButton addButton = new JButton("Add");
JButton clearButton = new JButton("Clear");

//create text boxes


text1.setBounds(180,50,100,30);
text2.setBounds(180,80,100,30); //add components
text3.setBounds(180,110,100,30); frame.add(text1);
frame.add(text2);
//set button bounds frame.add(text3);
addButton.setBounds(60,150,80,30); frame.add(addButton);
clearButton.setBounds(160,150,80,30); frame.add(clearButton);
Event Handling

• Objects have a state.


• Changing the state of an object is known as event.
• Example
– Button click
– Mouse move
– Key stroke
– Change of a text field
– etc.
How are those events been handled in Java?
Event types

• Action Event- user interface element is activated E.g:


selection of menu items
• Item Event - selection or deselection of an itemized or list
element E.g: such as checkbox
• Text Event- triggered when a textfield is modified
• Window Event - window related operation is performed.
E.g.: such as closing or activating a window
• Key Event - whenever a key is pressed on the keyboard
Partners in Event handling

Event Source Event Listener Event Class

Component that generate Contain methods to handle All the Events in Java and
the event. the events which will be event classes associated
informed via event with them.
A component can have notifications.
multiple events Two important methods:
This is from javax.awt.event - getSource()
Example package. - toString()
- Button
- Menu
- Radio button
Partners in Event handling (examples)
Event Listener Listener Method
Action Event ActionListener void actionPerformed(ActionEvent e)
Eg: button press, list item selected
Key Event KeyListener void keyPressed(KeyEvent e)
Eg: input is received from keyboard void keyReleased(KeyEvent e)
void keyTyped(KeyEvent e)
Mouse Event MouseListener void mouseClicked(MouseEvent e)
Eg: mouse is dragged, clicked, void mouseEntered(MouseEvent e)
moved, etc void mouseExited(MouseEvent e)
void mousePressed(MouseEvent e)
void mouseReleased(MouseEvent e)
Item Event ItemListener void itemStateChanged(ItemEvent e)
Eg: check-box or list item is clicked
Text Event TextListener void textValueChanged(TextEvent e)
Eg: text area or text field is changed
Implement Event handling in Java

1. Declare an Even Handler Listener class


2. Implement the function for the Listener class
3. Pass the listener class instance to the component’s
addListener method.
Implement Event handling in Java (for a button)
//event handler
button.addActionListener(

new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(ButtonFrame.this, "You
have clicked the button.");
}
}

);
Display a message
Radio button listener
Radio button listener

• Click of a button will clear the content in the text field

• The background color of the text field will be changed


when a color is selected from the radio buttons.

• Keep the text field as a global components that all other


components can access.
Button listener code
JButton buttonClear = new JButton("Clear");
buttonClear.setBounds(100,300,100,30);
add(buttonClear);
//action Listener for the Button
buttonClear.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
textField1.setText("");
}
}
);
Radio button listener (red color button)
rbRed = new JRadioButton("Red");
rbRed.setBounds(100,100,100,30);
ButtonGroup colorGroup = new ButtonGroup();
colorGroup.add(rbRed);
//radio button listener
rbRed.addActionListener(
new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
textField1.setBackground(Color.red);
}
}
);
Use GUI designer in NetBeans

• You can design the GUI by drag and drop the


components instead of pure coding.
• In NetBeans,
– Right click on the project
– Select New
– Select JFrame Form
– Provide a name to the frame window file and select Finish.
• A simple form without any component will be opened.
Use GUI designer in NetBeans (cont.)

• Drag and drop the components from the tool window.


• Use the property window to change the properties of the
component.
• Click on the Source tab in the design area to view the
code of the GUI.
• The main method in the form java file can be removed as
appropriate.
• Constructor of the GUI class calls InitComponents() to
initialize the frame and the components.

You might also like