Professional Documents
Culture Documents
import java.lang.System;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.io.IOException;
FileInputStream inStream =
new FileInputStream ("test.txt");
int inBytes = inStream.available();
System.out.println ( "The inStream has " + inBytes + " bytes
available.");
byte inBuf[]=new byte[inBytes];
int bytesRead = inStream.read ( inBuf, 0, inBytes);
System.out.println ( bytesRead + " bytes were read.");
System.out.println ("They are: " + new String (inBuf) );
inStream.close();
File f = new File ("test.txt");
f.delete();
}
}
In the above program:
The FileOutputStream constructor creates an output stream for the
file “test.txt”. The file is automatically created in the current working
directory. Then the program writes the string "This is a test." to the
output file stream. The output stream is closed to make sure that all
data are written to the file.
The file is then reopened as an input file by creating an object of
class FileInputStream. Method avaiable() is used to determine the
number of available bytes in the file and method read (-,-,-) is used to
read these bytes into a byte array. The input stream is closed and
then a File object is created to provide access to the file. The program
then uses the method delete( ) to delete the file.
The program's output is given by:
The inStream has 15 bytes available.
15 bytes were read.
They are: This is a test.
Text Input
JTextField (text fields): single line of text
JTextArea (text areas): multiple lines of text
Both inherit from the abstract class JTextComponent.
For text fields (p.378):
JPanel p = new JPanel ();
JTextField tf = new JTextField ("Default input", 20);
// Adds a text field and initializes its content;
sets the width equal to 20 columns.
p.add (tf);
tf.setText ( "HKBU");
//Changes the content of the text field.
tf.setColumn (10);
// Change the size of the text field.
p.validate();
// Recompute the size and layout of all components in a container.
String s = tf.getText().trim();
// Return the exact text and trim any extraneous spaces for the data in
the text field.
interface DocumentListener (3 methods)
insertUpdate(..)
character(s) inserted
removeUpdate(..)
character(s) deleted
changedUpdate(..)
changed in formatting, etc.
panel.add(new JLabel("Hours:"));
hourField = new JTextField("12", 3);
panel.add(hourField);
hourField.getDocument().addDocumentListener(listener);
panel.add(new JLabel("Minutes:"));
minuteField = new JTextField("00", 3);
panel.add(minuteField);
minuteField.getDocument().addDocumentListener(listener);
add(panel, BorderLayout.SOUTH);
// add the clock
For text areas, the user can enter any number of lines of text, using
the ENTER key to separate them.
JTextArea textArea = new JTextArea (8, 40);
// 8 lines of 40 columns
frame.add (textArea);
Internally, each line ends with '\n'.
textArea.setLineWrap (true); // long lines are wrapped
visually; no '\n' characters are inserted into the text.
Automatic Scrolling
textArea = new JTextArea ( 8, 40 );
JScrollPane scrollPane = new JScrollPane( textArea );
frame.add( scrollPane, BorderLayout.CENTER );
JPasswordField
The characters that the user entered are not actually displayed, bu
represented by an echo character (typically ‘*’).
JPasswordField( String text, int columns)
Radio Buttons
ButtonGroup group = new ButtonGroup();
JRadioButton smallButton = newJRadioButton( “Small”, false );
group.add( smallButton );
JRadioButton mediumButton = newJRadioButton( “Medium”,
false );
group.add( mediumButton );
Sliders
JSlider slider = new JSlider(min, max, initialValue); // default: 0, 100, 5
JSlider slider = new JSlider(SwingConstants.VERTICAL, min, max,
initialValue);
ChangeEvent, addChangeListener(), stateChanged()
snap to ticks – move slider to closest tick
// common listener for all sliders
listener = new ChangeListener()
{
public void stateChanged(ChangeEvent event)
{
// update text field when the slider value changes
JSlider source = (JSlider) event.getSource();
textField.setText("" + source.getValue());
}
};
#DocumentListener getText
TextComponent
insertUpdate
removeUpdate
changedupdate
#ListSelectionListener
valueChanged getSource List
Adapter Classes
Implementing six methods that do nothing is a tedious work. To
simplify this work, each of the listener interfaces that has more than
one method comes with a companion adapter class that implements
all the methods in the interface but does nothing with them.
For example, the WindowAdapter class has seven do-nothing
methods. This means the adapter class automatically satisfies the
technical requirements of using interface.
These are adapters:
WindowAdapter, ComponentAdapter, ContainerAdapter,
FocusAdapter,
KeyAdapter, MouseAdapter, MouseMotionAdapter.
The keyTyped event reports the characters that were typed (‘A’)
whereas the keyPressesd and keyReleased events report on the raw
keystrokes (representing by the virtual key codes).
When we override the method keyPressed and keyReleased, we use
the getKeyCode method to obtain the virtual key code:
void keyPressed ( keyEvent evt) {
int keyCode = evt.getKeyCode ();
}
When we override the keyTyped method, we use the getKeyChar
method to obtain the actual character typed:
char keyChar = evt.getKeyChar();
if (find(event.getPoint()) == null)
setCursor(Cursor.getDefaultCursor());
else
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
}
public void mouseDragged(MouseEvent event)
{
if (current != null)
{
int x = event.getX();
int y = event.getY();
// drag the current rectangle to center it at (x, y)
current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2,
SIDELENGTH, SIDELENGTH);
repaint();
}
}
}
Actions
to separate the responsibilities of getting user input and executing
commands;
multiple ways to activate the same command: menu, keystroke,
button, etc.
one class object for each command;
one listener for multiple event sources
Mulicasting
One event source, many listeners
Simply add multiple listeners to an event source.
There is no guarantee about the order in which the events are
delivered to the listeners.
2D Shapes
The Java 2D library organizes geometric shapes in an object-oriented
fashion. There are
abstract classes Line2D, Rectangle2D,
Ellipse2D, and etc. Each class contains two static inner classes Float a
Double, e.g.,
Rectangle2D.Float floatRect = new Rectangle2D.Float( 10.0F, 25.0F,
22.5F, 20.0F );
// left x, top y, width, height; float values
Rectangle2D.Double doubleRect = new Rectangle2D.Double( 10.0, 25
22.5, 20.0 );
// double values
//example
Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width,
height);
g2.draw(rect);
// draw the enclosed ellipse
Ellipse2D ellipse = new Ellipse2D.Double();
ellipse.setFrame(rect);
g2.draw(ellipse);
// draw a diagonal line
Object Cloning
Employee original = new Employee(“John Public”, 50000);
Employee copy = original; // copying
copy.raiseSalary(10); // oops – also changed original
Using the clone() method in the Object class copies only the first level of
fields. If there are immutable subobjects in the
data fields (such as a String object), this library clone() method works fin
Employee copy = original.clone();
copy.raiseSalary(10); // OK – original unchanged.
Quite frequently, subobjects are mutable, and one must override the clon
method to make
a “deep” copy that clones the subobjects as well. The relevant class mus
also
implement the Cloneable interface.
class Employee implements Cloneable {
public Employee(String n, double s) { ... }
public Employee clone() { ... }
}
public Employee clone() throws CloneNotSupportedException
{
// call Object.clone()
Employee cloned = (Employee) super.clone();
// clone mutable fields
cloned.hireDay = (Date) hireDay.clone();
return cloned;
}
Inner classes
Inner classes are classes defined within another class.
Only inner classes can be private. Regular classes always have either package or
public visibility.
Advantages: ability to access instance fields of the outer classes; inner classes can be
private to ensure encapsulation
public void start()
{
// Creating an inner class object.
ActionListener listener = new TimePrinter();
Timer t = new Timer(interval, listener);
t.start();
}
Local inner classes
Define a class within a method. The class is usable only in that method (always private to
method). No access modifier is needed.
For example, in Example 6-4, the inner class TimePrinter is used only once.
public void start()
{
class TimePrinter implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Date now = new Date();
System.out.println("At the tone, the time is ” + now);
if (beep) Toolkit.getDefaultToolkit().beep();
}
}
Object variables in Java are polymorphic, i.e., an object variable of a class can refer to an
object of this particular class or any of the subclasses.
Another form of polymorphism is discussed in the section about overriding (see below),
where one method name is being overloaded or overridden.
We can assign a subclass object to a superclass variable.
Manager boss = new Manager ( “John”, 70000, 1990, 1, 2 );
Employee em1 = new Employee ( “Lee”, 50000, 1992, 3, 1 );
Employee em2 = new Employee ( “Wong”, 55000, 1994, 9, 4 );
Employee em3 = new Employee (“Chan”, 60000, 1996, 3, 8 );
Employee EM = boss; // ok!
/* In this case, EM and boss refer to the same area of memory. The actual type of
EM is Manager, but the variable type of EM is Employee. */
Employee[] staff = new Employee[4];
staff [0] = boss;
/*Ok, although the type of staff[0] is Employee and the type of boss is Manager. */
staff [1] = em1;
staff [2] = em2;
staff [3] = em3;
However, the converse (assigning a superclass object to a subclass variable) is false in general.
superclass object cannot be used as a subclass object.
Overloading and overriding
The scenario that methods in different classes of an inheritance hierarchy have the same
signature (method name and parameter list) and same return type but different contents is
called overriding that method name (polymorphism). Notice that the return type is not
part of the signature.
Overloading a class provides more than one method with the same name, but with
different signatures.
Overriding a class hierarchy replaces the superclass's implementation of a method in
the subclass. Their signatures and return types must be identical. Note that only
non-static methods may be overridden. For example,
// in class Employee
public void raiseSalary( double byPercent ) {
salary *= ( 1. + byPercent / 100. );
}
// in class Manager
public void raiseSalary( double byPercent ) {
Date today = new Date();
//addition 0.5% for each year of service
double bonus_percent =
0.5* ( today.getYear() – getHireDay().getYear() );
super.raisesalary( byPercent + bonus_percent );
}
When you override a method, the subclass method must be at least as visible as the
superclass method. For example,
• If the superclass method is public, the subclass method must also be public.
• If the superclass method is private, the subclass method can be public. Also,
• in this case, if the method is named, say, func(), the subclass method cannot call
super.func().
When an object of a subclass calls a method name (this method may or may not have been
overridden in the inheritance hierarchy), which one will actually be invoked? The rules are:
(1) The subclass checks whether or not it has a method with that name and with exactly
the same parameters. If so, use it. If not,
(2) Java moves to the parent class and looks there for a method with that name and those
parameters. If so, it calls that method. If not,
(3) Java continues to move up the inheritance chain. The parent classes are checked
until the chain of inheritance stops (an error) or until Java finds a matching method
This is one of the fundamental inheritance rules: a method redefined in a subclass hides or over
the method of the ancestor class.
Dynamic binding
Dynamic binding occurs when a superclass and a subclass both have a method of the same sign
and return type.
If an object of a subclass is assigned to a superclass variable, and the variable calls an overridd
method, which one of the overridden methods in the inheritance hierarchy will be invoked?
The answer is - according to the actual type of the object itself, not the type of the variable.
Consider the code from Example 5-1:
for (int i = 0; i < staff.length; i++) {
Employee e = staff[i];
// staff[0] is of type boss; staff[1] and staff[2] are of type Employee
System.out.println( "name=" +
e.getName() + //static binding
", salary = " + e.getSalary()); // dynamic binding
}
The Java compiler produces the method tables for the Employee and Manager classes (in Exam
5-1):
Employee:
getName() → Employee.getName()
getSalary() → Employee.getSalary()
getHireDay() → Employee.getHireDay()
raiseSalary( double ) → Employee.raiseSalary( double )
Manager:
getName() → Employee.getName()
getSalary() → Manager.getSalary()
getHireDay() → Employee.getHireDay()
raiseSalary( double ) → Employee.raiseSalary( double )
setBonus( double ) → Manager.setBonus( double )
Constructors in inheritance hierarchy
Every constructor of a subclass must somehow call a constructor of the superclass (to set up
the data fields of the superclass).
(1) In a constructor of a subclass, we can explicitly use super with the appropriate
(2) parameters to invoke one of the superclass's constructors. This must be done in the
first statement of the subclass’s constructor.
(2) If the subclass constructor does not call a superclass constructor explicitly, the default
constructor of the superclass will be called automatically by the compiler.
By convention, if a class does not have any constructor, the Java compiler will
automatically generate a default constructor. However, if the class has one or more cons
that requires parameters (but no default constructor), the compiler will not
generate a default constructor. Thus
(i) if the superclass has no default constructor but does possess other constructors, we
explicitly use one of these constructors via super. Otherwise the compiler will repo
error;
(ii) if the superclass has no constructor at all and the subclass constructor does not use
the default constructor provided by the compiler will be called.
Methods
In Java, the terminology method is used instead of functions in C. All methods must
be defined inside a class.
public The member can be accessed by any class.
private The member can be accessed only by methods within the same class (to make sure
that no outside agency can access the members except through the methods
of our class).
protected The member can be accessed by subclasses of this class and classes in the same
package.
(none) Members declared with no access modifier are accessible only to classes in the same
package.
Overloading Methods
Each method has a signature - the name together with the number and types of its parameters
in the parameter list.
Two methods of a class can have the same name but different number or types of parameters.
This feature is called overloading - because the name of the method has been overloaded.
Constructors
Java offers a good way to initialize data fields of instances (especially for private fields)
through constructors.
Static Fields and methods
Static fields and methods (class fields and methods) are associated with a class as a whole,
not with a particular instance. They are declared static in the class definition.
The value of a static field (class field) does not change from one class instance to another.
There is exactly one copy of the variable, no matter how many object instances (even zero)
there are of the class. This single value is shared by all objects of the class. It represents a
piece of “class-wide” information.
Using a block for initialization - a class can also have static initialization blocks to set
up static fields or other necessary states.
public static double [] buffer = new double[BUFFER_SIZE];
static {
int i;
for ( i = 0 ; i < buffer.length ; i++ )
buffer[i] = java.lang.Math.random( );
}
Thus a static method cannot use the implicit parameter this.
Finalizers
Every class in Java can have a finalizer method that releases resources back to the operating
system. This method is called before the garbage collector sweeps away the object. A
class’s finalizer method always has the name finalize, receiving no parameters and returning no
value. (I.e., its return type is void.)
tmp3[e][f] = contents3[a-1][b-1];
contents3[a-1][b-1] = contents3[a-1][c-1];
contents3[a-1][c-1] = tmp3[e][f];
for(i=0;i <= i3;i++){
for(j=0;j < maxline3;j++){
if(contents3[i][j]==null)break;
System.out.println(contents3[i][j]);
}System.out.println(""); }
}
MP2
import java.io.*;
import java.util.*;
public Blue_Card(String n, int an, Date cs, ArrayList<Trip> ml){
this.name = n;
this.acct_no = an;
this.customer_since = cs;
this.mileage_list = ml;
}
public Blue_Card(){}
public Blue_Card claim_ticket(int km){
Collections.sort(mileage_list);
return this;
}
class Trip implements Comparable<Trip>{
public int compareTo(Trip other){
return
date_granted.compareTo(other.date_granted);
}
}
public class MP2 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
ArrayList<Trip> Ada_list = new ArrayList<Trip>();
Ada_list.add(new Trip(20000, new Date(2007-
1900,1-1,5)));
Ada_list.add(new Trip(15000, new Date(2008-
1900,8-1,8)));
System.out.print("Please enter mileage earned:");
int me = in.nextInt();
}
}
if(option == 6){
System.exit( 0 );
}
MP3
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
public class MP3 {
public static void main(String[] args){
KFrame frame = new KFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class KFrame extends JFrame{
public KFrame(){
setTitle("MP3");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
KPanel panel = new KPanel();
add(panel);
}
public static final int DEFAULT_WIDTH = 315;
public static final int DEFAULT_HEIGHT = 635;
}
class MyMouseAdapter extends MouseAdapter
{ public void mousePressed( MouseEvent e){
int x =e.getX();
int y = e.getY();
}
}
class MyKeyAdapter extends KeyAdapter
{
public void keyPressed(KeyEvent event)
{ int code = event.getKeyCode();
char code2 = event.getKeyChar();
}
}
MP4
public KFrame(){
setTitle("MP4");
main_panel = new JPanel();
main_panel.setLayout( new BorderLayout() );
main_panel.add(left_panel,BorderLayout.WEST);
right_panel = new RPanel();
right_panel.setLayout( new BorderLayout() );
right_panel.setPreferredSize(new Dimension(300,
700));
right_top = new RTPanel();
right_top.setPreferredSize(new Dimension(300,
250));
right_panel.add(right_top, BorderLayout.NORTH);
right_middle = new RMPanel();
right_middle.setLayout(new BorderLayout());
right_middle.setPreferredSize(new Dimension(300,
250));
JPanel right_middle_bottom = new JPanel();
right_middle_bottom.setPreferredSize(new
Dimension(300, 150));
right_middle_bottom.setLayout(new
GridLayout(8,1));
top_scores = new JLabel(" Top Scores");
name = new JLabel(" Name Scores");
first = new JLabel("1.");
second = new JLabel("2.");
third = new JLabel("3.");
fourth = new JLabel("4.");
fifth = new JLabel("5.");
JTextField tf = new JTextField (" ", 10);
right_middle_bottom.add(top_scores);
right_middle_bottom.add(name);
right_middle_bottom.add(first);
right_middle_bottom.add(second);
right_middle_bottom.add(third);
right_middle_bottom.add(fourth);
right_middle_bottom.add(fifth);
right_middle_bottom.add(tf);
right_middle.add(right_middle_bottom,
BorderLayout.SOUTH);
right_panel.add(right_middle,
BorderLayout.CENTER);
right_bottom = new RBPanel();
right_bottom.setPreferredSize(new Dimension(300,
200));
slider_panel = new SPanel();
slider_panel.setLayout( new BorderLayout() );
slider = new JSlider(1,100,50);
slider.setPaintTicks(true);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
slider.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent event)
{
JSlider source = (JSlider)event.getSource();
slider_value = source.getValue();
timer.setDelay(slider_value+1000);
slider.transferFocus();
s_r.transferFocus();
p_r.transferFocus();
//timer.start();
System.out.println(slider_value);
}
}
);
speed = new JLabel(" Speed");
slider_panel.add(speed,BorderLayout.NORTH);
slider_panel.add(slider,BorderLayout.CENTER);
right_bottom.add(slider_panel);
button_panel = new BPanel();
s_r = new JButton("Start");
p_r = new JButton("Pause");
button_panel.add(s_r);
button_panel.add(p_r);
right_bottom.add(button_panel);
right_panel.add(right_bottom,
BorderLayout.SOUTH);
main_panel.add(right_panel,BorderLayout.CENTER);
add(main_panel);
pack();
}
PT2
public KFrame(){
JLabel label = new JLabel("Select your next figue
here:");
JButton square = new JButton("Square");
JButton triangle = new JButton("Triangle");
JButton circle = new JButton("Circle");
square.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
figure = 1;
repaint();
}
}
);
top_left_down.add(square);
top_left_down.add(triangle);
top_left_down.add(circle);
top_left.setLayout(new GridLayout(2,1));
top_left.add(label);
top_left.add(top_left_down);