0% found this document useful (0 votes)
57 views14 pages

OOPsheet

The document provides a comprehensive overview of various Java programming concepts, including object-oriented programming keywords, event handling, GUI components, and JavaFX. It includes coding examples for inheritance, mouse listeners, action listeners, layout management, and exception handling. Additionally, it discusses the differences between Swing and JavaFX, highlighting the advantages of JavaFX for modern UI development.

Uploaded by

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

OOPsheet

The document provides a comprehensive overview of various Java programming concepts, including object-oriented programming keywords, event handling, GUI components, and JavaFX. It includes coding examples for inheritance, mouse listeners, action listeners, layout management, and exception handling. Additionally, it discusses the differences between Swing and JavaFX, highlighting the advantages of JavaFX for modern UI development.

Uploaded by

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

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

A extends B : A inherits from B : INHERITANCE

A implements B : A uses the interface B : INTERFACE

OOP Keyword
This

public class Bill {

Doctor doctor;
Patient patient;
private double amountDue;

public Bill(Patient patient, Doctor doctor){


this.patient = patient; Giving the variable of the input to the instance of the class
amountDue = doctor.getOfficeVisitFee();
}

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 -

public class Doctor extends Person {


String specialty;
double officeVisitFee;

public Doctor(String name, int age, String specialty, double officeVisitFee) {


super(name, age); we take the variable from the constructor from Person
this.specialty = specialty;
this.officeVisitFee = officeVisitFee;
//TODO Auto-generated constructor stub
}

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()

public boolean equals (Object otherDoctor){


if (otherDoctor == null){
return false;
}
if (getClass() != otherDoctor.getClass()){
return false;

Coding examples 2
}
Doctor other = (Doctor) otherDoctor;
return super.equals(other) && specialty.equals(other.specialty) && officeVisitFee == other.officeVisitFee;
}

MouseListener

public class MouseComponent2 extends JComponent


{ private int x = 20,y = 20;
public MouseComponent2()
{
class MousePressListener implements MouseListener
{ public void mousePressed(MouseEvent event)
{ x = event.getX();
y = event.getY();
repaint();// repaints the applet
}
public void mouseReleased(MouseEvent event) {}
public void mouseClicked(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
}
MouseListener listener = new MousePressListener();
addMouseListener(listener);
}
public void paintComponent(Graphics g)
{ Graphics2D g2 = (Graphics2D)g;
g2.drawString("Leaaaa", x, y);
}
}
-----------------------------------------------------------
public class MouseFrame2
{
public static void main(String[] args)
{ MouseComponent2 comp = new MouseComponent2();
JFrame frame = new JFrame();
frame.add(comp);
frame.setSize(500, 500);
frame.setVisible(true);
}
}

Reading input in window

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

To construct a text area use the JTextArea class ;


• To construct a text area with n rows and m columns use the constructor: JTextArea (int n, int m)
‒ To append a string to a text area use the method append(String str) that appends the given text to the end of the text area.
• To (dis)allows the user to edit a text area use the methods: setEditable(boolean flag)

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) {

BankAccount account = new BankAccount(1000);


JTextArea textArea = new JTextArea(10, 30);
JScrollPane scrollPane = new JScrollPane(textArea);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane);
frame.setSize(200, 100);
frame.setVisible(true);
JLabel rateLabel = new JLabel("Interest Rate: ");
JTextField rateField = new JTextField(10);
JButton calButton = new JButton("Add Interest");
class CalculateListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
double rate = Double.parseDouble(rateField.getText());
account.deposit((account.getBalance()*rate/100));
textArea.append(account.getBalance() + "\n");
}
}
ActionListener listener = new CalculateListener();
calButton.addActionListener(listener);
JPanel controlPanel = new JPanel();
controlPanel.add(rateLabel);
controlPanel.add(rateField);
controlPanel.add(calButton);

JFrame controlFrame = new JFrame();


controlFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
controlFrame.add(controlPanel);
controlFrame.setSize(220, 100);
controlFrame.setVisible(true);
}

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);

userlabel = new JLabel("Username");


userlabel.setBounds(15, 20, 80, 25);
panel.add(userlabel);

