Credits

Showing newest posts with label Java. Show older posts
Showing newest posts with label Java. Show older posts

Saturday, March 13, 2010

Java Applet's Life Cycle

Any Java Applet goes through four stages: initialization, start, stop and destroy. When an applet is run, it executes initialization once, then proceeds to  start method. However, should we minimize the applet, it stops its execution, then if restored, it goes to execute start again. The destroy method is only run if one chooses to close fully the window.


Find below a sample program to demonstrate the life cycle of an applet. 

[+/-] show/hide



import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class AppletLifeCycle extends Applet implements ActionListener {
Label messageInit = new Label("init ");
Label messageStart = new Label("start ");
Label messageDisplay = new Label("display ");
Label messageAction = new Label("action ");
Label messageStop = new Label("stop ");
Label messageDestroy = new Label("destroy ");
Button pressButton = new Button("Press");

int countInit,countStart,countDisplay,countAction, countStop,countDestroy;

public void init()
{++countInit;
add(messageInit);
add(messageStart);
add(messageDisplay);
add(messageAction);
add(messageStop);
add(messageDestroy);
add(pressButton);
pressButton.addActionListener(this);
display();
}

public void start()
{
++countStart;
display();
}

public void display()
{
++countDisplay;
messageInit.setText("init "+countInit);
messageStart.setText("start "+countStart);
messageDisplay.setText("display "+countDisplay);
messageAction.setText("action "+countAction);
messageStop.setText("stop "+countStop);
messageDestroy.setText("destroy "+countDestroy);

}

public void stop()
{
++countStop;
display();
}
public void destroy()
{
++countDestroy;
display();

}


public void actionPerformed(ActionEvent e)
{
++countAction;
display();
}
}

Saturday, March 6, 2010

Java's Border Layout

A Layout Manager arranges the sizes, location and arrangement of components inside a container. There are six different layouts that can be used. In this post, one useful layout is the border layout. Use this layout if you need five regions of your container: EAST, WEST, NORTH, SOUTH,  and CENTER.


Should only few regions are used, the unused regions shrunk to give space to the used portions. See sample program below to display a container with buttons on the set regions.

[+/-] show/hide



import java.awt.*;
import javax.swing.*;

