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

Referencing other classes in classes(1)

Uploaded by

chumbucket2050
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Referencing other classes in classes(1)

Uploaded by

chumbucket2050
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Referencing other classes in classes

Assume that we have to write a class DataSet for BankAccount objects.


A DataSet object has to add BankAccount objects one by one, and to
output the reference to a BankAccount object with max balance.
We will keep track of the sum total of all accounts, just for an example
public class DataSet
{ ...
public void add(BankAccount x)
{ sum = sum + x.getBalance(); it searches for object x with
a type of BankAccount and gets it balance (getbalance is a
method for BankAcc class)
if (count == 0 || max.getBalance() < x.getBalance())
max = x; It checks first variable count and if its
empty then obviously there was no balances so the first added
balance will be the max one for now but if there is already more
balances then it gets the value of max and checks if current
object’s value is bigger than max and changes it inot max if so
count++;
}
public BankAccount getMaximum()
{ return max; } function that expects to return the
maximum of the type of BankAccount
private double sum;
private BankAccount max;
private int count;
}

Interface
● An interface is a named collection of abstract methods (methods without
implementations), and constant declarations.
● An interface is not a class. → You cannot create variables of an interface.
● Instead, a class implements an interface.
● When a class implements an interface, it does two things.
o Promises to provide bodies for all the functions that interface defines.
o Gets the variables described by the interface for free.
● Note that in an interface:
o All the methods are abstract; that is, they have a name, parameters, and
a return type, but they don’t have anything inside them.
o All the methods are implicitly public.
o All data declarations are implicitly constant declarations. i.e., public static
final. This implies that instance fields cannot be declared in interface.
o interfaces are not classes; i.e., they cannot be instantiated. Thus, the line
Measurable x = new Measurable (); is a mistake!
public class ClassName implements InterfaceName {}

Casting
Type converting: interface to class

You need to do this cuz interface lets you have max variable for multible
classes – it can be maximum for coin or for BankAccount
Risks of casting is that there is risk of losing information like int x = (int)
2.4 and when we try to cast object type into type that is not an object (in
that case we use instanceof -> if(x instanceof Coin) {}

Generics
-We can create class with not yet known type during the creation of
class for example Arraylists use generics to know what type of objects it
contains
-We declare said class like this: public class A<T>, later the <T> will
be replaced with the type when

instance is created

Polymorphism
We can reference objects that are “below” superclass in herarchy
In polymorphism we can point down but we cannot point up
Person p = new Graduate();#Correct
Staff s = new Person(); #NOT correct
● When can call methods, only if the
reference type has them.
○ Assume Graduate has method
getDegree();
○ We can’t do p.getDegree();
because Person doesn't have it.
● If we call a method and the actual object overrides it, we will perform the
lowest override.
○ Assume Person and Student have function payRent();
○ If we call p.payRent(); we will perform payRent of Student because
that’s the lowes override we found.

Casting:
● We can cast objects from superclass references to subclass reference
type, this lets us call methods of the subclass.
○ ((Graduate)p).getDegree(); is correct.
● When casting we dont know the type of object before running the code,
so we might cast to things we are not allowed to.
○ (Employee)P will not tell us there is a problem when we write it
because Employee inherits from Person, but when running, p is not actually
an Employee, so we will get an exception.
● Prevent this by checking the type before casting with:
○ if(p instanceof Employee)

Final modifier

Processing timer
events
javax.swing.Timer object
generate timer “events” at
fixed intervals
When a timer event occurs, the Timer object needs to notify some object
called an event listener;
The class of the event-listener object must implement the ActionListener
interface
To create a listener you write this

MyListener listener = new MyListener();


Timer t = new Timer(interval, listener);
t.start();
Timer t calls the actionPerformed method of
the listener object every interval
milliseconds!

Processing timer events


The full code of timer event example will be
public class TimerTest
{ public static void main(String[] args)
{ class CountDown implements ActionListener
{ public CountDown(int initialCount)
{ count = initialCount; }
public void actionPerformed(ActionEvent event)
{ if (count >= 0)
System.out.println(count);
if (count == 0)
System.out.println("Liftoff!");
count--;
} you specify in initialcount how long it will countdown for
and the timer decreases this count. Every timeframe it will print the
amount of counts left and decreases it by one and when it equals 0 it will
print “Liftoff!”
private int count;
}
CountDown listener = new CountDown(10);
final int DELAY = 1000;
Timer t = new Timer(DELAY, listener);
here you start the countdown -> it will count down 10 times and
delay is 1000 and since it counts ticks in milliseconds then the delay
between all countdowns will be 1 second
t.start();
}
}
Lecture 5
Layout Management
The most useful layout managers flow layout, border layout, grid layout

JFrame and JPanel


JFrame is used to create stand alone apps like an alert window
JPanel is mostly considered container, is used in more complex apps so it
requires usually further groupings
Flow layout – Row layout from left to right
Border Layout – Groups objects into northe, west, east, south and center

containers
Grid layout – it will create a grid, the rows and columns are defined
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 3));
buttonPanel.add(button1);
buttonPanel.add(button2);
buttonPanel.add(button3);
buttonPanel.add(button4);
...