passwordLabel = new JLabel("Password");


passwordLabel.setBounds(15, 60, 80, 25);
panel.add(passwordLabel);

LoginAccess = new JLabel("");


LoginAccess.setBounds(100, 90, 150, 25);
panel.add(LoginAccess);

userText = new JTextField();


userText.setBounds(120, 20, 150, 25);
panel.add(userText);

password = new JPasswordField();


password.setBounds(120, 60, 150, 25);
panel.add(password);

ActionListener listener = new ClickListener();


loginButton = new JButton("Login");
loginButton.addActionListener(listener);
loginButton.setBounds(15, 95, 75, 25);
panel.add(loginButton);

Coding examples 4
frame.setVisible(true);

}
// public static boolean loggedIn = true;

public static class ClickListener implements ActionListener{


public void actionPerformed(ActionEvent e){
boolean LoggedInSuccess = LoginManager.login(userText.getText(), password.getText());
int NbAttemptMade = LoginManager.getAttempts();

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();
}

}
}

public class LoginManager{

static int AttemptMade = 0;


static String[] passwordStorage = {"123Welcome","Qwerti","Azertu2"};
static String[] userStorage = {"jerry","tom","enrique"};

public static boolean login(String userName, String password) {

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;
}

Layout and Buttons


By default, a JPanel uses a flow layout
By default, JFrame uses a border layout

Methods for buttons and labels

Coding examples 5
Same for JLabel, just methods SetBounds in addition

Example of GridLayout and BorderLayout

public class MyFrame


{ public static void main(String[] args)
{ JLabel a = new JLabel("AAAAAAAAAAA");
JLabel b = new JLabel("BBBBBBBBBBB");
JLabel c = new JLabel("CCCCCCCCCCC");
JTextField e = new JTextField(10);
JTextField f = new JTextField(10);
JTextField g = new JTextField(10);

JPanel centerPanel = new JPanel();


centerPanel.setLayout(new GridLayout(2, 3)); //nb of rows then column
centerPanel.add(a);
centerPanel.add(e);
centerPanel.add(b);
centerPanel.add(f);
centerPanel.add(c);
centerPanel.add(g);

JFrame frame = new JFrame();


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(centerPanel, BorderLayout.CENTER);
frame.add(new JButton("Do Button"),BorderLayout.SOUTH);
frame.setVisible(true);
}
}

Example with ComboBox

JComboBox combo = new JComboBox();


combo.addItem("Serif");
combo.addItem("SansSerif");

String select = (String) combo.getSelectedItem();

class solve extends JFrame implements ItemListener {

static JFrame f;
static JLabel l, l1;
static JComboBox c1;

public static void main(String[] args)


{

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");
}
}
}

Example with Radio Button

JRadioButton smallButton = new JRadioButton("Small");


JRadioButton mediumButton = new JRadioButton("Medium");
JRadioButton largeButton = new JRadioButton("Large");
ButtonGroup group = new ButtonGroup();
group.add(smallButton);
group.add(mediumButton);
group.add(largeButton);
[…]
if (largeButton.isSelected()) {
size = LARGE_SIZE;
}

Presenting Button Groups


javax.swing.border.TitledBorder:
javax.swing.border.EtchedBorder:

Example Check Boxes


Because check box settings do not exclude each other,you do not place a set of check boxes inside a button group

use IsSelected() ;

class solve extends JFrame {

static JFrame f;
public static void main(String[] args)
{

f = new JFrame("frame");
f.setLayout(new FlowLayout());

JCheckBox c1 = new JCheckBox("checkbox 1");


JCheckBox c2 = new JCheckBox("checkbox 2");

JPanel p = new JPanel();

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...

System.out.println("Reading SMTP Info.");


}
};
Timer timer = new Timer(100 ,taskPerformer);
timer.setRepeats(false);
timer.start();

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

Layouts should have consistent arrangements of a UI control such as


Buttons, Texts, Shapes, within the viewable area
• JavaFX layouts are simpler and more intuitive to implement than Swing

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

