OOPsheet
OOPsheet
Coding examples
Vocabulary
OOP Keyword
This
Super
Overwriting toString()
Overwriting equals()
MouseListener
Reading input in window
TextArea
Action Listener
Layout and Buttons
Methods for buttons and labels
Example of GridLayout and BorderLayout
Example with ComboBox
Example with Radio Button
Presenting Button Groups
Example Check Boxes
Menu
Timer
Java FX
JavaFX example
JavaFX Media
Exception Handling
Streams
Object Streams
Python (Theory)
Coding examples 1
Vocabulary
OOP Keyword
This
Doctor doctor;
Patient patient;
private double amountDue;
Super
super means that we are talking about the variable not from the class we are in, but from the class with inherit, so one level
above the class we're in -
Overwriting toString()
Usefull when we have variables that are not Strings, and we want to put them into a big String, to present information
public String toString() { //when we want to make the Age and Name which are objects into a String
return getClass().getName() +
"[name = " + name + " ]" + "\n" + "[age = " + age + " ]" + "\n" + "[specialty " + specialty + "]" + "\n" + "[office Visit Fee
}
private String a;
public String toString() {
a = "";
for(int i = 0 ; i<BillStorage.size();i++){
a += BillStorage.get(i).toString() + "\n";
}
return a;
}
Overwriting equals()
Coding examples 2
}
Doctor other = (Doctor) otherDoctor;
return super.equals(other) && specialty.equals(other.specialty) && officeVisitFee == other.officeVisitFee;
}
MouseListener
import javax.swing.JOptionPane;
class ReadingInput {
public static void main(String[] args) {
String input = JOptionPane.showInputDialog("Introduce a number (int)");
//conversing the String into a number
int count = Integer.parseInt(input);
[…]
System.out.print("The number introduced is " + count);
}
}
TextArea
Coding examples 3
• To set the font of a text area use: setFont(Font f)
• To add scroll bars create a JScrollPane object with constructor parameter the reference of the JTextArea
object.
import javax.swing.*;
import java.awt.event.*;
public class TextAreaTest {
public static void main(String[] args) {
Action Listener
public static void main(String[]args){
LoginManager manager = new LoginManager();
JPanel panel = new JPanel();
frame = new JFrame();
frame.setSize(400,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
panel.setLayout(null);
Coding examples 4
frame.setVisible(true);
}
// public static boolean loggedIn = true;
if(!LoggedInSuccess){
LoginAccess.setText("You have made "+ NbAttemptMade+ ".");
if(NbAttemptMade>=3){
JOptionPane.showMessageDialog(frame, "You don't have attempts left !", "Closing window", JOptionPane.ERROR_MESSAGE
frame.dispose();
}
}
else{
JOptionPane.showMessageDialog(frame, "You logged in !", "Loggin window", JOptionPane.ERROR_MESSAGE);
frame.dispose();
}
}
}
AttemptMade++;
if(AttemptMade>3){
return false;
}
for(int i = 0 ; i<userStorage.length ; i++){
if(userStorage[i].equalsIgnoreCase(userName)){
if(passwordStorage[i].equals(password))
return true;
else{
return false;
}
}
}
return false;
}
Coding examples 5
Same for JLabel, just methods SetBounds in addition
static JFrame f;
static JLabel l, l1;
static JComboBox c1;
f = new JFrame("frame");
solve s = new solve();
f.setLayout(new FlowLayout());
String s1[] = { "Jalpaiguri", "Mumbai", "Noida", "Kolkata", "New Delhi" }
c1 = new JComboBox(s1);
c1.addItemListener(s);
l = new JLabel("select your city ");
Coding examples 6
l1 = new JLabel("Jalpaiguri selected");
l.setForeground(Color.red);
l1.setForeground(Color.blue);
JPanel p = new JPanel();
p.add(l);
p.add(c1);
p.add(l1);
f.add(p);
f.setSize(400, 300);
f.show();
}
public void itemStateChanged(ItemEvent e)
{
// if the state combobox is changed
if (e.getSource() == c1) {
l1.setText(c1.getSelectedItem() + " selected");
}
}
}
use IsSelected() ;
static JFrame f;
public static void main(String[] args)
{
f = new JFrame("frame");
f.setLayout(new FlowLayout());
p.add(c1);
p.add(c2);
f.add(p);
f.setSize(300, 300);
Coding examples 7
f.show();
}
}
Menu
public JMenuItem createItem(final String name) {
// Global variables can be accessed from an inner class method
private JLabel label;
class MyItemListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
newName = name;
setNewText();
}
}
JMenuItem item = new JMenuItem(name);
ActionListener listener = new MyItemListener();
item.addActionListener(listener);
return item;
}
public void setNewText() {
label.setText(newName);
}
Timer
public class Test {
public static void main(String [] args) throws Exception{
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
Thread.sleep(5000);
}
}
Java FX
Swing has been around for quite some time with the same purpose of
providing UI needs of Java
• Swing offers excellent flexibility and capability in creating a GUI
• Swing classes are not built to leverage graphical hardware
components. This reduces performance and lacks efficiency when
dealing with complex graphics
• JavaFX brought a fresh new UI framework as a complete UI library
Coding examples 8
layouts
• Some common layouts are:
javax.scene.layout.Hbox: Lays out UI controls within a horizontal box
javax.scene.layout.Vbox: Lays out UI controls within a vertical box
javax.scene.layout.FlowPane: UI controls are arranged in a flow that wraps at the flow
pane interior
javax.scene.layout.BorderPane: UI controls are laid out in the left, top, right, bottom,
and centre position of the scene
javax.scene.layout.GridPane: Lays out UI controls in a tabular fashion, in grids of rows
and columns
JavaFX example
root.setCenter(gridpane);
stage.setScene(scene);
stage.show();
}
public static void main
(String[] args){
launch(args);
}
}
JavaFX Media
The JavaFX media API enables a developer to incorporate audio and
video capabilities into a Java application
• The Media API is designed to be cross platform; that means
multimedia content can be implemented in an equivalent manner
while coding across multiple devices (tablet, media player, TV, etc.)
• The MediaPlayer class provides the controls for media playing but
does not provide any view
• A view can be realized with the help of MediaView
}
public static void main
(String[] args){
launch(args);
}
}
Coding examples 9
Exception Handling
More specific exceptions must be placed before more general ones
Coding examples 10
BufferedReader bufferedReader = new BufferedReader(streamReader); //reading the file
while((line = bufferedReader.readLine())!=null){
lines++;
String wordsStore[] = line.split("\\s+");
words += wordsStore.length;
chars += line.length();
}
streamReader.close();
}catch(IOException e, ){
e.printStackTrace();}
/*
*Throws is when the method just says that there is an exception, but chooses not to do anything about it
*We will see here all the different cases of exception handling
*/
//Method just says that there is exception, but does nothing about it, so the part of the code which calls the method will have to
public static void testException(int a) throws Exception{
if (a<0){
throw new Exception("input is negative");
}
System.out.println("good input");
}
//Methods which deals with the exception generated in the testException method
public static void test2(int a){
try{
testException(a);
}catch(Exception e){
e.printStackTrace();
}
}
//Method which completely deals with its exception, can be called as such, no need to deal with exception
public static void test4(int a){
try{if (a<0){
throw new Exception("input is negative");
}}catch(Exception e){
e.printStackTrace();
}
}
//Methods which will cause an exception because call a method which cause an exception which is not handled
public static void test5(int a) throws Exception{
testException(a);
}
}
}
Coding examples 11
Streams
public void openProcessFile() {
ArrayList<Product> result = new ArrayList<Product> ();
try(Scanner in = new Scanner(new FileReader(fileName));
{ // select file name
result = readProducts(in);
...
}
catch(FileNotFoundException e)
{ System.out.println("Bad file name");}
catch(IOException e)
{ System.out.println("Corrupted file");}
}
}
}
}
Scanner scanner = new Scanner(new FileReader(file)); //if we don't find file, throw exception
String target = word;
while(scanner.hasNext()){
String line = scanner.nextLine();
if(line.contains(target)){
storage.add(line);
}
}
}catch(FileNotFoundException e){
e.printStackTrace();
return null;
}
Object Streams
Employee e = new Employee("John", 20000);
ObjectOutputStream out = new ObjectOutputStream
(new FileOutputStream("e.dat"));
out.writeObject(e);
Python (Theory)
Coding examples 12
Python is Interpreted
• Python is processing at runtime by the interpreter. You do not need to
compile your program before executing it
Python is Interactive
• You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs
Python is Object-Oriented
• Python supports Object-Oriented style or technique of programming that
encapsulates code within objects
Some similarities:
– “(Almost) everything is an object”
– Reputation for excellent cross-platform support
– Standard libraries (Python scores over Java)
Some differences:
– Indentation vs semicolon
– Duck typing
o Very easy to write and not too bad to read BUT difficult to analyse
– User-defined operator overloading
– Automatic compilation vs javac
– Interpreted (slower)/compiled (runs in a virtual machine)
o There are compilers for Python (Jyphon, Cython, etc.)
2. Strings
3. Lists
5. Dictionaries : list but instead of having index for each element, we have keys
Operations on List :
Coding examples 13
print(list[-1]) # Prints the last element
[70.2]
It is possible to have combination of basic data types, such as lists of tuples for example #
Explaination : when using in range(x,y), it actually creates a list storing the value from x to y that we gave
Coding examples 14