Java
PREVIOUS
NEXT
Java graphics - paint and repaint
draw simple graphics with Java - with exampleThere are many graphics which can be drawn in Java, and here is a rundown of the syntax:
A line:
public abstract void drawLine(int x1, int y1, int x2, int y2);
An outlined rectangle:
public abstract void drawRect(int x, int y, int width, int height);
A Filled rectangle:
public abstract void fillRect(int x, int y, int width, int height);
A rectangle with fill of the background color:
public abstract void clearRect(int x, int y, int width, int height);
An Oval outline:
public abstract void drawOval(int x, int y, int width, int height);
A filled oval
public abstract void fillOval(int x, int y, int width, int height);
An outline of a polygon, where the x and y are arrays of coordinates:
public abstract void drawPolygon(int[] x, int[] y, int numEdges);
A filled polygon, where the x and y are arrays of coordinates:
public abstract void fillPolygon(int[] x, int[] y, int numEdges);
Every graphics object has many attributes, the most obvious being it... Read More
Java Enumeration and Iterators
What and how to use Enumerationa and IteratorsDefenitions:
Set: an unordered array of elements or objects
Collection: an ordered set
*Vectors already implement the Collection interface, but you can define your own Collection.
*ArrayLists and Vectors, both support Iterators
Enumeration
An enumeration is an object that generates elements one at a time, used for passing through a collection, usually of unknown size.
The traversing of elements can only be done once per creation.
Enumeration's have two options:
nextElement() which returns the next object in the collection
hasMoreElements() which returns true, until the last object has been returned by nextElement()
Code Example:
import java.util.Vector;
import java.util.Enumeration;
public class EnumerationTester {
public static void main(String args[]) {
Enumeration days;
Vector dayNames = new Vector();
dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add... Read More
Java: text file IO - output (swing)
the output of text files in JavaThe output streams in Java may throw exceptions (the recipe on Exceptions should probably be read first, assuming i've written already), so these cases must be handled or caught.
The easier of the 2 IO options is output, so we will start with that:
Keep in mind that there are many ways to output text in Java, this recipe covers a couple of the more basic ways.
The 2 exceptions that must be handled are:
java.io.FileNotFoundException
-which occurs if the specified input or output file cannot be found or created.
and
java.io.IOException
-which occurs if any other form of IO error occurs, such as a buffer overrun, underrun, corruption of data, and many other issues.
*be sure to import the java.io.* if you do not know the exact extension of the stream you are using.
Code Example:
/*This first example uses the most basic (I think) of all the output streams, the FileOutputStream */
import java.io.*;
public class FileOutputStreamTest {
public static void main(St... Read More
Java: text file IO - input (swing)
the input of text files in JavaNow to read in the files created in the output recipe:
*These code segments will simply read the *.dat files to the console, but they can easily be re-directed to a JTextArea, or JList, etc.
When reading a file in, there are 3 exceptions that can be thrown
java.io.EOFException
-which occurs if the End Of File marker is not found, this marker is automatically placed on a file with the .close() method and resembles the symbol /0.
java.io.FileNotFoundException
-which occurs if the file specified does not exist or cannot be opened
and
java.io.IOException
-which occurs if any other form of IO error occurs, such as a buffer overrun, underrun, corruption of data, and many other issues.
CODE example:
/*This example reads a text file with FileInputStream */
import java.io.*;
public class FileInputStreamTest {
public static void main(String args[]) {
try {
FileInputStream in = new FileInputStream("myFile.dat");
while(in.available() > 0)
System.out.print((char)in.re... Read More
Java: Standard Dialog Boxes (swing)
Displaying The Standard Dialog Boxes in Java*NOTE*This recipe simply shows how to use the code, to display the dialog boxes, if you require a fully coded example including buttons, and JFrame, please E-mail the address below.
There are many different dialog boxes that come standard with Java, including:
* General
* Warning
* Error
* Information
* Question/Confirmation
* Input
* Option (many variations on this one)
-the option of text, icon and which button options to choose is all for you to decide, based on the type of dialog you choose.
In each exmaple below, the option this can be left as is, or -as is recommended- replaced with the name of the class/object that called it.
The First String will be the text displayed in the window, and the second String will be the title of the dialog. The main difference in the dialog types are the button options, and the displayed icon.
General:
JOptionPane.showMessageDialog(this, "General msg", "General", JOptionPane.PLAIN_MESSAGE);
Warning:
JOpti... Read More
Java: Object file IO - output (swing)
outputing a file with objects instead of text.Simlarly to ouputing text, but there are a few key differences:
-If the Object is of your own personal class/creation, it needs to implement java.io.serializable, the implmentation and reasons will be described in the serializable recipe.
-the stream used is: java.io.ObjectOutputStream
-there is only one output command, as all items output must be objects, ie String, Integer, etc, either by using wrappers (discussed under wrapper recipe), or as an Object by default.
*All Java supplied Objects are serializable
Since a String is an object (array of chars as a class), I will use it here, but if Integers the objects not the the elementary variable int then the objects are not recognizable in the output file, as they are serialized.
ObjectStream can only throws one main error
IOException: thrown when there is an error writting to, or creating the specified file.
CODE example:
import java.io.*;
public class ObjectStreamExample{
public static void... Read More
Java: Object file IO - input (swing)
reading in a file with objects instead of text.Simlarly to inputing text, but there are a few key differences:
-If the Object is of your own personal class/creation, it needs to implement java.io.serializable, the implmentation and reasons will be described in the serializable recipe.
-the stream used is: java.io.ObjectInputStream
-there is only one output command, as all items output must be objects, ie String, Integer, etc, either by using wrappers (discussed under wrapper recipe), or as an Object by default.
*All Java supplied Objects are serializable
The file attempted to be read is the myFile3.dat created in Java: Object file IO - output (swing)
ObjectStream can only throws one main error
IOException: thrown when there is an error reading from the specified file.
CODE example:
import java.io.*;
public class ObjectStreamExample{
public static void main(String args[]){
try{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("myFile3.dat"));
String s = (String)in.readOb... Read More
Java: Serializable
The Interface: 1) It's uses 2) Why it's important 3) How to implement itjava.io.Serializable
an important addition when saving your own personal objects.
The method reading in the object from a file, must either handle the errors on it's own, or throw them to be caught elsewhere:
IOException: thrown upon a read error
and
ClassNotFoundException: thrown if the class has been modified, since being written, or an unknown object type is found.
The method writting the file must either handle the error on it's own, or throw them to be caught elsewhere:
IOException: thrown upon a read error
*These errors are all subclasses of Exception and if you are not concerned w/ specific errors can be grouped into a single catch block as i have done here.
Code Example:
import java.io.*;
import java.util.*; //Vector use
public class ObjectTest{
public void readObject(){
try{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("myFile3.dat"));
Vector v = (Vector)in.readObject();
in.close();
Sys... Read More
Java: Constructors
use and creation of constructors*I used a constructor in my example under serializable.
A constructor is a method with the same name as the class it is defined in, and is automatically called with the operator new.
CODE example:
public class Constructor{
public static class Objects implements java.io.Serializable{
String text;
public Objects(){
text = "William. ";
}
public Objects(String s){
text = s;
}
}
public static void main(String args[]){
//create an object initialized by the constructor
Objects o = new Objects();
System.out.println(o.text); //the output is William. since that is the text provided in the default constructor.
//create another object initialized with text supplied
Objects o2 = new Objects("Wilson");
System.out.println(o2.text); //the text within the object o2 is Wilson since we supplied it
}
}
This example uses 2 different constructors in the same class Objects, this is possible only because the parameter list is different for the 2 constructors, and is possible fo... Read More
Java: toString
Teach an Object how to print itself, just by saying it's name.*I used the ToString method in my example under serializable.
The ToString() could quite possibly be the most usefull method i've ever used, since it is the most versitile, and handy for debugging.
It uses the syntax:
public String ToString(){
return ;
}
This method is called when asked to print an Object, to include it allows you to specify what is to be printed when the object is called.
Unlike any other type of method this method is implied and it is not necessary to add .toString() on the end of the object.
All spellings of the toString are as i have layed them out, and it NEVER takes any parameters, and only returns a String. Simple calculations can be done before hand, but if at all possible, stylistically this is not the place for them.
CODE example:
public class ToStringExample{
public static class Objects implements java.io.Serializable{
String text;
public Objects(){
text = "William. ";
}
public Objects(String s){
... Read More
Java: Exceptions - Try, Catch and Finally
Method by method handling of errors and exceptionsIt should be noted that all exceptions that can be generated, are subclasses of the class java.lang.throwable.Exception. With this in mind, and the idea of a heirarchy of errors, it is possible to write effective, and working exception try, catch and finally blocks.
When adding the exceptions the order in which they appear MUST be in an upward order. What i mean by this is, that you work from lower subclasses towards the superclass [/b]Exception[/b].
If theses exceptions are written in the opposite order, then the lower catch blocks are useless, since a superclass will catch exceptions found in it's subclasses.
An example of what not to do:
try{}
catch(Exception e){}
catch(IOException e){}
*in this case Exception is the top class and is above IOException, and the code within IOException will NEVER be excecuted, even in the instance of an IO error, since Exception will handle all errors.
The correct way to do the above:
try{}
catch(IOExc... Read More
Java: Exceptions - Throwing
the throwing of exceptions to be caught elsewhereIt should be noted that all exceptions that can be generated, are subclasses of the class java.lang.throwable.Exception. With this in mind, and the idea of a heirarchy of errors, it is possible to write effective, and working throwable exceptions combined with knowledge of try and catch blocks.
When dealing with throwing exceptions, the somewhere in the trace of method calls, the error must be caught. As before try and catch blocks are needed, but not in every method.
CODE example:
public class ExceptionTester5 {
private static int quotient(int numerator, int denominator) throws ArithmeticException {
if (denominator == 0)
throw new ArithmeticException();
return(numerator / denominator);
}
public static void main(String args[]) {
int number1=0, number2=0, result=0;
try {
number1 = 1;
number2 = 0;
result = quotient(number1,number2);
System.out.print(number2 + " goes into " + number1);
System.out.println(" this many times: " + result);
}
ca... Read More
Java: Exceptions - Writting your own
writting your own Exceptions (It's really quite simple)Writting your own Exceptions is simply a case of syntax and knowing how exceptions work. If you haven't already done so I suggest reading the previous 2 recipes on Try/Catch/Finally and Throwing Exceptions.
*This recipe will combine the ideas used in the last 2, and add to them, a brand new object class, as a subclass of Exception written by me, to be implemented as a new Exception. (It's really quite simple)
First we need an Exception class:
I am going to design a class to take the place of the ArithmeticException class, for the case of dividing by zero.
There are 2 key things to remember when writting an Exception class:
1) it must extend Exception, either directly or indirectly(through one of it's subclasses)
2) The constructor needs to call super() with the text to be placed into .Message and for it's toString().
*All other information, such as Stack Trace is done automatically by the JVM.
CODE example:
public class DivideByZer... Read More
Java: Packages
Clean up your class files, by using your own packages.Have you ever wanted to clean up a folder FULL of .class files, and sort them into folders based on their use?
Or just put the program into a folder so all that is visible is a single .exe, or .bat, or .java?
*Well my friend here is how!
All that is requried is a few lines:
An example seems the best way to go:
I'll have 3 class files:
1) program.java
2) GUI.java
3) run.java
suppose i want to put program and GUI into folders based on their use, and leave run at the same level as these folders.
I will assume that GUI and program don't need to know about each other, and run, needs access to both.
Ending File Heirarchy:
GUI.java
program.java
run.class
run.java
PROGRAM <--this is a folder
|
---------program.class
GUI <----this is a folder
|
-----------GUI.class
NOTE that as long as you do not wish to modify a .class file, AND it is not needed to run your program, the corresponding .java file is not necessary, and can be deleted.
To... Read More
Java: Null Layout Manager (swing)
how to use the Null Layout ManagerLayout Managers are used in the orginization of Panels and Frames. The proper layout should be chosen to accomodate, frame resizings and use.
+ signs represent empty space.
Null:
*No Layout, items must be manually positioned and arranged.
This layout should only be used if the window will not and cannot be resized, as the item in the window will stay where they are placed, be that hidden or[b] clumped in one corner of a window.
This Layout is [b]Very simple to use, but is not all that professional so be careful where you use it.
CODE example:
import java.awt.event.*;
import javax.swing.*;
public class NoLayoutExample extends JFrame {
public NoLayoutExample(String name) {
super(name);
JTextField newItemField;
JList itemsList;
JButton addButton;
JButton removeButton;
getContentPane().setLayout(null);
//The text field
newItemField = new JTextField();
newItemField.setLocation(12,12);
newItemField.setSize(150,30);
getContentPane().add(newItemField);
//The A... Read More
Java: Flow Layout Manager (swing)
how to use the Flow Layout ManagerLayout Managers are used in the orginization of Panels and Frames. The proper layout should be chosen to accomodate, frame resizings and use.
+ signs represent empty space.
Flow:
---------------------------
| Frame Title |▄|▐ |X|
---------------------------
| item1 -> item2 ->++|
| item3 ->... ++++++|
|++++++++++++++|
|++++++++++++++|
----------------------------
*Items are placed in a flow pattern, one after another left to right and top
to bottom. (If the direction chosen is LEFT, other choices are available)
It is similar to the null layout, but the flow layout arranges the items for you, with a speficied horizontal and vertical gap, all defined within the 3 constructors allowed in this layout:
public FlowLayout();
-the default constructor, with default values supplied, they should be:
align = LEFT
hGap = 0
vGap = 0
*but you may want to check that this has stayed the same in updates to the JVM
public FlowLayout(int align);
-where only th... Read More
Java: Border Layout Manager (swing)
how to use the Border Layout ManagerLayout Managers are used in the orginization of Panels and Frames. The proper layout should be chosen to accomodate, frame resizings and use.
+ signs represent empty space.
Border:
---------------------------
| Frame Title |▄|▐ |X|
---------------------------
|++++Top Item+++++ |
|++++++ _++++++++|
|Left Item|_|Right Item|
|+++++++++++++++ |
|++Bottom Item+++++|
----------------------------
_
|_| can be a Center Item
*Items can be placed along the border/edges of a frame.
This time there is are only 2 constructors, the default and one in which the horizontal and vertical gap, must be supplied.
public BorderLayout()
public BorderLayout(int hgap, int vgap)
This layout manager is fairly straight forward, so the best way to learn it is with an example.
CODE Example:
import java.awt.*;
import javax.swing.*;
public class BorderLayoutManagerExample extends JFrame {
public BorderLayoutManagerExample (String title) {
super(title);
Container conten... Read More
Java: Card Layout Manager (swing)
how to use the Card Layout ManagerLayout Managers are used in the orginization of Panels and Frames. The proper layout should be chosen to accomodate, frame resizings and use.
+ signs represent empty space.
Card:
--------------------------- --------------------------- ---------------------------
| Frame Title |▄|▐ |X| | Frame Title |▄|▐ |X| | Frame Title |▄|▐ |X|
--------------------------- --------------------------- ---------------------------
|++++++++++++++| |++++++++++++++| |++++++++++++++|
|++++++++++++++| |++++++++++++++| |++++++++++++++|
|++++ Card 1 ++++ | | ++++ Card 2 ++++| |++++ Card 3 ++++ |
|++++++++++++++| |++++++++++++++| |++++++++++++++|
|++++++++++++++| |++++++++++++++| |++++++++++++++|
---------------------------- --------------------------- ----------------------------
*Where all 3 Cards are the same frame, displayed at different times.
There are 2 available constructors for this manager, just like the border layout:
public CardLa... Read More
Java: Grid Layout Manager (swing)
how to use the Grid Layout ManagerLayout Managers are used in the orginization of Panels and Frames. The proper layout should be chosen to accomodate, frame resizings and use.
+ signs represent empty space.
Grid:
This Layout is useful for aligning elements or items onto a grid. The items will be added left to right across each row, and continuing at the beginning of the next row, similar to that of the Flow layout. This layout does have the draw back that the NULL layout does, as it aligns items according to a set size of rows and columns, and shrinking the frame beyond a resonable size will hide items.
There are 2 constructors:
public GridLayout(int rows, int columns)
-which takes only the rows and columns you wish to have mapped out
public GridLayout(int rows, int columns, int hGap, int vGap) throws IllegalArgumentException;
-which takes the rows and columns to be mapped out as well as the horizontal and vertal gaps to place between the items.
CODE Example:
import java.awt.*;
import ... Read More
Java: Wrapper Classes
Decription on going to and from the java Object wrapper classes.Wrapper classes to exactly what they say, they wrap primitive types (eg: int, double, etc) in Objects which can be placed into Vectors, and many, many other uses.
*Notice that an Object starts with a capital letter, while the primitives all start with a lowercase. Also notice that Strings are Ojects.
These Wrapper classes can be created in many ways, so i will start slow, simply returning objects with a String.
Integer from String:
Integer i = Integer.valueOf("125");
Double from String:
Double d = Double.valueOf("5.829754097");
Float from String:
Float f = Float.valueOf("8.43543");
Boolean from String:
Boolen b = Boolean.valueOf("true");
//This will represent true
Character from String:
Character c = Character.valueOf("G");
The more common use is given the primitive in a variable. This next section shows how to convert a variable to these wrapper classes and back to a primitive.
Integer:
int i = 5;
Integer I = Integer.valu... Read More