0% found this document useful (0 votes)
151 views40 pages

Java Course - Beginner

This document contains summaries of 30 tutorials on Java programming concepts including: 1. Hello World - An introduction to printing text in Java. 2. Variables - Declaring and assigning variable values. 3. User Input - Getting input from the user using the Scanner class. 4. Basic Calculator - Building a simple calculator that takes input and performs addition. 5. Control Flow - Covering if/else statements, logical operators, switch statements, while loops and for loops. 6. Arrays - Creating and manipulating arrays, including summing array elements. 7. Random Numbers - Generating random numbers using the Random class. The tutorials progress from basic concepts to more advanced
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)
151 views40 pages

Java Course - Beginner

This document contains summaries of 30 tutorials on Java programming concepts including: 1. Hello World - An introduction to printing text in Java. 2. Variables - Declaring and assigning variable values. 3. User Input - Getting input from the user using the Scanner class. 4. Basic Calculator - Building a simple calculator that takes input and performs addition. 5. Control Flow - Covering if/else statements, logical operators, switch statements, while loops and for loops. 6. Arrays - Creating and manipulating arrays, including summing array elements. 7. Random Numbers - Generating random numbers using the Random class. The tutorials progress from basic concepts to more advanced
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/ 40

http://www.youtube.com/watch?

v=Hl-zzrqQoSE&list=PLFE2CE09D83EE3E28

Tutorial 4: Hello World


Hello World
public class Hello_world {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello World!");
}
}

Applet
import java.applet.*;
import java.awt.*;
public class HelloWorldapplet extends Applet
{
public void paint (Graphics g)
{
g.drawString("Hello World!", 50, 25);
}
}

