TCP2201 Object-Oriented Analysis and Design
TCP2201 Object-Oriented Analysis and Design
• Containers
• holds components in a specific layout
• can hold other containers/components
• divided into 2: top-level and secondary-level containers
• Top-level containers – frame and dialog are most
common (equivalent JFrame and JDialog)
• Secondary-level containers – placed INSIDE top level
containers or another secondary container. Most common
are Panel and ScrollPane (equivalent JPanel,
JScrollpane)
• Extends javax.Swing.* and java.event.*
• Makes use of a container class – components are placed inside
the container based on a layout.
• With the container, GUI applications are standalone programs
that, by default, has a window (with size, border, location etc),
titlebar, control section, menu/tool bar (optional) , content area
and statusbar
• Typical containers and components are shown below (AWT
versions)
• Provides main standalone window for a Java GUI application
• Because it is an application, a JFrame needs the main() in your
code to run (same with JDialog)
• Has title bar with controls, optional menu bar and content area
• Needs a size!
• Common JFrame constructors
public JFrame()
public JFrame(String title)
public JFrame(GraphicsConfiguration gc)
public JFrame(String,GraphicsConfiguration)
• JFrame objects are ALWAYS invisible during declaration. To show
on screen use the setVisible method.
Ref: http://docs.oracle.com/javase/7/docs/api/java/awt/Frame.html
https://docs.oracle.com/javase/tutorial/uiswing/components/frame.html
import javax.swing.*;
public Test(){
super("This is a frame");
setSize(300,300);
setVisible(true);
setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]){
Test m = new Test();
}
}
Ref: http://docs.oracle.com/javase/7/docs/api/javax/swing/JPanel.html
http://docs.oracle.com/javase/7/docs/api/javax/swing/JScrollPane.html
• Classes of ready made and reusable GUI components
• AWT includes Button, TextField, Label, CheckBox,
CheckBoxGroup(radio), List and Choice these are the ones
you need to know and are most common anyways
• All components shown below need the java.awt.* package
Ref: http://docs.oracle.com/javase/7/docs/api/java/awt/Label.html
http://docs.oracle.com/javase/7/docs/api/javax/swing/JLabel.html
• This class creates a labeled button which triggers an action
depending on state –normal (non-pushed), highlighted and
pushed.
• Requires ActionEvent to capture event that occurs towards the
button – else the button does nothing and is for show only
• Two constructors for Button
public Button(String btnlbl);
public Button();
• JButton has additional constructors, e.g.
public JButton(Icon icn);
public JButton(String btnlbl, Icon icn);
• Syntax example
JButton aButton = new JButton("Push me");
Ref: http://docs.oracle.com/javase/7/docs/api/java/awt/Button.html
http://docs.oracle.com/javase/7/docs/api/javax/swing/JButton.html
import javax.swing.*;
Ref: http://docs.oracle.com/javase/7/docs/api/java/awt/Checkbox.html
http://docs.oracle.com/javase/7/docs/api/javax/swing/JCheckBox.html
add(new JCheckBox("one", true));
add(new JCheckBox("two"));
add(new JCheckBox("three"));
setSize(300,150);
setVisible(true);
Ref:http://docs.oracle.com/javase/7/docs/api/java/awt/CheckboxGroup.html
for (int i=0;i<2;i++){
CheckboxGroup cbg = new CheckboxGroup()
Checkbox cbox = new Checkbox("Check "+i,cbg,false);
add(cbox);
}
Ref:https://docs.oracle.com/javase/7/docs/api/javax/swing/JRadioButton.html
• Alternative to radio buttons is to use choice - allows for selection
of a single option but saves space compared to radio buttons.
• Choice constructor
public Choice()
• Syntax example
Choice colorOption = new Choice();
colorOption.add("Blue"); // accepts String only
• Swing replaces choice with JComboBox
• Syntax example
String[] petStrings = { "Bird", "Cat", "Dog"};
JComboBox pList = new JComboBox(petStrings);
Ref: http://docs.oracle.com/javase/7/docs/api/java/awt/Choice.html
http://docs.oracle.com/javase/7/docs/api/javax/swing/JComboBox.html
Choice nc = new Choice();
nc.add("Blue");
nc.add("Red");
nc.add("Green");
add(nc);
Ref: http://docs.oracle.com/javase/7/docs/api/java/awt/TextArea.html
String sample = new String("Lorem ipsum dolor sit amet.....");
TextArea ta = new TextArea(sample, 4,30);
add(ta);
(rows,columns)
setLayout(new GridLayout(1,3));
setLayout(new GridLayout(0,5));
When both the number of rows and the number of columns have been set to
non-zero values, either by a constructor or by the setRows and setColumns
methods, the number of columns specified is ignored.
Instead, the number of columns is determined from the specified number of
rows and the total number of components in the layout.
setLayout(new BorderLayout());
add(new Button("North"), BorderLayout.NORTH);
add(new Button("South"), BorderLayout.SOUTH);
add(new Button("East"), BorderLayout.EAST);
add(new Button("West"), BorderLayout.WEST);
add(new Button("Center"), BorderLayout.CENTER);
import java.awt.*;
public FrameDemo(){
super("This is a frame");
setSize(300,150);
setVisible(true);
}
public static void main(String args[]){
FrameDemo m = new FrameDemo();
}
}
• Add in listener we want (this example tracks mouse movement)
AND event handling package
import java.awt.*;
import java.event.*;
public class FrameDemo extends Frame implements
MouseListener{
public FrameDemo(){
super("This is a frame");
setSize(300,150);
setVisible(true);
}
public static void main(String args[]){
FrameDemo m = new FrameDemo();
}
}
• Override all abstract methods from interface class (add them all in!)
import java.awt.*;
import java.awt.event.*;
public class FrameDemo extends Frame implements MouseListener{
public FrameDemo(){
super("This is a frame");
setSize(300,150);
setVisible(true);
}
public static void main(String args[]){
FrameDemo m = new FrameDemo();
}
public void mouseClicked(MouseEvent evt){};
public void mouseExited(MouseEvent evt){};
public void mouseReleased(MouseEvent evt){};
public void mousePressed(MouseEvent evt){};
public void mouseEntered(MouseEvent evt){};
}
• Override the abstract methods we want to use
import java.awt.*;
import java.awt.event.*;
public class FrameDemo extends Frame implements MouseListener{
public FrameDemo(){
super("This is a frame");
setSize(300,150);
setVisible(true);
}
public static void main(String args[]){
FrameDemo m = new FrameDemo();
}
public void mouseClicked(MouseEvent evt){};
public void mouseExited(MouseEvent evt){
setBackground(Color.white);};
public void mouseReleased(MouseEvent evt){};
public void mousePressed(MouseEvent evt){};
public void mouseEntered(MouseEvent evt){
setBackground(Color.red);};
}
• Add the trigger to the component
import java.awt.*;
import java.awt.event.*;
public class FrameDemo extends Frame implements MouseListener{
public FrameDemo(){
super("This is a frame");
setSize(300,150);
setVisible(true);
addMouseListener(this);
}
public static void main(String args[]){
FrameDemo m = new FrameDemo();
}
public void mouseClicked(MouseEvent evt){};
public void mouseExited(MouseEvent evt){
setBackground(Color.white);};
public void mouseReleased(MouseEvent evt){};
public void mousePressed(MouseEvent evt){};
public void mouseEntered(MouseEvent evt){
setBackground(Color.red);};
}
public class FrameDemo extends Frame implements MouseListener{
Label nl = new Label("This is a label");
public FrameDemo(){
setLayout(new FlowLayout());
add(nl);
setSize(300,150);
setVisible(true);
addMouseListener(this);
}
public static void main(String args[]){
FrameDemo m = new FrameDemo();
}
public void mouseClicked(MouseEvent evt){
int x = evt.getX();
int y = evt.getY();
nl.setText("Clicked: " + x + "," +y);
};
public void mouseExited(MouseEvent evt){};
public void mouseReleased(MouseEvent evt){};
public void mousePressed(MouseEvent evt){};
public void mouseEntered(MouseEvent evt){};
}
• Keyboards cannot move so they only have one interface class for
events
• Keyboard events are triggered whenever the keyboard is used
(does not have to be within a component like a text field)
• Useful for handling events in applications with no discrete
components for keyboard to interact with (e.g. games)
• KeyEvents
public void keyPressed(KeyEvent e){};
public void keyReleased(KeyEvent e){};
public void keyTyped(KeyEvent e){};
import java.awt.*;
import java.awt.event.*;
public class FrameDemo extends Frame implements KeyListener{
Label nl = new Label("This is a label");
public FrameDemo(){
super("This is a frame");
setLayout(new FlowLayout());
add(nl);
setSize(300,150);
setVisible(true);
addKeyListener(this);
}
public static void main(String args[]){
FrameDemo m = new FrameDemo();
}
public void keyPressed(KeyEvent evt){
int keyPressed=evt.getKeyCode();
nl.setText("Key = "+(char)keyPressed);
}
public void keyReleased(KeyEvent evt){};
public void keyTyped(KeyEvent evt){};
}
• Makes use of a set of Listeners ActionListener, ItemListener,
and AdjustmentListener - each for a specific task
• ActionListener 'listens' for actions like button presses and
textfield changes
• ItemListener 'listens' for actions like selections and
check/uncheck operations on multiple items (lists, choices,
checkboxes)
• AdjustmentListener 'listens' for actions on scrollbars
• How to use?
• implement the interface class ActionListener, ItemListener
and/or AdjustmentListener to your class
• Attach a source trigger to a component (i.e. addActionListener,
addItemListener, addAdjustmentListener)
• override ALL methods from interface class
• capture event (ActionEvent, ItemEvent, AdjusmentEvent)
• perform operation against event captured
• Some events can be triggered by the component themselves (e.g.
similar to the mouseEntered, mouseExited previously) and can
also be captured
• Example: Button also has mouseEntered and MouseExited
triggers which can be used to highlight mouse overs
• Works on buttons, fields etc.
• To use, implements ActionListener in the program code
• Add the ActionListener to the object to which an event will be
triggered
• Overload all abstract methods from ActionListener in program
code (i.e actionPerformed)
• Handle the triggered event in the chosen method
import java.awt.*;
import java.awt.event.*;
public class FrameDemo extends Frame implements ActionListener{
private Button btnCount;
public FrameDemo(){
setLayout (new FlowLayout());
btnCount = new Button("Close");
add(btnCount);
setSize(300,150);
setVisible(true);
btnCount.addActionListener(this);
}
public static void main(String args[]){
FrameDemo m = new FrameDemo();
}
public void actionPerformed(ActionEvent evt){
System.exit(0);
}
}
• What if multiple buttons declared under one identifier?
for (int i=0;i<3;i++){
Button btnarray = new Button("Button "+i);
add(btnarray);
btnarray.addActionListener(this);
}
• Use method to extract button details
public void actionPerformed(ActionEvent evt){
String btn=evt.getActionCommand();
if (btn.equals("Button 0"))
System.exit(0);
else if (btn.equals("Button 1"))
lbl.setText("Button 1 pressed");
else if (btn.equals("Button 2"))
lbl.setText("Button 2 pressed");
else if (btn=="Close")
System.exit(0);
}
• This slide mostly references any code using pure AWT
• The close button on the title bar on applications cannot be
referenced as a object.
• Java has prepared methods to anticipate actions such as closing
the window using the [ X ] button
• To use, add a window listener to the main container to listen when
an exit event is triggered
addWindowListener(new ExitListener());
• Handle the event when it occurs by overriding the ExitListener
public class ExitListener() extends WindowAdapter{
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
• Similar method of implementing listeners – just different interface
classes and methods to override and on different components
• Not all components will work correctly with listeners (e.g. you
cannot addActionListener to a Frame)
Ref: http://docs.oracle.com/javase/7/docs/api/java/awt/event/ItemListener.html
http://docs.oracle.com/javase/7/docs/api/java/awt/event/AdjustmentListener.html
• Newer way to do Java GUIs
• You are allowed to use JavaFX if you want.
• Tutorial available at
https://docs.oracle.com/javafx/2/get_started/jfxpub-
get_started.htm
• There is no main()
• public class MainActivity extends AppCompatActivity
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.myfirstapp.MainActivity">
<EditText
android:id="@+id/editText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="@string/edit_message" <Button
android:inputType="textPersonName" android:id="@+id/button"
app:layout_constraintLeft_toLeftOf="parent" android:layout_width="wrap_content"
app:layout_constraintTop_toTopOf="parent" android:layout_height="wrap_content"
app:layout_constraintRight_toLeftOf="@+id/button" android:text="@string/button_send"
android:layout_marginLeft="16dp" /> app:layout_constraintBaseline_toBaselineOf="@+id/editText"
app:layout_constraintLeft_toRightOf="@+id/editText"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp" />
</android.support.constraint.ConstraintLayout>
• Kept in strings.xml for easy translation without needing to access
the source code.
<resources>
<string name="app_name">My First App</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</string>
</resources>
• What you need to do on your own
• Try out all the code examples shown today on your own
• Refer to the online documentation at
https://docs.oracle.com/javase/8/docs/api/index.html?javax/swi
ng/package-summary.html
• Read up on the listeners
• Swing tutorial at https://docs.oracle.com/javase/tutorial/uiswing/
• JavaFX tutorial at
https://docs.oracle.com/javafx/2/get_started/jfxpub-
get_started.htm
NOTE: The content in this set of slides is
NOT ENOUGH to cover the entire content
of Java GUI/event programming .
You MUST put in your own effort to
research other methods not covered here
that WILL come out during exams OR are
required in your assignment