Components in swing
JLabel – creates a label
Can display text and images.
JLabel label = new JLabel(“TEXT”);
label.setText(“New Text”);
label.getText();
label.setForeground(Color.GREEN);
JButton – creates a button
Buttons trigger events when they are clicked.
JButton button = new JButton(“Text on button”);
button.addActionListener(new MyActionListener);
button.setText(“new text”);
button.setEnabled(<boolean>); #makes it so the button is/isn’t active
JTextField
Provides the user an area to type text.
JTextField field= new JTextField(“Initial text”);
field.getText(); #returns the current text in the text area
field.addActionListener(new MyActionListener()); #listener triggers
when textField is clicked not when text changes
JRadioButton – creates a radio button
Use if you want to select only one choice at a time.
JRadioButton smallButton = new JRadioButton(“Small”); #make a new
radio button
JRadioButton largeButton = new JRadioButton(“Large”);
ButtonGroup group = new ButtonGroup(); #make a new button group.
You can only
check one button from the group.
group.add(smallButton); #add the button to the group
group.add(largeButton); #Add the radio button to the group
if (largeButton.isSelected()) {} #check if the button is clicked

JCheckBox – creates a check box


It has two states: checked and unchecked.
JCheckBox italicBox = new JCheckBox("Italic");
If you want to check for whether the checkbox is selected or not you
can do it this way:
if (italicBox.isSelected()) {}
JComboBox – creates a combo box ( a list field)
With combo boxes, you can present a list of choices. If it’s editable you
can add your own text as well. (2in1list and text field)
JComboBox combo = new JComboBox();
combo.addItem("Serif");
combo.addItem("SansSerif");
To get the currently selected item:
String select = (String) combo.getSelectedItem();
JMenu – creates a menu
Top-down menu. You can add submenus to menu points as well.
JMenuBar menuBar = new JMenuBar(); #make new menu bar
setJMenuBar(menuBar); #add menubar to the frame
JMenu newMenu = new JMenu(“NewMenuPoint”); #make new menu point
menuBar.add(newMenu); #add menu point to menu bar
JMenu newSubMenu = new JMenu(“NewMenuPoint”); #make new submenu
point
newMenu.add(newSubMenu); #add submenu point to menu point
When the user presses the menu item sends an action event. You can add a
listener to it:
ActionListener listener = new ExitItemListener();
exitItem.addActionListener(listener);

Events
Java swing has some pre-made event listener interfaces which you can
implement in a class to make your own listeners.
MouseListener: Used to get information from the mouse
import java.awt.event.*;
class MouseSpy implements MouseListener{
public void mousePressed(MouseEvent event){ #when the mouse is
presses on a component
System.out.println("Pressed! x=" + event.getX() + " y=" +
event.getY());
}
public void mouseReleased(MouseEvent event){} #when the mouse
is released on a component
public void mouseClicked(MouseEvent event){} #when the mouse is
clicked
public void mouseEntered(MouseEvent event){}#when the mouse
enters a component
public void mouseExited(MouseEvent event){} #when the mouse
exits a component
}
To use a MouseListener you need to add it to the frame:
MouseSpy listener = new MouseSpy();
frame.addMouseListener(listener);
ActionListener: Action listeners are used to to listen for events from sources.
To create a listener, create a class implementing ActionListener, and
override the actionPerformed method:
public class MyListener implements ActionListener{
public void actionPerformed(ActionEvent e){
//Do something
}
}
To use it, you need to add it to the source:
JButton b = new JButton (“Click me please”);
MyListener listener = new MyListener();
b.addActionListener(listener);

Graphics and GUI


We create this in swing (see the pic on the next page)

Drawing shapes
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;

public class RectangleComponent extends JComponent{


public void paintComponent(Graphics g){
// Recover Graphics2D
Graphics2D g2 = (Graphics2D) g;
// Construct a rectangle and draw it
//Rectangle box = new Rectangle2D(x, y, width, height);
Rectangle box = new Rectangle2D(5, 10, 20, 30);
g2.draw(box);
//Move rectangle 15 units to the right and 25 units down
box.translate(15, 25);
g2.draw(box);
}
}
^That’s how you create a gui

Main drawing funtions in swing


Shapes:
●Rectangle2D.Double box = new Rectangle2D.Double
(x,y,width,height)
● Line2D.Double line = new Line2D.Double (x1,y1,x2,y2)
● Ellipse2D.Double ellipse = new
Ellipse2D.Double(cornerX, cornerY, width, height);
● Point2D.Double point = new Point2D.Double(x, y);
Strokes (You can change the color and thickness of lines.):
g2.setColor(Color.magenta);
g2.setStroke(new BasicStroke(4.0F)),
Text:
g2.drawString(String s, float x, float y);
Color:
Color newColor = new Color(float red, float green, float
blue);

You might also like