**Lecture 2 (LayOut Managers)
component---event--->Listener
(close button)---windowEvent--->WindowListener
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent; // This is the file Ending listener.java
public class EndingListener impements ActionListener
public void actionPerformed(ActionEvent e)
{
System.exit(0)
}
}
To develop a GUI program we need:
1. JFrame = first window ,we can set the width and height
2. JButton
import javax.swing.JFrame;
import javax.swing.JButton;
public class FirstSwingDemo{
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
public static void main(String[] args){
JFrame firstWindow = new JFrame(WIDTH, HEIGHT);
firstWindow.setSize(WIDTH, HEIGHT);
JButton endButton = new JButton("Click to end program");
EndingListener buttonEar = new EndingListener();
endButton.addActionListener(buttonEar);
firstWindow.add(endButton);
firstWindoe.setVisible(true);
}
}
**Text Field
// A text field is an object of the class JTextField
// It allows the user to send a single line of text
e.g.
JTextField text1 = new JTextField("Enter a text");
JTextField text2 = new JTextField("Enter text 2");
// A JTextArea is the same as the JTextField
// The only difference is that it allows for multiple lines .
**Menu
// A menu is an object of the class JMenu.
// A choice on the menu is called an item.
// an item belongs to the class JMenuItem.
e.g.
JMeno menu = new JMenu("Menu");
JMenuItem item1 = new JMenuItem("Item1");
item1.addActionListener(item1);
menu.add(item1);
**Menu Bar
// Is a container for menus
e.g.
JMenuBar bar = new JMenuBar();
bar.add(menu);
**Components of GUI
JButton --- is a button
JLabel ---
JTextField --- text object takes in one line of text
JTextArea --- text object takes in multiple lines of text
JMenu --- contains items / or choices in the menu
JMenuItem --- is a menu choice
JMenuBar --- contains the menus
**Components VS Containers
// components-- serve as ways for the user to interact with the GUI program (JButton, JLabel)
// containers-- hold components (e.g. JFrame, JPanel)
**What a GUI program should have
1. Containers : can have other containers : each container can have its own Layout manager.
2. components
3. layout manager to position the components inside the container
**Layout Managers
// add method adds components to a container but does not specify how
// e.g. to add a layout manager to JFrame name window;
window.setLayout(new BorderLayout());
// BorderLayout manager places the components that are added to the JFrame object into five
regions N,E,W,S and the CENTER.
JFrame window = new JFrame();
window.setLayout(new BorderLayout());
JLabel label1 = new JLabel("First label");
window.add(label1, BorderLayout.NORTH);
JLabel label2 = new JLabel("Second label");
window.add(label2, BorderLayout.SOUTH);
JLabel label3 = new JLabel("Third label");
window.add(label3, BorderLayout.CENTER);
**FlowLayout
// FlowLayout manager arranges components one after the other from left to right.
// if it runs out of space is then moves to the next line.
**GridLayout
// arranges components in a 2D grid with some number of rows and columns
setLayout(new GridLayout(rows, columns));
Each entry is the same size.
Each component is stretched to fit its grid position
Items are filled from left to right top to bottom.
JFrame window = new JFrame();
window.setLayout(new GridLayout(2, 3));
window.add(new JLabel("First label"));
window.add(new JLabel("Second label"));
window.add(new JLabel("Third label"));
window.add(new JLabel("Fourth label")); // goes to the next line
window.add(new JLabel("Fifth label")); // goes to the next line
// GridLayout(0,3) : sets as many rows as required
// GridLayout(2,0): sets as many columns as required
**JPanels
// Panels simply divide the JFrame and groups smaller objects into larger objects(e.g. buttons
into a panel, then panels into a JFrame)
**Action Commands
// setActionCommand()
// setBackground()
**Colors and Fonts
public void actionPerformed(ActionEvent e){
String buttonString = e.getActionCommand();
if (buttonString.equals("Red"))
redPanel.setBackground(Color.RED);
else if (buttonString.equals("White"))
whitePanel.setBackground(Color.WHITE);
else if (buttonString.equals("Blue"))
bluePanel.setBackground(Color.BLUE);
else
System.out.println("Unexpected error.")
**Containers
JFrame
JPanel
**Components
JButton
JLabel
JTextField
JTextField
JMenu
JMenuItem
JMenuBar
**Layout managers
BorderLayout
FlowLayout
GridLayout
// A color is an object of the class Color from the java.awt package.
There are constants in the Color class that represent a number of basic colors
The color of a GUI component can be set with setBackground:
button.setBackground(Color.PINK);
// The JFrame cannot be colored directly.
// You need to instead color the content pane of the JFrame
// The content pane is the inside of the JFrame
// The background color can be set as follows:
frame.getContentPane().setBackground(Color.BLUE);
**Colors
RGB - RED/GREEN/BLUE
// We can create a Color object and specify its values:
Color brown = new Color(200, 150, 0);
// Integer values must be in the range 0-255
Color brown = new Color((float)(200.0/255),(float)(150.0/255),(float)
(0.0/0));
// Float vallues must be in the range 0.0-1.0 inclusive
e.g.
float num1 = 2.5f;
double num2 = 2.5;
float num3 = 2.5; // Won't compile, java thinks decimals are doubles
float num3 = (float)2.5;
**JColorChooser
// The class (JColorChooser) from javax.swing can be used to allow a user to choose a color.
showDialog method of JColorChooser produces a color choosing window.
User can choose a color by selecting RGB values or from a set of color samples
Color sampleColor = JColorChooser.showDialog(frame, "title", initColor);
frame --- GUI object from which dialog window is launched
title --- Window title
initColor --- initially selected color
**Fonts
// A font is from the Font class (from java.awt).
// A constructor creates a font in the given style and size
Font font1 = new Font("SansSerif", Font.PLAIN, SIZE);
// Serif font--- has small lines at the ends of letters
// Sans-Serif--- does not have small lines at the ends of letters
// Font.PLAIN--- Style modifiers (plain, bold, and italic)
**Monospaced
Means that all the characters have equal width
**Window Listeners
// Window Listeners handle events fired by window events
e.g.Events:
Opening
Closing
Minimising
Maximising
Deactivating
Activating
// Window listener is defined as :
public class ClassName implements WindowListener
// This means it has to define seven methods
// But you can have empty bodies for methods you do not need
// A window event is an object of the class WindowEvent , which is passed as an argument to all
seven methods
// The WindowListener interface and the WindowEvent class are in the package java.awt.event
public void windowOpened(WindowEvent e)
//Invoked when a window is opened.
public void windowClosing(WindowEvent e)
//Invoked when close-window button is clicked
public void windowClosed(WindowEvent e)
//Invoked when a window has been closed
public void windowIconified(WindowEvent e)
// Invoked when a window is iconified, when you click the minimize button
in a JFrame
public void windowDeiconified(WindowEvent e)
Invoked when a widow is deiconified , when you activate a minimize
window.
public void windowActivated(WindowEvent e)
//Invoked when a window is activated
public void windowDeactivated(WindowEvent e)
//Invoked when a window is deactivated
// addWindowListener method can register a listener to a JFrame window
JFrame frame = new JFrame();
ExitListener listener= new ExitListener();
frame.addWindowListener(listener);
// setDefaultCloseOperation
if you want the window listener to handle all window behaviour
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
If the method is not called, the following default action will take place
This will hide the JFrame, but not end the program
**Icons
// JLabels, JButton, and JMenuItems can have icons
// An icon is an object of the ImageIcon class.
// It is based on a digital picture such as .gif or .jpg
// ImageIcon class is used to convert a picture file to a Swing icon
ImageIcon wavingIcon = new ImageIcon("waving.gif");
An icon can be added to a label using the setIcon method as follows:
JLabel label = new JLabel("Mood check");
labelsetIcon(icon);
// Icons and text may be added to Jbutton and JMenuItem in the same way as they are added
to a JLabel.
JButton happyButton = new JButton("Happy");
ImageIcon happyIcon = new ImageIcon("smiley.gif");
happyButton.setIcon(happyIcon);
// Insets : object of the class insets are used to specify the size of the margin in a button or
menu item.
// arguments given are in Pixels
public Insets(int top, int left, int bottom, int right);
**Scroll Bars
// When a text area is created, the number of lines that are visible and the number of characters
per line are specified as follows:
JTextArea area = new JTextArea(15, 30);
In order to combat this we can use scroll bars with the text area.
// When a JScrollPane is created, the text area to be viewed is given as an argument.
JTextArea area = new JTextArea(15, 30);
JScrollPane scrolled = new JScrollPane(area);
// The JScrollPane can be added to a container, such as JPanel or JFrame.
panel.add(scrolled);
// Scroll bar policies:
scrolled.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS)
;
scrolled.setHorizontalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AWLAYS);
Swing Inheritance and Graphics
// First a general form of a class is defined and compiled(Base class/parent class)
// Then more specialized forms of the class are created(Derived/child class)
they inherit methods and instance variables from base class.
// A better way to define a swing window is to make it a derived class of the JFrame, this is a
normal way to deine a windowing interface.
e.g.
public class LoginWindow extends JFrame
public class ExitWindow extends JFrame
public class HomePage extends JFrame
// super() --- calls the parent constructor class
**The graphics class
Every container and component that can be drawn on the screen has an associated
Graphics object.
The object has date specifying the area of the screen covered by the component.
E.g. the Graphics object for a JFrame specifies drawing takes place inside the window
borders.
// Java has a drawing coordinate system where the origin point (0,0) is at the upper left corner
of the drawing area.
// Units and sizes are in Pixels
// When drawing the imaginary upper left corner that a shape is in is specified
// Swing components have an already defined method called paint.
The method draws the component or container on the screen.
public void paint(Graphics g){}
// When the paint method is invoked , g is replaced by the Graphics object associated with the
JFrame
// When redefined, always include super.paint(g)
// Object g can be used as the calling object for drawing
g.drawOval(...);
g.drawRect(...);
g.drawLine(...);
HOW RO REDEFINE THE paint Method
public void paint(Graphics g){
super.paint(g); // Step 1: Invoke the parent constructor
// Step 2: Invoke drawing methods
g.drawOval(...);
g.drawRect(...);
g.drawLine(...);
}