public class SimpleJavaFXApp extends Application{


public void start
(Stage stage){
stage.setTitle("Login");
BorderPane root= new BorderPane();
Scene scene= new Scene(root, 380, 150, Color.WHITE);
GridPane gridpane= new GridPane();
Label userNameLabel= new Label("User Name");
gridpane.setHalignment(userNameLabel, HPos.RIGHT);
gridpane.add(userNameLabel, 0, 0);

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 class SimpleMediaPlayer extends Application


{
public void start
(Stage stage){
Scene scene= new Scene(new Group(), 540, 209);
stage.setScene(scene);
stage.setTitle("Media Player");
stage.show();
String audio_source = "/home/folder/mySong.mp3";
File f= new File(audio_source);
Media media= new Media(f.toURI().toString());
MediaPlayer mediaPlayer= new MediaPlayer(media);
mediaPlayer.setAutoPlay(true);
MediaView mediaView= new MediaView(mediaPlayer);
((Group) scene.getRoot()).getChildren().add(mediaView);

}
public static void main
(String[] args){
launch(args);

}
}

Coding examples 9
Exception Handling
More specific exceptions must be placed before more general ones

public class FileCounter {


/* Write a class FileCounter (template provided) that asks a user for a file name and keeps track of
the number of characters, words, and lines in that file. */

private static int chars = 0;


private static int words = 0;
private static int lines = 0;

public static void main(String[]args){


String file = new String("C:\\Users\\leahi\\Documents\\AAA-Maastricht class\\Period 1.2\\CS2\\Coding lab\\Lab\\Lab6\\file1.txt
processFile(file);
System.out.println("Number of words "+getWordCount());
System.out.println("Number of characters "+getCharacterCount());
System.out.println("Number of lines "+getLineCount());
}

public static void processFile(String file){


lines = 0;
words = 0;
chars = 0;
String line;
try{
FileInputStream inputStream = new FileInputStream(file); //reaching the file
InputStreamReader streamReader = new InputStreamReader(inputStream); //turning my inputstream into a reader because BufferedR

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();}

//In case I had another error to handle


catch(IOException e, ){
e.printStackTrace();}
}

public static int getWordCount() {return words; }

public static int getCharacterCount() {return chars;}

public static int getLineCount() {return lines; }

public class ExamException {

/*
*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);
}

public static void main(String[]args){


try{
testException(-2);
test5(-9);
}catch(Exception e){
e.printStackTrace();
}
test2(-3);
test4(-9);

}
}

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");}
}

public class Find {


public static void main(String[] args){ //args is an array containing all the files I should look for the target word in
// Use this method to test your program
if(args.length>0){
for (int i = 1; i < args.length; i++) {
getLinesWithWordForFile(args[i], args[0]); //use args[] because we take input from terminal

}
}
}

public static String[] getLinesWithWordForFile(String file, String word){


// Write the word searching method here, return all lines that contain the word.
// Make sure you return the full line that contains the word and that you return
// ALL lines that contain the word
try{
ArrayList<String> storage = new ArrayList <String>();

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);
}
}

String[] array = storage.toArray(new String[0]);


for(String s : array){
System.out.println(s);
}
return array;

}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.)

Pyhton is slower than Java because interpreted

Python has five standard types

1. Numbers (int, long, float, etc.)

2. Strings

3. Lists

4. Tuples : sort of list

5. Dictionaries : list but instead of having index for each element, we have keys

Operations on List :

list = [ “abcd”, 786 , 2.23, “john”, 70.2]


tinylist = [123, “john”]
print(list)

# Prints complete list


[“abcd”, 786, 2.23, “john”, 70.2]

print(list[0]) # Prints first element of the list


abcd

print(list[1:3]) # Prints elements starting from 2nd till 3rd


[786, 2.23]

print(list[2:]) # Prints elements starting from 3rd element


[2.23, “john”, 70.2]

Coding examples 13
print(list[-1]) # Prints the last element
[70.2]

print(tinylist * 2) # Prints list two times


[123, “john”, 123, “john”]

print(list + tinylist) # Prints concatenated lists


[ “abcd”, 786 , 2.23, “john”, 70.2, 123, “john”]

tinylist.append(10) # Append elements in the list


print(tinylist)
[123, “john”, 10]

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

You might also like