public class BorderLayoutDemo extends JFrame{
JButton bN,bS, bE, bW;
Container con = getContentPane();

public BorderLayoutDemo()
{
bN=new JButton("North");
bS=new JButton("Center");
bE=new JButton("East");
bW=new JButton("West");

con.setLayout(new BorderLayout());

con.add(bN,BorderLayout.NORTH);
con.add(bS,BorderLayout.CENTER);
con.add(bE,BorderLayout.EAST);
con.add(bW,BorderLayout.WEST);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public static void main (String [] args){
BorderLayoutDemo frm = new BorderLayoutDemo();
frm.setSize(400,300);
frm.setTitle("Border Layout Demo");
frm.setVisible(true);
}
}

Friday, March 5, 2010

Java Applets

Applet is different from a typical Java application where it has to work with the Java environment itself. On the other hand, applet must work within another application like an HTML page. Thus, it requires a browser. 


The class name must be the compiled Java program. They are to be of the same location to work. Do check  the needed Java program below.


[+/-] show/hide



import java.applet.*;
import javax.swing.*;

public class AppletGreet1 extends Applet {
JLabel greeting = new JLabel("Hello world");

@Override
public void init()
{

add(greeting);

}

}

Tuesday, February 23, 2010

Java's Event Handling

Action events on Java's button are possible through their own event - handling methods.

A component must have a listener so it can execute the corresponding event methods.  Below is an example of event handling on action buttons.



[+/-] show/hide




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

public class ButtonActionEventv2 extends JFrame implements ActionListener
{
JButton redButton = new JButton("Red");
JButton greenButton = new JButton("Green");
JButton blueButton = new JButton("Blue");
JPanel pane=new JPanel();
public ButtonActionEventv2(){

setTitle("Button Action Event Frame");
setSize(300,150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

redButton.addActionListener(this);
pane.add(redButton);

greenButton.addActionListener(this);
pane.add(greenButton);
blueButton.addActionListener(this);
pane.add(blueButton);
add(pane);
setVisible(true);
}

public void actionPerformed(ActionEvent e){
Object source = e.getSource();
if (source==redButton)
pane.setBackground(Color.red);
else if (source==greenButton)
pane.setBackground(Color.green);
else pane.setBackground(Color.blue);

}

public static void main (String[] args){
ButtonActionEventv2 apps = new ButtonActionEventv2();

}
}

Monday, February 15, 2010

Java's Calendar Date

Java has a built - in class for setting date and time.  Find below a sample date and time Java program that gets an instance of the current system date and time, and displays this on the frame.



[+/-] show/hide




import java.awt.*;
import javax.swing.*;

public class ClockFrame extends JFrame {
public ClockFrame() {
super("Clock");
setSize(225, 125);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flo = new FlowLayout();
setLayout(flo);
ClockPanel time = new ClockPanel();
add(time);
setVisible(true);
}

public static void main(String[] arguments) {
ClockFrame clock = new ClockFrame();
}
}


import javax.swing.*;
import java.awt.*;
import java.util.*;

public class ClockPanel extends JPanel {
public ClockPanel() {
super();
String currentTime = getTime();
JLabel time = new JLabel("Time: ");
JLabel current = new JLabel(currentTime);
add(time);
add(current);
}

String getTime() {
String time;
// get current time and date
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int month = now.get(Calendar.MONTH) + 1;
int day = now.get(Calendar.DAY_OF_MONTH);
int year = now.get(Calendar.YEAR);

String monthName = "";
switch (month) {
case (1):
monthName = "January";
break;
case (2):
monthName = "February";
break;
case (3):
monthName = "March";
break;
case (4):
monthName = "April";
break;
case (5):
monthName = "May";
break;
case (6):
monthName = "June";
break;
case (7):
monthName = "July";
break;
case (8):
monthName = "August";
break;
case (9):
monthName = "September";
break;
case (10):
monthName = "October";
break;
case (11):
monthName = "November";
break;
case (12):
monthName = "December";
}
time = monthName + " " + day + ", " + year + " "
+ hour + ":" + minute;
return time;
}
}

Java's Scroll Pane

A scroll pane works as scroll bars particularly vertical and horizontal scrollers for a window with long lines of items.


But a scroll pane in Java works together with other components like text areas or a list. An example below shows a sample program with scroll pane and text area. 

[+/-] show/hide




//import java.awt.LayoutManager;
//import java.awt.*;
/*adding of components to frame without a panel*/
import java.awt.FlowLayout;
import javax.swing.*;
public class GUIQuiz2 extends JFrame{

public GUIQuiz2(){
setSize(220,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel toLabel= new JLabel("To: ",SwingConstants.LEFT);
JLabel fromLabel= new JLabel ("From:",SwingConstants.LEFT);
JLabel messageLabel = new JLabel (" Message:",JLabel.LEFT);
JTextField toField=new JTextField("Receiver's name",15);
JTextField fromField = new JTextField("Sender's name",15);
JTextArea msgArea= new JTextArea("Write your message here.",4,15);
msgArea.setLineWrap(true);
msgArea.setWrapStyleWord(true);
JScrollPane scrollpane=new JScrollPane(msgArea);
FlowLayout flo=new FlowLayout();

setLayout(flo);
add(toLabel);
add(toField);
add(fromLabel);
add(fromField);
add(messageLabel);
add(scrollpane);

setVisible(true);
}
public static void main (String args[]){
GUIQuiz2 myFrame=new GUIQuiz2();
}
}

Java's Buttons

Buttons are used to at least have a corresponding action once they are clicked  like when we click Save Button on a Microsoft Window Environment.

Buttons can be created either through the java.awt or javax.swing with a little modification. Find below a sample program made with Swing components.

[+/-] show/hide




import javax.swing.*;
import java.awt.*;

public class PlayBack extends JFrame {
public PlayBack() {
super("My Player");
setBounds(300,200,450, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
FlowLayout flo = new FlowLayout();
setLayout(flo);
JButton play = new JButton("Play");
JButton stop = new JButton("Stop");
JButton pause = new JButton("Pause");
JButton rewind = new JButton("Rewind");
JButton forward = new JButton("Forward");
add(play);
add(stop);
add(pause);
add(rewind);
add(forward);
}

public static void main(String[] arguments) {
PlayBack pb = new PlayBack();
pb.setVisible(true);
}
}

Java's Action Event and Listener

If buttons are clicked and  we expect to have some actions, then we associate an action event on these components. 


To integrate events for buttons, we associate ActionEvent and ActionListener to respond to events.

[+/-] show/hide




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

public class ButtonActionEventv2 extends JFrame implements ActionListener
{
JButton redButton = new JButton("Red");
JButton greenButton = new JButton("Green");
JButton blueButton = new JButton("Blue");
JPanel pane=new JPanel();
public ButtonActionEventv2(){
    
setTitle("Button Action Event Frame");
setSize(300,150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
redButton.addActionListener(this);
pane.add(redButton);

greenButton.addActionListener(this);
pane.add(greenButton);
blueButton.addActionListener(this);
pane.add(blueButton);
add(pane);
setVisible(true);
}

public void actionPerformed(ActionEvent e){
Object source = e.getSource();
if (source==redButton)
pane.setBackground(Color.red);
else if (source==greenButton)
pane.setBackground(Color.green);
else pane.setBackground(Color.blue);

}

public static void main (String[] args){
ButtonActionEventv2 apps = new ButtonActionEventv2();

}
}

Java's KeyListener

Events are handled in Java through Event handlers and listeners. For every listener, there is a corresponding event handler. There are methods associated with this interface and shall be worked with even it means doing nothing.


Below is an application of key listener. 

[+/-] show/hide



/*responding to user input*/
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class KeyViewerGUI extends JFrame implements KeyListener {
JTextField keyText = new JTextField(80);
JLabel keyLabel = new JLabel("Press any key in the text field.");

KeyViewerGUI() {
super("KeyViewer");
setSize(350, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
keyText.addKeyListener(this);
BorderLayout bord = new BorderLayout();
setLayout(bord);
add(keyLabel, BorderLayout.NORTH);
add(keyText, BorderLayout.CENTER);
setVisible(true);
}

public void keyTyped(KeyEvent input) {
char key = input.getKeyChar();
keyLabel.setText("You pressed " + key);
}

public void keyPressed(KeyEvent txt) {
// do nothing
}

public void keyReleased(KeyEvent txt) {
// do nothing
}

public static void main(String[] arguments) {
KeyViewerGUI frame = new KeyViewerGUI();
}
}

Sunday, February 14, 2010

Java's GUI List

Another interesting component in Java is a list that actually displays n items.  Unlike a combo box, a scroll pane can be integrated with a list and that one or multiple items can be selected. 


To define a list, use JList  class.  It can have any of the following constructors:

JList() - creates an empty list;

JList(Object [])- creates an array object;

JList  (Vector) - creates a vector object in a list.

Use setVisibleRowCount(parameters) to define the number of items to be displayed on the list.


[+/-] show/hide



import javax.swing.*;
import java.awt.*;

public class ListGUI extends JFrame {
String[] jobs={"Programmer","Analyst","Network Administrator","DB Administrator","System Auditor"};
JList jobList=new JList(jobs);
public ListGUI() {
super("List");
setSize(345, 120);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

FlowLayout flo = new FlowLayout();
jobList.setVisibleRowCount(3);
JScrollPane scroller=new JScrollPane(jobList);

setLayout(flo);
add(scroller);
setVisible(true);
}

public static void main(String[] arguments) {
ListGUI app = new ListGUI();
}
}

Saturday, February 13, 2010

Java's Text Components

An interactive Java  would require a text input in single or  multiple lines. Java has text fields and text areas where inputs of all sorts can be used.


A text field  can be defined using JTextField and a text area under JTextArea classes. Check the sample program below that uses text fields, text areas, labels and buttons. 

[+/-] show/hide



 
/*adding of components to frame without a panel*/
import java.awt.FlowLayout;
import javax.swing.*;
public class GUIQuiz2 extends JFrame{
// private LayoutManager FlowLayout;
public GUIQuiz2(){
super("Message Form");
setSize(220,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
JLabel toLabel= new JLabel("To: ",SwingConstants.LEFT);
JLabel fromLabel= new JLabel ("From:",SwingConstants.LEFT);
JLabel messageLabel = new JLabel (" Message:",JLabel.LEFT);
JTextField toField=new JTextField("Receiver's name",15);
JTextField fromField = new JTextField("Sender's name",15);
JTextArea msgArea= new JTextArea("Write your message here.",4,15);
msgArea.setLineWrap(true);
msgArea.setWrapStyleWord(true);
JScrollPane scrollpane=new JScrollPane(msgArea);
FlowLayout flo=new FlowLayout();
    
setLayout(flo);
add(toLabel);
add(toField);
add(fromLabel);
add(fromField);
add(messageLabel);
add(scrollpane);
    
setVisible(true);
}
public static void main (String args[]){
GUIQuiz2 myFrame=new GUIQuiz2();
}
}

Java Combo Box

Another GUI component of Java is a combo box. This is a short drop - down list that allows a user to select an option.

To create this component, use the JComboBox class. Check the sample program below. 

[+/-] show/hide




import javax.swing.*;
import java.awt.*;

public class ComboBoxes extends JFrame {
public ComboBoxes() {
super("Combo Boxes");
setSize(345, 120);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JComboBox profession = new JComboBox();
FlowLayout flow = new FlowLayout();
profession.addItem("Programmer");
profession.addItem("Analyst");
profession.addItem("Programmer");
profession.addItem("Database Administrator");
profession.addItem("Network Administrator");
profession.addItem("Project Manager");
setLayout(flow);
add(profession);
setVisible(true);
}

public static void main(String[] arguments) {
ComboBoxes app = new ComboBoxes();
}
}

Java's Check Boxes

Java has several GUI components, one of the commonly used components is a check box. This is non - exclusive like a radio button, meaning for several check boxes, they can all be selected. But to make the components exclusive, then they have to be grouped using the ButtonGroup class. 

Check the sample below.



[+/-] show/hide



import javax.swing.*;
import java.awt.*;

public class CheckBoxes extends JFrame {
public CheckBoxes() {
super("CheckBoxes");
setSize(300, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel jobLabel=new Jlabel("Select job position:");
JCheckBox programmer = new JCheckBox("Programmer",true);
JCheckBox analyst = new JCheckBox("Analyst");
JCheckBox sysadmin = new JCheckBox("System Administrator");
JCheckBox dbadmin = new JCheckBox("Database Administrator");
FlowLayout flo = new FlowLayout();
ButtonGroup jobs = new ButtonGroup();
jobs.add(programmer);
jobs.add(analyst);
jobs.add(sysadmin);
setLayout(flo);
add(jobLabel);
add(programmer);
add(analyst);
add(dbadmin);
add(sysadmin);
setVisible(true);
}

public static void main(String[] arguments) {
CheckBoxes app = new CheckBoxes();
}
}

Into Java GUI's

Prior to Midterm exam with STI, I was supposed to cover Graphical User Interface topics but with limited time, I missed covering this section.


When I made my Java Programming project in my masteral in IT, it was indeed a great struggle. I made use of NetBeans 6.1 with Jasper Reports and MySQL, and the General Ledger System I made for our store was the humble accomplishment from months of programming.


So, now that I teach GUI programming but only with JCreator,  I find the designing and coding more difficult.  


I only wish that my students shall use Java in their future projects but with the ordeal they go through writing simple Java programs, my wish seems to be remote and impossible.  I think with my students and Java experience, we can only choose to have fun while learning Java. 


Thursday, February 4, 2010

Teaching GUI of Java

Graphical User Interface (GUI) allows interaction of user with the system. Java like any object - oriented languages does allow GUI in different ways. These include actions with buttons, check boxes, list, scroll bar, textboxes, and others. 


GUI components take the standard javax.swing and jawa.awt as the fundamental classes for instantiating objects.


Java in 21 days provides easy - to - understand examples.  Check the program below that makes a text area.  

[+/-] show/hide




import javax.swing.*;
import java.awt.*;

public class TextArea extends JFrame {
public TextArea() {
super("TextArea");
setSize(500, 180);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea comments = new JTextArea(8, 40);
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(comments);
setVisible(true);
}

public static void main(String[] arguments) {
TextArea app = new TextArea();
}
}

Friday, January 22, 2010

Java's Thread

Java makes use of Thread to allow multi-tasking or programming. Threads can be created either through extending the Thread class or implementing Runnnable interface.


The program below shows a simple use of a Thread. It shall display  n number  "This is a sample one." and another n number of  of " This is a sample two."  With multi-threading, there is no precise pattern as to the output since OS will determine the resources including time to which activity shall be done first and for how long.  Thus, multiple runs of this program may produce different results. 





[+/-] show/hide




class SampleThread1 extends Thread
{
public void run()
{
  for(int x=1;x<=25;x++) System.out.println("This is a sample one!"); }}  

class SampleThread2 extends Thread
{
public void run()
{
  for(int x=1;x<=25;x++) System.out.println("This is a sample two!"); }}  
class SentenceThread {
public void main(String[] args) {
SampleThread1 myFirst= new SampleThread1();
SampleThread2 mySecond= new SampleThread2();
myFirst.start();
mySecond.start();}}  

Friday, January 15, 2010

Java's Random Access File

Processing of records is faster once there is an instant search for any of the record. Java provides Random Access File that extends from the Object class and inherits DataInput and DataOutput interface.


Do check the program below that allow an added input or entry to an existing file.

[+/-] show/hide




/*use of Random Access File */

/* program must add to end of data.txt the new text*/
import java.io.*;
public class RandAccessFile{
public static void main(String [] args) throws IOException{
BufferedReader in = new BufferedReader (new InputStreamReader (System.in));
System.out.print("Enter file name: ");
String str=in.readLine();

File file = new File ("\\Documents and Settings\\Rose\\My Documents\\NetBeansProjects\\SampleExercises\\src\\",str);
if (!file.exists())
{
System.out.println("File does not exist.");
}
try{
//open aa file for both reading and writing
RandomAccessFile rand=new RandomAccessFile(file,"rw");
rand.seek(file.length()); //seek to end of file
rand.writeBytes("This is my new text."); //write to end of file
rand.close();
System.out.println("Write successfully.");
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
}

Thursday, January 14, 2010

File Class of Java

In Java, the use of File class is possible. One can actually check information about the file like its existence, modification dates, and size.


I have the program below to check whether a certain file exists.  It is however, important that if there really is a file, the location path must be correct.



[+/-] show/hide




import java.io.*;
public class checkFile{
public static void main(String args[]){
File f=new File("C:\\Documents and Settings\\Rose\\My Documents\\NetBeansProjects\\SampleExercises\\src\\","data.txt");
if (f.exists())
{
System.out.println(f.getName()+" exists.");
System.out.println("The file is "+f.length()+" bytes long" );
if (f.canRead())
System.out.println(" Ok to read.");
if (f.canWrite())
System.out.println(" ok to write.");
}
else
System.out.println("File does not exist.");
}
}

Wednesday, January 13, 2010

Another Java Throw Program

 Here is another Java use of throw with exceptions.  

[+/-] show/hide




/* Creating Throwable Class */

import java.io.*;
public class RateCalc{
public static int calcInsurance(String birth) throws Exception{
final int year = 2010;
int age=0;
int birthYear = Integer.parseInt(birth);
age=year - birthYear;
if (age < 16)
{ throw new Exception ("Age is: "+ age);}
else
{
int drivenYears = age - 16;
if (drivenYears<4)
return 1000;
else
return 600;
}
}

public static void main (String[] args) throws IOException{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String inData = null;
System.out.println("Enter birth year: ");
inData = stdin.readLine();

try
{
System.out.println(" Your insurance is : "+calcInsurance(inData));
}
catch(Exception oops)
{
System.out.println("Too young for insurance!");}
}
}




Java's Throw Clause

Exceptions are errors that may occur because of invalid input, logic mistakes or programmer's omission or commission.  But, in Java these can be handled through some methods or can be remedied with better programming solutions.


Using try . . . catch and finally blocks, exceptions can be thrown and caught. Check the sample program below that throws an exception message once a negative integer is tried for square root. 

[+/-] show/hide




/* Square Root of an integer */
import java.io.*;
class ThrowDemo1
{ public static void main (String args[])throws IOException{
BufferedReader br=new BufferedReader (new InputStreamReader (System.in ));
System.out.println("Enter an integer: ");
int num=Integer.parseInt(br.readLine());
try{

if (num<0)
throw new ArithmeticException();
else
System.out.println("Square root of "+num+" : "+Math.sqrt(num));
}
catch (ArithmeticException ae)
{
System.out.println("Negative number is not allowed.");
}
}
}