Tutorial 5: Variables
class Apples {
public static void main(String args[]){
double tuna; // declaring a variable
tuna = 5.28; // assigning a variable
System.out.print("I want ");
System.out.print(tuna);
System.out.println(" movies");
System.out.print("Apples"); //finish the line

Tutorial 6: Getting user input


import java.util.Scanner; // we told java that we need tu use the scanner to get
information from the keyboard
class Apples {

public static void main (String args[]){


Scanner bucky = new Scanner(System.in); //every information from
the keyboard in the variable bucky
System.out.println(bucky.nextLine());
bucky.close(); // it wasnt in the tutorial but its a good information to
save memory
}
}

Tutorial 7: Building a basic calculator


import java.util.Scanner; //importing the scanner
class Apples {
public static void main (String args[]){
Scanner bucky = new Scanner(System.in);
double fnum, snum, Answer; //creating the variables
System.out.println("Enter the first num: ");
fnum = bucky.nextDouble();
System.out.println("Enter the second num: ");
snum = bucky.nextDouble();
Answer = fnum + snum;
System.out.println(Answer);
}
}

Tutorial 8: Math Operators


Int variables = results are always integer.
% = resto
import java.util.Scanner;
class tutorial8{
public static void main (String args[]){
Scanner bucky = new Scanner(System.in);
int girls, boys, people;
girls = 8;
boys = 3;
people = girls % boys;
System.out.println(people);
}
}

Tutorial 9: Increment Operators


class tutorial8{
public static void main (String args[]){
Scanner bucky = new Scanner(System.in);
int tuna = 5;
int bass = 18;
++tuna;
System.out.println(tuna);
System.out.println(++tuna); // change to six Increment Operators

System.out.println(tuna);
System.out.println(tuna++); //use with five, and than change to six
System.out.println(tuna);
System.out.println(tuna--); //use with seven, and than change to six
System.out.println(tuna);
//assigning operators
tuna = tuna + 5;
//easier way
tuna += 8;
System.out.println(tuna);
tuna -= 8;
tuna *= 8;

Tutorial 10: If Statements


if(test == 9){ //== exactly equal // if(test != 9) not equal
class tutorial8{
public static void main (String args[]){
int A, B, C, Result;
A = 5;
B = 7;
C = 8;
Result = A % 2;
if(Result>0){
System.out.println("A impar");
} else{
System.out.println("A Par");
}
Result = B % 2;
if(Result>0){
System.out.println("B impar");
} else{
System.out.println("B Par");
}
Result = C % 2;
if(Result>0){
System.out.println("C impar");
} else{
System.out.println("C Par");
}
}
}

Tutorial 11: Logical Operators


class tutorial8{
public static void main (String args[]){
int boy, girl;
boy = 18;

<=, >=

girl = 68;
if(boy > 10 || girl < 60){ //&& = AND
|| = OR
System.out.println("You can enter");
}else{
System.out.println("You can not enter");
}
}
}

Tutorial 12: Switch Statement


class tutorial8{
public static void main (String args[]){
int age;
age = 2;
switch (age){
case 1:
System.out.println("You can crawl");
break;
case 2:
System.out.println("You can talk");
break;
case 3:
System.out.println("You can get it trouble");
break;
default:
System.out.println("I dont know how old you are");
break;
}
}
}

Tutorial 13: While Loop


class tutorial8{
public static void main (String args[]){
int counter = 0;
while (counter < 10){
System.out.println(counter);
counter++;
}
}
}

Tutorial 14: Using multiple Classes


Creating a new class tuna:

//dont have main, because it will not execute


public class tuna {
public void simpleMessage(){
System.out.println("This is another class");
}
}

Calling the class tuna in the main class:


class Apples {
public static void main (String[] Args){
tuna tunaObject = new tuna();
tunaObject.simpleMessage();
}

Tutorial 15: Using methods with parameters


Method Apples
import java.util.Scanner;
class Apples {
public static void main (String[] Args){
Scanner input = new Scanner(System.in);
tuna tunaObject = new tuna();
System.out.println("Enter your name here: ");
String name = input.nextLine(); // name to be equal to anything we

type in
}

tunaObject.simpleMessage(name);

Method Tuna
public class tuna {
public void simpleMessage(String name){ //name is called argument
System.out.println("Hello " + name);
}
}

Tutorial 16: Many methods and instances


Apples
import java.util.Scanner;
class Apples {
public static void main (String[] Args){
Scanner input = new Scanner(System.in);
tuna tunaObject = new tuna();
System.out.println("Enter name of first gf here:");

String temp = input.nextLine();


tunaObject.setName(temp);
tunaObject.saying();
}
}

Tuna
public class tuna {
private String girlName; // instead of public, public any class can use
available, private only the methods inside this class can manipulate and change
public void setName(String name){
girlName=name;
}
public String getName(){
return girlName;
}
public void saying(){
System.out.printf("Your first gr was %s", getName());
}
}

Tutorial 17: Constructors


class Apples {
public static void main (String[] Args){
tuna tunaObject = new tuna ("Kelsey"); //constructor give a value as
soon as the object is created.
tunaObject.saying();
}
}

Tutorial 18: Nested if statements


import java.util.Scanner;
class Apples {
public static void main (String[] Args){
int age;
Scanner input = new Scanner(System.in);
System.out.println("Write your age:");
age = input.nextInt();
if (age <50) {
System.out.println("You are young");
}else{
System.out.println("You are old");
if (age > 75) {
System.out.println("You are really old!");
}
}
}

Tutorial 19: else if statements


if (age <50) {
System.out.println("You
else if (age <40)
System.out.println("You
else if (age <30)
System.out.println("You
else if (age <20)
System.out.println("You

are not young");


are in your 40s");
are in your 30s");
are fucking young");

Tutorial 20: conditional operators


class apples {
public static void main (String[] args) {
int age = 21;
//age is grater then 50 ? "True" ; "False"
System.out.println(age > 50 ? "You are old" : "You are young");
}
}

Tutorial 21: simple averaging program


import java.util.Scanner;
class lalalau {
public static void main (String[] args) {
Scanner input = new Scanner (System.in);
int total = 0;
int grade;
int average;
int counter = 0;

while(counter < 11){


System.out.println("Digite o " + ++counter + " nmero:");
grade = input.nextInt();
total = total + grade;
}
average = total/10;
System.out.println("Your avarage is "+ average);

Tutorial 22: for Loops


class lalalau {
public static void main (String[] args) {
for(int counter =1; counter <=10; counter ++){//1 when loop starts,
2 when loop end, 3 how much increment by
System.out.println(counter);
}

Tutorial 23: compound interest program


class lalalau {
public static void main (String[] args) {
// A = P(1+R)^n
double amount;
double principal = 10000;
double rate =.01;
for (int day=1; day<=20;day++){
amount=principal*Math.pow(1 + rate, day); //pow = power
System.out.println(day + " : " + amount);
}
}

Tutorial 24: do while Loops


class lalalau {
public static void main (String[] args) {
int counter = 15; //diference between the while loop, it didnt test
first, garantee at least one loop.
do{

System.out.println(counter);
counter++;
}while(counter<=10);
}

Tutorial 25: Math Class Methods


class lalalau {
public static void main (String[] args) {
System.out.println(Math.abs(-26.7)); //abs gives the absolute value
System.out.println(Math.ceil(7.4)); //ceiling = arredondamento cima
System.out.println(Math.floor(7.4)); //ceiling = arredondamento baixo
System.out.println(Math.max(8.6, 5.2)); //gives the maximum
System.out.println(Math.min(8.6, 5.2)); //gives the maximum

quadrada)

System.out.println(Math.pow(5,3)); //power 5^3


System.out.println(Math.sqrt(16)); //gives the square root (raiz

Tutorial 26: Random number generator


import java.util.Random;
class lalalau {
public static void main (String[] args) {
Random dice = new Random();
int number;

for (int counter =1; counter<=10; counter ++){


//number = dice.nextInt(6); //for 0 to five
number = 1+dice.nextInt(6); // for 1 to 6
System.out.println(number + " ");
}

Tutorial 27: Introduction to Arrays


class lalalau {
public static void main (String[] args) {
int bucky[] = new int[10]; //with square brakets = to arrays
bucky [0]= 87;
bucky [1] = 543;
bucky [9] = 65;
System.out.println(bucky[9]);
//array initializer
int bucky2[]={2,4,5,7,9}; //0 = 2, 1=4, 2=5, 3=7,4=9
System.out.println(bucky2[2]);

//show the five of the sequence

}
}

Tutorial 28: Creating an Array Table


class lalalau {
public static void main (String[] args) {
System.out.println("Intex\tValue"); // \t = tab
int bucky[]={32,12,18,54,2};
//function .length indentifies the length of an array
for(int counter = 0; counter<bucky.length; counter ++){//first
element is always zero
System.out.println(counter + "\t" + bucky[counter]);
}
}

Shows:
Intex
0
1
2
3

Value
32
12
18
54

Tutorial 29: Summing elements of arrays


class lalalau {
public static void main (String[] args) {
int bucky[]={21,16,86,21,2};
int sum=0;
for(int counter=0;counter<bucky.length;counter++){
sum+=bucky[counter]; //sum+ add values to the variable sum
}
System.out.println("The sum of these numbers is " + sum);
}

Tutorial 30: Array elements as counters

/*HARD

import java.util.Random;
import java.util.Random;
class lalalau {
public static void main (String[] args) {
Random rand = new Random();
int freq[]=new int [7]; //for 0 to 6
for (int roll=1;roll<=100;roll++){
++freq[1+rand.nextInt(6)]; //IMPORTANT 1+ because of this
aspect (0 to 6)
//++freq = each time it hits 1, add 1 to this number, at the
beginin, 0 to 7 start with zero
}
System.out.println("Face\tFrequency");
for(int face=1;face<freq.length;face++){ //count for 1 to 6
System.out.println(face+"\t"+freq[face]);
}
}

Tutorial 31: Enhanced for Loop


class lalalau {
public static void main (String[] args) {
int bucky[] = {3,4,5,6,7};
int total = 0;
for(int x: bucky){ //(type indentifier name) special enhanced
for statement
total+=x;
//(what type you want to store, what v variable you
want to loop
}
System.out.println(total);
}

Tutorial 32: Arrays in methods


class lalalau {
public static void main (String[] args) {
int bucky[]={3,4,5,6,7};
change(bucky);
for(int y:bucky)
System.out.println(y);
}
public static void change(int x[]){
for(int counter=0;counter<3.length;counter++)
x[counter]+=5;
}
}

Tutorial 33: Multidimensional Arrays


class lalalau {
public static void main (String[] args) {
int firstarray[][]={{8,9,10,11},{12,13,14,15}};
//firstarray[0][1]
int secondarray[][]={{30,31,32,33},{43},{4,5,6}} //3 rows
}

Tutorial 34: Table for Multidimensional Arrays


class lalalau {
public static void main (String[] args) {
int firstarray[][]={{8,9,10,11},{12,13,14,15}}; firstarray[0][1]
int secondarray[][]={{30,31,32,33},{43},{4,5,6}}; //3 rows
System.out.println("This is the first Array");
display(firstarray);
System.out.println("This is the second Array");
display(secondarray);

}
public static void display(int x[][]){
for(int row=0;row<x.length;row++){
for(int column=0;column<x[row].length;column++){
System.out.print(x[row][column]+"\t");
}
System.out.println();
}
}
}

Tutorial 35: Variable Length Arguments


class lalalau {
public static void main (String[] args) {
System.out.println(average(1,2,3,4,5));
}
public static int average(int...numbers){ //when you dont know how
many, you use ...
int total=0;
for(int x:numbers)
total+=x;
return total/numbers.length;
}

Tutorial 36: Time Class


import java.util.Scanner;
public class tuna {
//timeclass = diferent bunch of time functions
private int hour;
private int minute;
private int second;
public void setTime(int h,int m, int s){
hour = ((h>=0 && h<24) ? h : 0);
minute = ((m>=0 && h<60) ? m : 0);
second = ((h>=0 && h<60) ? s : 0);
}
public String toMilitary(){
return String.format("%02d:%02d:%02d", hour, minute,
second);
}
public void Typetime(){
Scanner time = new Scanner(System.in);
System.out.println("Digite a quantidade de Horas: ");
hour= time.nextInt();
System.out.println("Digite a quantidade de minutos: ");
minute= time.nextInt();
System.out.println("Digite a quantidade de segundos: ");
second= time.nextInt();
hour = ((hour>=0 && hour<24) ? hour : 0);
minute = ((minute>=0 && minute<60) ? minute : 0);
second = ((second>=0 && second<60) ? second : 0);

}
}
import java.util.Scanner;

class Apples {
public static void main (String[] Args){
Scanner dig = new Scanner(System.in);
tuna ABCObject = new tuna();
System.out.println(ABCObject.toMilitary());
System.out.println("Voc deseja setar as horas manualmente? (s/n)");
String letra = dig.nextLine();
switch (letra){
case "s":
ABCObject.Typetime();
break;
case "n":
ABCObject.setTime(13,27,6);
break;
default:
System.out.println("Voce digitou a letra errada sua besta!");
}
System.out.println(ABCObject.toMilitary());

Tutorial 37: set regular time


public String toString(){
return String.format("%d:%02d:%02d %s", ((hour==0||
hour==12)?12:hour%12), minute, second, (hour <12?"AM":"PM"));
}

Tutorial 38: Public, private, this


// private = only the methods in the same class can use the variables
// public = variables can be used outside the class
// this = when you have same name variables and needs to use diferent
values, you can set .this
private int hour =1;
private int minute =2;
private int second=3 ;
public void setTime(int hour,int minute, int second){
this.hour = 4
this.minute = 5
this.second = 6

Tutorial 39: Multiple Constructors


//constructor = method with the same name as the class, when you create
an object, you call that method
// multiple constructors
public class tuna {
private int hour;
private int minute;
private int second;
public tuna(){
this(0,0,0);
}
public tuna(int h){
this(h,0,0);
}
public tuna(int h, int m){
this(h,m,0);
}
public tuna(int h, int m, int s){
setTime(h,m,s);
}

public void setTime (int h, int m, int s){


setHour(h);
setMinute(m);
setSecond(s);
}

Tutorial 40: Set and get methods


(continua no 41)
Tutorial 41 : Building Objects for Constructors
O programa seleciona o public tuna que pussui mesmo nmero de
argumentos declarados = mesmo nmero de variveis.
class Apples {
public static void main (String[] Args){
tuna tunaObject = new tuna();
tuna tunaObject2 = new tuna(5);
tuna tunaObject3 = new tuna(5,13);
tuna tunaObject4 = new tuna(5,13,43);
System.out.printf("%s\n",
System.out.printf("%s\n",
System.out.printf("%s\n",
System.out.printf("%s\n",
}
}

tunaObject.toMilitary());
tunaObject2.toMilitary());
tunaObject3.toMilitary());
tunaObject4.toMilitary());

public class tuna {


private int hour;
private int minute;
private int second;
public tuna(){
this(0,0,0);
}
public tuna(int h){
this(h,0,0);
}
public tuna(int h, int m){
this(h,m,0);
}
public tuna(int h, int m, int s){
setTime(h,m,s);
}
public void setTime (int h, int m, int s){
setHour(h);
setMinute(m);
setSecond(s);
}
public void setHour(int h){
hour =((h>=0 && h<24)?h:0);
}
public void setMinute(int m){
minute =((m>=0 && m<60)?m:0);
}
public void setSecond(int s){
second =((s>=0 && s<60)?s:0);
}
public int getHour(){
return hour;
}
public int getMinute(){
return minute;
}
public int getSecond(){
return second;
}
public String toMilitary(){
return String.format("%02d:%02d:
%02d",getHour(),getMinute(),getSecond());
}
}

Tutorial 42 : toString
public class potpie {
private int month;
private int day;
private int year;
public potpie(int m, int d, int y){ //constructor
month = m;

day = d;
year = y;
}

System.out.printf("The Constructor for this is %s\n", this);

public String toString(){


return String.format("%d/%d/%d",month,day,year);
}
}

class Apples {
public static void main (String[] Args){
potpie potObject = new potpie(4,5,6);
}
}

Tutorial 43 : Composition
- Referring to objects in othe classes as members
- Using tostring to change an object into a variable string
public class tuna {
private String name;
private potpie birthday; //reference to a potpie object
public tuna(String theName, potpie theDate){
name = theName;
birthday = theDate;
}
public String toString(){
return String.format("My name is %s, my birthday is %s", name,
birthday);
}
}
// object to string
//direciona o objeto para uma classe que o transforma em
string, pronto para compor o texto

Tutorial 44 : Enumeration
public enum tuna { //kind a classes, but using to declare constants = create an
enumeration constructor
bucky("nice","22"),
kelsey("cutie","10"),
julia("bigmistake","12"); //constants and objects
private final String desc; // variables to represent 2 arguments
private final String year;

tuna(String description, String birthday){ //enumeration constructor alows to


return the information we want
desc = description;
year = birthday;
}
public String getDesc(){
return desc;
}

public String getYear(){


return year;
}

class Apples {
public static void main (String[] args){
for(tuna people: tuna.values())
System.out.printf("%s\t%s\t%s\n", people,
people.getDesc(), people.getYear());
}
}

Tutorial 45 : Enumset range


public enum tuna { //kind a classes, but using to declare constants = create an
enumeration constructor
bucky("nice","22"),
kelsey("cutie","10"),
julia("bigmistake","12"), //constants and objects
nicole("italian","13"),
candy("diferent","14"),
erin("iwish","16");
private final String desc; // variables to represent 2 arguments
private final String year;
tuna(String description, String birthday){ //enumeration constructor alows to
return the information we want
desc = description;
year = birthday;
}
public String getDesc(){
return desc;
}

public String getYear(){


return year;
}

import java.util.EnumSet; IMPORTANT


class Apples {

public static void main (String[] args){


for(tuna people: tuna.values())
System.out.printf("%s\t%s\t%s\n", people,
people.getDesc(), people.getYear());
System.out.println("\nAnd now for the range of constants!!\n");
for(tuna people: EnumSet.range(tuna.kelsey, tuna.candy)) HEREEE
System.out.printf("%s\t%s\t%s\n", people, people.getDesc(),
people.getYear());
}
}

Tutorial 46 : Static
public class tuna {
private String first;
private String last;
private static int members = 0; //every object shares the same variable,
change all objects
public tuna(String fn, String ln){
first = fn;
last = ln;
members++;
System.out.printf("Constructor for %s %s, members in the club:
%d\n", first, last, members);
}
} class Apples {
public static void main (String[] args){
tuna member1 = new tuna("Megan","Fox");
tuna member2 = new tuna("Natalie", "Portman");
tuna member3 = new tuna("Taylor", "Swift");
}
}

Tutorial 47 : More on Static


class Apples {
public static void main (String[] args){
tuna member1 = new tuna("Megan","Fox");
tuna member2 = new tuna("Natalie", "Portman");
tuna member3 = new tuna("Taylor", "Swift");
System.out.println();
System.out.println(member2.getFirst());
System.out.println(member2.getLast());
System.out.println(member2.getMembers()); //variable is shared, the
others are unique

} public class tuna {


private String first;
private String last;
private static int members = 0; //every object shares the same variable,
change all objects
public tuna(String fn, String ln){
first = fn;
last = ln;
members++;
System.out.printf("Constructor for %s %s, members in the club:
%d\n", first, last, members);
}
public String getFirst(){
return first;
}
public String getLast(){
return last;
}
public static int getMembers(){
return members;
}
}
//TRICK!!!
class Apples {
public static void main (String[] args){
tuna member1 = new tuna("Megan","Fox");
tuna member2 = new tuna("Natalie", "Portman");
tuna member3 = new tuna("Taylor", "Swift");
System.out.println(tuna.getMembers); //with static, you dont need an
object! you can put the classname at the println. BECAUSE ITS SHARED.
}
}

Tutorial 48 : Final
public class tuna {
private int sum;
private final int NUMBER; //in front of variable, you cant modified no
mather what happens
//must inicialize!
public tuna(int x){
NUMBER = x;
}
public void add(){
sum+=NUMBER;
}
public String toString(){
return String.format("sum = %d\n", sum);
}
} class Apples {

public static void main (String[] args){


tuna tunaObject = new tuna(10);
for(int i=0; i<5;i++){
tunaObject.add();
System.out.printf("%s",tunaObject);
}
}

Tutorial 49 : Inheritance
//superclass = because other classes will inherit stuff from here
//instead of modifying all the time the same method in all classes, we create one
method in "food", so all the other classes will inherit
public class food {
public void eat(){
System.out.println("I am the new methods");
}
}
public class potpie extends food{ //extends means inheritance from...
}
public class tuna extends food{
}
class Apples {
public static void main (String[] args){
tuna tunaObject = new tuna();
potpie potObject = new potpie();
tunaObject.eat();
potObject.eat();
}

Tutorial 50 : Graphical interface user GUI


import javax.swing.JOptionPane;
class Apples {
public static void main (String[] args){
String fn = JOptionPane.showInputDialog("Enter first number");
//shows the input dialog box

String sn = JOptionPane.showInputDialog("Enter second number");


int num1 = Integer.parseInt(fn); //Converse String into Integer
int num2 = Integer.parseInt(sn);
int sum = num1+ num2;
JOptionPane.showMessageDialog(null, "The answer is " +sum, "the
title", JOptionPane.PLAIN_MESSAGE);
//(position, answer, title, icons?)
}
}

Tutorial 51 Gui with JFrame


import java.awt.FlowLayout; //import how things are placed, the layout
import javax.swing.JFrame; //gives all the basic windows features
import javax.swing.JLabel; //allows to put text and imagens on the screen
public class tuna extends JFrame{
private JLabel item1;
public tuna(){
super("The title bar"); // to add a title on a window
setLayout(new FlowLayout());
item1 = new JLabel("this is a sentence"); //output to a label
item1.setToolTipText("This is gonna show up on hover");
add(item1); //shows everything on the screeen
}
}
import javax.swing.JFrame;
class Apples {
public static void main (String[] args){
tuna bucky = new tuna();
bucky.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit the
program whem its closed
bucky.setSize(275,180);
bucky.setVisible(true);
}
}

Tutorial 52 Event Handling (to be continued - 53)


Tutorial 53 ActionListner (to be continued - 54)
C
//events are anything like move the mouse, click, press enter
//eventhandler is the code that response to the mouse clicking

//This process is calling Event Handling


import java.awt.FlowLayout;
import java.awt.event.ActionListener; //listen or wait for the user to enter
something
import java.awt.event.ActionEvent; //the events
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JOptionPane;
public class tuna extends JFrame{ //build a window using jframe
private
private
private
private

JTextField item1;
JTextField item2;
JTextField item3;
JPasswordField passwordField;

public tuna(){
super("the title");
setLayout(new FlowLayout());
item1 = new JTextField(10);
add(item1);
item2 = new JTextField("enter text here");
add(item2);
item3 = new JTextField("uneditable", 20);
item3.setEditable(false);
add(item3);
passwordField = new JPasswordField("mypass");
add(passwordField);
//to add some brains to them, waiting on the screen, something to
happen

thehandler handler = new thehandler();


item1.addActionListener(handler);
item2.addActionListener(handler);
item3.addActionListener(handler);
passwordField.addActionListener(handler);

}
// the class inside othe class inherited all the stuff
private class thehandler implements ActionListener{ //wait events to roll
the code - wait the enter in this case
public void actionPerformed(ActionEvent event){
//it takes one method and its called automately when a event calls
String string = "";
if(event.getSource()==item1)
string=String.format("field 1:
%s",event.getActionCommand()); //get the text from that location
else if(event.getSource()==item2)

string=String.format("field 2:
%s",event.getActionCommand());
else if(event.getSource()==item3)
string=String.format("field 3:
%s",event.getActionCommand());
else if(event.getSource()==passwordField)
string=String.format("password field is : %s",
event.getActionCommand());
}

JOptionPane.showMessageDialog(null,string);

}
}

import javax.swing.JFrame;
class Apples {
public static void main (String[] args){
tuna bucky = new tuna();
bucky.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
bucky.setSize(350, 100);
bucky.setVisible(true);
}

Tutorial 55 Introduction to Polymorphism

//Polymorphism - need a program that uses inheritance to explain


class Apples {
public static void main (String[] args){
//polymorphic array - stores objects of diferent classes in the
superclass type
//you can build one reference variable of the superclass and sign it to
objects of subclasses
food bucky[]=new food[2];
bucky[0]= new potpie();
bucky[1]=new tuna();
for(int x=0;x<2;++x){
bucky[x].eat();
}
}

public class food {


void eat(){
System.out.println("This food is great");
}
}

public class tuna extends food{


void eat(){
System.out.println("This tuna is great");
}
}
public class potpie extends food{
void eat(){
System.out.println("This potpie is great");
}
}

Tutorial 56 Polymorphic argument

//Polymorphism - need a program that uses inheritance to explain


class Apples {
public static void main (String[] args){
fatty bucky = new fatty();
food fo = new food();
food po = new potpie();
bucky.digest(fo); //bucky object, digest with food object is the
argument

bucky.digest(po);
//created an object so we can use all the stuff from fatty
//created new food object because this digest took food object as an

argument

//potpie object take a food argument, or a potpie or a tuna argument

}
}
public class fatty {
public void digest(food x){
x.eat();
}
}
public class food {
void eat(){

System.out.println("This food is great");

}
public class potpie extends food{
void eat(){
System.out.println("This potpie is great");
}
}

Tutorial 57 Overriding rules


//anytime you override a method you cant put diferent arguments ex: void eat(int x)
//this is overloadind, total diferent thing
//you cant also change the escope: ex: private void eat()
abstract public class food {
void eat(){
System.out.println("This food is great");
}
}
public class fatty {
tuna to = new tuna(); //tuna reference = tuna object
food fo = new food(); //food class is too general to create new
objects. We need this superclass to inheritance and polymorphism.
//abstract food = you can you use but you can create any objects
public void digest(food x){
x.eat();
}
}

Tutorial 58 Abstract and Concrete Classes


//abstract class = you cant create objects, its only usefull to polymorphism and
inheritance
//concrete class = especific enough to make objects of them (not abstract)
//abstract method = that must be overitten
abstract public class food {
public abstract void eat(); //you dont need a body and the entire class
muss be abstract
//also eat in potpie must be public when this method is public
//need to implement in any of the subclasses that extends the superclass
//food has abstract, so the classes with extends NEED to override that
method (use a method from food), if not it will have a problem

Tutorial 59 Class to hold objects


public class Dog extends Animal{
}
public class Fish extends Animal{
}
public class DogList {
private Dog[] thelist = new Dog[5];
private int i=0;
public void add(Dog d){
if (i<thelist.length){
thelist[i]=d;
System.out.println("Dog added at index "+i);
i++;
}
}
}
public class Animal {

}
class Apples {
public static void main (String[] args){
DogList DLO = new DogList();
Dog d = new Dog();
DLO.add(d);
}
}

Tutorial 60 Array holding many objects


class Apples {
public static void main (String[] args){
AnimalList ALO = new AnimalList();
Dog d = new Dog();
Fish f = new Fish();
ALO.add(d);
ALO.add(f);
}
}
public class AnimalList {
private Animal[] thelist = new Animal[5];

private int i = 0;
public void add(Animal a){
if(i<thelist.length){
thelist[i]=a;
System.out.println("Animal added at index "+i);
i++;
}
}
}
public class Animal {
}
public class Fish extends Animal{
}
public class Dog extends Animal{
}

Tutorial 61 Simple Polymorphic Program


class Apples {
public static void main (String[] args){
Animal[] thelist = new Animal[2];
Dog d = new Dog();
Fish f = new Fish();
thelist[0]=d;
thelist[1]=f;
for(Animal x: thelist){ //for goes trough the entire array thelist
x.noise();
}
}
}
public class Fish extends Animal{

public void noise(){


System.out.println("Glurp Slurp");
}

Tutorial 62 JButton (to be continued)


Tutorial 63 JButton Final Program
//program that creates two buttons with diferent caracteristics, and show a message
and its clicked.
import java.awt.FlowLayout;
import java.awt.event.ActionListener; //listen or wait for the user to enter
something
import java.awt.event.ActionEvent; //the events
import javax.swing.JFrame;

import
import
import
import

javax.swing.JButton;
javax.swing.Icon;
javax.swing.ImageIcon;
javax.swing.JOptionPane;

public class Gui extends JFrame{


private JButton reg;
private JButton custom;
public Gui(){
super("The Title");
setLayout(new FlowLayout());
reg = new JButton("reg Button");
add(reg); //put it on the screen
Icon b = new ImageIcon(getClass().getResource("Thiago.jpg"));
Icon x = new ImageIcon(getClass().getResource("xx.jpg"));
custom = new JButton("Custom",b);
custom.setRolloverIcon(x);
add(custom); //put it on the screen

HandlerClass handler = new HandlerClass();


reg.addActionListener(handler);
custom.addActionListener(handler);

private class HandlerClass implements ActionListener{ //we want to use


overrided methodes
public void actionPerformed(ActionEvent event){
JOptionPane.showMessageDialog(null, String.format("%s",
event.getActionCommand()));
}
}
}
import javax.swing.JFrame;
class Apples {
public static void main (String[] args){
Gui go = new Gui();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(300,200);
go.setVisible(true);
}

Tutorial 64 JCheckBox
Tutorial 65 The final CheckBox Program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Gui extends JFrame{
private JTextField tf;

private JCheckBox boldbox;


private JCheckBox italicbox; //1) make 3 variables
public Gui(){
super("The Title");
setLayout(new FlowLayout());//2) in our constructor, we set the title,
and the layout
// we add textfield,
bold box and italicbox on the screen
tf = new JTextField("Tis is a sentence",20);
tf.setFont(new Font("Serif", Font.PLAIN,14)); //PLAIN = not bold, not
italic, Size Fomnt
add(tf);
boldbox = new JCheckBox("bold");
italicbox = new JCheckBox("italic");
add(boldbox);
add(italicbox);
HandlerClass handler = new HandlerClass(); //3) we create a
HandlerClass to handle this events
boldbox.addItemListener(handler); //a handler listener waiting for
something to happen
italicbox.addItemListener(handler);
}
//Write something to do when its clicked
private class HandlerClass implements ItemListener{
//class that implements = means we can use all the methodes from
itemListeners but have to overwrith each
public void itemStateChanged(ItemEvent event){
//itemStateChanged = everytime we click in the box, one itemEvent
ocurs, and we can add some funcionality, its hadlered by the itemlistener
Font font = null;
if(boldbox.isSelected()&& italicbox.isSelected())
font = new Font("Serif", Font.BOLD + Font.ITALIC,14);
else if(boldbox.isSelected())
font = new Font("Serif", Font.BOLD, 14);
else if(italicbox.isSelected())
font = new Font("Serif", Font.ITALIC, 14);
else
font = new Font("Serif", Font.PLAIN, 14);
tf.setFont(font);
}
}
}
import javax.swing.JFrame;
class Apples {
public static void main (String[] args){
Gui go = new Gui();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(300,200);

go.setVisible(true);

Tutorial 66 JRadioButton
Tutorial 67 JRadioButton Final Program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//radiobuttom kind of checkbox, but you can have one radio buttom selected at the
time
public class Gui extends JFrame{
private JTextField tf;
private Font pf; //plain
private Font bf; //bold
private Font itf; //italic
private Font bif; //bold and italic
private JRadioButton pb;
private JRadioButton bb;
private JRadioButton ib;
private JRadioButton bib;
private ButtonGroup group; //stablish a relationship that only one buttom
can be selectef
public Gui(){
super("The Title");
setLayout(new FlowLayout());
tf = new JTextField("Thiago is awsome and hot", 25);
add(tf);
pb = new JRadioButton("plain",true); //true = checked false =
unchecked

bb = new JRadioButton("bold",false);
ib = new JRadioButton("italic",false);
bib = new JRadioButton("bold and italic",false);
add(pb);
add(bb);
add(ib);
add(bib);
group = new ButtonGroup();
group.add(pb);
group.add(bb);
group.add(ib);
group.add(bib);
pf = new Font("Serif", Font.PLAIN,14);
bf = new Font("Serif", Font.BOLD,14);
itf = new Font("Serif", Font.ITALIC,14);
bif = new Font("Serif", Font.BOLD + Font.ITALIC,14);
tf.setFont(pf);
//wait for event to happen, pass in font object to constructor
pb.addItemListener(new HandlerClass(pf));

bb.addItemListener(new HandlerClass(bf));
ib.addItemListener(new HandlerClass(itf));
bib.addItemListener(new HandlerClass(bif));
}
private class HandlerClass implements ItemListener{
private Font font;
//the font object get variable font
public HandlerClass(Font f){
font = f;
}
//tets the font to the font object that was passed in
public void itemStateChanged(ItemEvent event){
tf.setFont(font);
}
}

}
import javax.swing.JFrame;
class Apples {
public static void main (String[] args){

Gui go = new Gui();


go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(300,200);
go.setVisible(true);

Tutorial 68 JComboBox
Tutorial 69 Drop Down list program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//combobox - list of pictures in this exemple
public class Gui extends JFrame{
private JComboBox box;
private JLabel picture;
//2 array, one of filenames, one of images
private static String[] filename = {"b.jpg", "x.jpg"};
private Icon[] pics = {new
ImageIcon(getClass().getResource(filename[0])),new
ImageIcon(getClass().getResource(filename[1]))};
public Gui(){

super("the title");
setLayout(new FlowLayout());
box = new JComboBox(filename);

event){

//add some functionality with an itemlistener


box.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent

if(event.getStateChange()==ItemEvent.SELECTED)

picture.setIcon(pics[box.getSelectedIndex()]);
}
}
);
add(box);
picture=new JLabel(pics[0]);
add(picture);
}

Tutorial 70 JList
Tutorial 71 JList Program
import
import
import
import

java.awt.*;
java.awt.event.*;
javax.swing.*;
javax.swing.event.*;

//a list when you click in one option, a event happens


public class Gui extends JFrame{
private JList list;
private static String[] colornames = {"black","blue", "red", "white"};
private static Color[] colors = {Color.BLACK,
Color.BLUE,Color.RED,Color.WHITE};
public Gui(){
super("title");
setLayout( new FlowLayout());
list = new JList(colornames);
list.setVisibleRowCount(4);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);//select a
single selection at the time
add(new JScrollPane(list));
list.addListSelectionListener(
new ListSelectionListener(){
public void
valueChanged(ListSelectionEvent event){
getContentPane().setBackground(colors[list.getSelectedIndex()]);

}
}

);

Tutorial 72 Multiple selection List


Tutorial 73 Moving list items program
import
import
import
import

java.awt.*;
java.awt.event.*;
javax.swing.*;
javax.swing.event.*;

//list on left, when you select multiple itens, they move to the right
public class Gui extends JFrame{
private
private
private
private
"morebacon"};

JList leftlist;
JList rightlist;
JButton movebutton;
static String[] foods = {"bacon","wings","ham", "beer",

public Gui(){
super("title");
setLayout(new FlowLayout());
leftlist = new JList (foods);
leftlist.setVisibleRowCount(3);

leftlist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
add(new JScrollPane(leftlist));

event){

movebutton = new JButton("Move -->");


movebutton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent

rightlist.setListData(leftlist.getSelectedValues());
}
}
);
add(movebutton);
rightlist = new JList();
rightlist.setVisibleRowCount(3);
rightlist.setFixedCellWidth(100);
rightlist.setFixedCellHeight(15);

rightlist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
add(new JScrollPane(rightlist));
}

Tutorial 74 Mouse Events


Tutorial 75 Mouse Listener Interface
Tutorial 76 Mouse MotionListener Interface
import java.awt.*; //colors, border lauyout, etc
import java.awt.event.*;
import javax.swing.*;
//we can responde to mouse events - click or move or etc
public class Gui extends JFrame{
private JPanel mousepanel;
private JLabel statusbar;
public Gui(){
super("title");
mousepanel = new JPanel();
mousepanel.setBackground(Color.WHITE);
add(mousepanel, BorderLayout.CENTER);
statusbar = new JLabel("default");
add(statusbar, BorderLayout.SOUTH);
//new handling class
Handlerclass handler = new Handlerclass();
//2 types of mouse events
mousepanel.addMouseListener(handler); //click, press, release,
movein, moveout
mousepanel.addMouseMotionListener(handler);// movements
}
private class Handlerclass implements MouseListener,
MouseMotionListener{
public void mouseClicked(MouseEvent event){
statusbar.setText(String.format("Clicked at %d,
%d",event.getX(),event.getY()));
}
public void mousePressed(MouseEvent event){
statusbar.setText("You pressed down the mouse");
}
public void mouseReleased(MouseEvent event){
statusbar.setText("You released the button");
}
public void mouseEntered(MouseEvent event){
statusbar.setText("You entered the area");
mousepanel.setBackground(Color.RED);
}
public void mouseExited (MouseEvent event){
statusbar.setText("the mouse has left the window");
mousepanel.setBackground(Color.WHITE);
}
//these are mouse motion events

public void mouseDragged(MouseEvent event){ //hold down the

button

statusbar.setText("You are dragging the mouse");


}
public void mouseMoved(MouseEvent event){
statusbar.setText("You move the mouse");
}

Tutorial 77 Adapter Classes (mouse adapter class)


import java.awt.*; //colors, border lauyout, etc
import java.awt.event.*;
import javax.swing.*;
//we can responde to mouse events - click or move or etc
public class Gui extends JFrame{
private String details;
private JLabel statusbar;
public Gui(){
super("title");
statusbar = new JLabel("this is default");
add(statusbar,BorderLayout.SOUTH);
addMouseListener(new Mouseclass());
}
private class Mouseclass extends MouseAdapter{
public void mouseClicked(MouseEvent event){
details = String.format("You clicked %d",
event.getClickCount());
if (event.isMetaDown()) //you dont know what kind of mouse is
used, you assume all user are using the same 3 buttons.
details += "with right mouse button";
else if(event.isAltDown())
details += "with center mouse button";
else
details += "with left mouse button";
statusbar.setText(details);
}
}
}

Tutorial 78 File Class


Program to check if a file exists
import java.io.File;
class Apples {
public static void main (String[] args){
File x = new File("C:\\test\\greg.txt"); //with string, always use two \
if(x.exists())

else

System.out.println(x.getName()+"exist!");
System.out.println("this file doenst exist");

}
}

Tutorial 79 Creating Files


import java.util.*;
class Apples {
public static void main (String[] args){
final Formatter x; //output strings to a file

try{ //try this code


x = new Formatter("C:\\test\\fred.txt");
System.out.println("you created a file");
}
catch(Exception e){ //if error, do this
System.out.println("you got an error");
}

Tutorial 80 Writing to Files


import java.io.*;
import java.lang.*;
import java.util.*;
public class createfile {
private Formatter x;

file

public void openFile(){


try{
x = new Formatter("chinese.txt"); //if dont have, create this
}
catch (Exception e){
System.out.println("you have an error");
}
}
public void addRecords(){ //insert record into a file
x.format("%s%s%s", "20 ", "bucky ","roberts");
}
public void closeFile(){
x.close();
}
import java.util.*;

class Apples {
public static void main (String[] args){
createfile g = new createfile();
g.openFile();

g.addRecords();
g.closeFile();
}

Tutorial 81 Reading from Files


import java.io.*;
import java.util.*;
public class readfile {
private Scanner x;
public void openFile(){
try{
x = new Scanner(new File("chinese.txt"));
}
catch(Exception e){
System.out.println("could not find file");
}
}
public void readFile(){
while(x.hasNext()){
String a = x.next();
String b = x.next();
String c = x.next();
System.out.printf("%s %s %s \n", a,b,c);
}

}
public void closeFile(){
x.close();
}

class Apples {
public static void main (String[] args){
readfile r = new readfile();
r.openFile();
r.readFile();
r.closeFile();
}

Tutorial 82 Exception Handling


import java.util.*;
public class sample {
public static void main(String[] args){
Scanner input = new Scanner (System.in);
int x = 1;

do{
try{ //if you have an error hier inside the Try, its go to catch
System.out.println("Enter first num: ");
int n1 = input.nextInt();
System.out.println("Enter second num: ");
int n2 = input.nextInt();
int sum =n1/n2;
System.out.println(sum); //if divides by 0, an error will apear
x=2;
}
catch(Exception e){ //exception e catch all the errors
System.out.println("You cant do that");
}
}while(x==1);
}

Tutorial 83 FlowLayout
import java.awt.*; //colors, border lauyout, etc
import java.awt.event.*;
import javax.swing.*;
public class Layout extends JFrame {
private
private
private
private
private

JButton lb;
JButton cb;
JButton rb;
FlowLayout layout;
Container container;

public Layout(){
super("the title");
layout = new FlowLayout();
container = getContentPane();
setLayout (layout);

//left stuff in here


lb = new JButton("left");
add(lb);
lb.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event)
layout.setAlignment(FlowLayout.LEFT);
layout.layoutContainer(container);
}

);
//right stuff in here
rb = new JButton("right");
add(rb);
rb.addActionListener(
new ActionListener(){
public void
actionPerformed(ActionEvent event){

layout.setAlignment(FlowLayout.RIGHT);
layout.layoutContainer(container);
}

);
//CENTER stuff in here
cb = new JButton("center");
add(cb);
cb.addActionListener(
new ActionListener(){
public void
actionPerformed(ActionEvent event){
layout.setAlignment(FlowLayout.CENTER);
layout.layoutContainer(container);
}

);

}
}
import javax.swing.*;

class bucky {
public static void main (String[] args){
Layout go = new Layout();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(300,100);
go.setVisible(true);
}

Tutorial 84 Drawing Graphics


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Peach extends JPanel {
public void paintComponent(Graphics g){ //builded method inherited that
create all graphics in the screen
super.paintComponent(g);
this.setBackground(Color.WHITE);
g.setColor(Color.BLUE);
g.fillRect(25, 25, 100, 30);
g.setColor(new Color(190,81,215));
g.fillRect(25, 65, 100, 30);
g.setColor(Color.RED);

g.drawString("this is some text", 25, 120);


}
}
import javax.swing.*;
class bucky {
public static void main (String[] args){
JFrame f = new JFrame("Title");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Peach p = new Peach();
f.add(p);
f.setSize(400,250);
f.setVisible(true);
}

You might also like