A Java superclass is a
A Java class may be either a subclass, a superclass, both, or neither!
The Cat class in the following example is the subclass and the Animal class is the superclass.
public class Animal { |
A Java superclass is a
A Java class may be either a subclass, a superclass, both, or neither!
The Cat class in the following example is the subclass and the Animal class is the superclass.
public class Animal { |
Focus events occur when any component gains or loses input focus on a graphical user interface. Focus applies to all components that can recieve input.
To handle a focus event, a class must implement the FocusListener interface.
The following example shows how to use focus events in Swing:
/*
* FocusEventDemo.java is a 1.4 example that requires
* no other files.
*/
import java.util.Vector;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FocusEventDemo extends JPanel
implements FocusListener {
final static String newline = "\n";
JTextArea display;
public FocusEventDemo() {
super(new GridBagLayout());
GridBagLayout gridbag = (GridBagLayout)getLayout();
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1.0; //Make column as wide as possible.
JTextField textField = new JTextField("A TextField");
textField.setMargin(new Insets(0,2,0,2));
textField.addFocusListener(this);
gridbag.setConstraints(textField, c);
add(textField);
c.weightx = 0.1; //Widen every other column a bit, when possible.
c.fill = GridBagConstraints.NONE;
JLabel label = new JLabel("A Label ");
label.setBorder(BorderFactory.createEmptyBorder(0,5,0,5));
label.addFocusListener(this);
gridbag.setConstraints(label, c);
add(label);
String comboPrefix = "ComboBox Item #";
final int numItems = 15;
Vector vector = new Vector(numItems);
for (int i = 0; i <>) {
vector.addElement(comboPrefix + i);
}
JComboBox comboBox = new JComboBox(vector);
comboBox.addFocusListener(this);
gridbag.setConstraints(comboBox, c);
add(comboBox);
c.gridwidth = GridBagConstraints.REMAINDER;
JButton button = new JButton("A Button");
button.addFocusListener(this);
gridbag.setConstraints(button, c);
add(button);
c.weightx = 0.0;
c.weighty = 0.1;
c.fill = GridBagConstraints.BOTH;
String listPrefix = "List Item #";
Vector listVector = new Vector(numItems);
for (int i = 0; i <>) {
listVector.addElement(listPrefix + i);
}
JList list = new JList(listVector);
list.setSelectedIndex(1); //It's easier to see the focus change
//if an item is selected.
list.addFocusListener(this);
JScrollPane listScrollPane = new JScrollPane(list);
//We want to prevent the list's scroll bars
//from getting the focus - even with the keyboard.
//Note that in general we prefer setRequestFocusable
//over setFocusable for reasons of accessibility,
//but this is to work around bug #4866958.
listScrollPane.getVerticalScrollBar().setFocusable(false);
listScrollPane.getHorizontalScrollBar().setFocusable(false);
gridbag.setConstraints(listScrollPane, c);
add(listScrollPane);
c.weighty = 1.0; //Make this row as tall as possible.
c.gridheight = GridBagConstraints.REMAINDER;
//Set up the area that reports focus-gained and focus-lost events.
display = new JTextArea();
display.setEditable(false);
//The method setRequestFocusEnabled prevents a
//component from being clickable, but it can still
//get the focus through the keyboard - this ensures
//user accessibility.
display.setRequestFocusEnabled(false);
display.addFocusListener(this);
JScrollPane displayScrollPane = new JScrollPane(display);
//Work around for bug #4866958.
displayScrollPane.getHorizontalScrollBar().setFocusable(false);
displayScrollPane.getVerticalScrollBar().setFocusable(false);
gridbag.setConstraints(displayScrollPane, c);
add(displayScrollPane);
setPreferredSize(new Dimension(450, 450));
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
public void focusGained(FocusEvent e) {
displayMessage("Focus gained", e);
}
public void focusLost(FocusEvent e) {
displayMessage("Focus lost", e);
}
void displayMessage(String prefix, FocusEvent e) {
display.append(prefix
+ (e.isTemporary() ? " (temporary):" : ":")
+ e.getComponent().getClass().getName()
+ "; Opposite component: "
+ (e.getOppositeComponent() != null ?
e.getOppositeComponent().getClass().getName() : "null")
+ newline);
display.setCaretPosition(display.getDocument().getLength());
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("FocusEventDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new FocusEventDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
This tip shows the way to capture the screen shot of the particular area on the screen and save it to a jpg file.
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class RobotExp {
public static void main(String[] args) {
try {
Robot robot = new Robot();
// Capture the screen shot of the area of the screen defined by the rectangle
BufferedImage bi=robot.createScreenCapture(new Rectangle(100,100));
ImageIO.write(bi, "jpg", new File("C:/imageTest.jpg"));
} catch (AWTException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This sample code shows the uses of formatted input fields. This code shows a frame with one text filed and a button. The text field is intended to take only integer input and format the number after it lost the focus.
import java.awt.BorderLayout;
import java.text.NumberFormat;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TextFormatterExp extends JFrame {
public TextFormatterExp() {
setTitle("My First Swing Prog.");
JPanel panel = new JPanel();
JLabel label = new JLabel("Number :");
JFormattedTextField tf = new JFormattedTextField(NumberFormat
.getIntegerInstance());
tf.setColumns(10);
panel.add(label);
panel.add(tf);
JButton button = new JButton();
button.setLabel("Click Me");
panel.add(button);
getContentPane().add(panel, BorderLayout.SOUTH);
pack();
}
public static void main(String[] args) {
TextFormatterExp tfe = new TextFormatterExp();
tfe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tfe.setVisible(true);
}
}
Quicksort is a well-known sorting algorithm developed by C. A. R. Hoare that, on average, makes Θ(n log n) comparisons to sort n items. However, in the worst case, it makes Θ(n^2) comparisons. Typically, quicksort is significantly faster in practice than other Θ(n log n) algorithms, because its inner loop can be efficiently implemented on most architectures, and in most real-world data it is possible to make design choices which minimize the possibility of requiring quadratic time. Quicksort is a comparison sort and, in efficient implementations, is not a stable sort.
Quicksort sorts by employing a divide and conquer strategy to divide a list into two sub-lists.
The steps are:
The base case of the recursion are lists of size zero or one, which are always sorted. The algorithm always terminates because it puts at least one element in its final place on each iteration.
Quicksort with median-of-three partitioning functions nearly the same as normal quicksort with the only difference being how the pivot item is selected. In normal quicksort the first element is automatically the pivot item. This causes normal quicksort to function very inefficiently when presented with an already sorted list. The divison will always end up producing one sub-array with no elements and one with all the elements (minus of course the pivot item). In quicksort with median-of-three partitioning the pivot item is selected as the median between the first element, the last element, and the middle element (decided using integer division of n/2). In the cases of already sorted lists this should take the middle element as the pivot thereby reducing the inefficency found in normal quicksort.
The following code shows how to implement quick aortwith median-of-three partitioning and cutoff for small arrays:
/**
* Quicksort algorithm.
* @param a an array of Comparable items.
*/
public static void quicksort( Comparable [ ] a ) {
quicksort( a, 0, a.length - 1 );
}
private static final int CUTOFF = 10;
/**
* Internal quicksort method that makes recursive calls.
* Uses median-of-three partitioning and a cutoff of 10.
* @param a an array of Comparable items.
* @param low the left-most index of the subarray.
* @param high the right-most index of the subarray.
*/
private static void quicksort( Comparable [ ] a, int low, int high ) {
if( low + CUTOFF > high )
insertionSort( a, low, high );
else {
// Sort low, middle, high
int middle = ( low + high ) / 2;
if( a[ middle ].compareTo( a[ low ] ) < 0 )
swapReferences( a, low, middle );
if( a[ high ].compareTo( a[ low ] ) < 0 )
swapReferences( a, low, high );
if( a[ high ].compareTo( a[ middle ] ) < 0 )
swapReferences( a, middle, high );
// Place pivot at position high - 1
swapReferences( a, middle, high - 1 );
Comparable pivot = a[ high - 1 ];
// Begin partitioning
int i, j;
for( i = low, j = high - 1; ; ) {
while( a[ ++i ].compareTo( pivot ) < 0 )
;
while( pivot.compareTo( a[ --j ] ) < 0 )
;
if( i >= j )
break;
swapReferences( a, i, j );
}
// Restore pivot
swapReferences( a, i, high - 1 );
quicksort( a, low, i - 1 ); // Sort small elements
quicksort( a, i + 1, high ); // Sort large elements
}
}
/**
* Method to swap to elements in an array.
* @param a an array of objects.
* @param index1 the index of the first object.
* @param index2 the index of the second object.
*/
public static final void swapReferences( Object [ ] a, int index1, int index2 ) {
Object tmp = a[ index1 ];
a[ index1 ] = a[ index2 ];
a[ index2 ] = tmp;
}
/**
* Internal insertion sort routine for subarrays
* that is used by quicksort.
* @param a an array of Comparable items.
* @param low the left-most index of the subarray.
* @param n the number of items to sort.
*/
private static void insertionSort( Comparable [ ] a, int low, int high ) {
for( int p = low + 1; p <= high; p++ ) {
Comparable tmp = a[ p ];
int j;
for( j = p; j > low && tmp.compareTo( a[ j - 1 ] ) < 0; j-- )
a[ j ] = a[ j - 1 ];
a[ j ] = tmp;
}
}
Heapsort is one of the best general-purpose sorting algorithms, a comparison sort and part of the selection sort family. Although somewhat slower in practice on most machines than a good implementation of quicksort, it has the advantages of worst-case O(n log n) runtime and being an in-place algorithm. Heapsort is not a stable sort.
The following code shows how to implement heap sort in
/**
* Standard heapsort.
* @param a an array of Comparable items.
*/
public static void heapsort( Comparable [ ] a )
{
for( int i = a.length / 2; i >= 0; i-- ) /* buildHeap */
percDown( a, i, a.length );
for( int i = a.length - 1; i > 0; i-- )
{
swapReferences( a, 0, i ); /* deleteMax */
percDown( a, 0, i );
}
}
/**
* Internal method for heapsort.
* @param i the index of an item in the heap.
* @return the index of the left child.
*/
private static int leftChild( int i )
{
return 2 * i + 1;
}
/**
* Internal method for heapsort that is used in
* deleteMax and buildHeap.
* @param a an array of Comparable items.
* @index i the position from which to percolate down.
* @int n the logical size of the binary heap.
*/
private static void percDown( Comparable [ ] a, int i, int n )
{
int child;
Comparable tmp;
for( tmp = a[ i ]; leftChild( i ) < i =" child">)
{
child = leftChild( i );
if( child != n - 1 && a[ child ].compareTo( a[ child + 1 ] ) < 0 )
child++;
if( tmp.compareTo( a[ child ] ) < 0 )
a[ i ] = a[ child ];
else
break;
}
a[ i ] = tmp;
}
/**
* Method to swap to elements in an array.
* @param a an array of objects.
* @param index1 the index of the first object.
* @param index2 the index of the second object.
*/
public static final void swapReferences( Object [ ] a, int index1, int index2 )
{
Object tmp = a[ index1 ];
a[ index1 ] = a[ index2 ];
a[ index2 ] = tmp;
}
By Melissa Oxendale
July 17, 2007
My verdict: It successfully turned the BlackBerry I tested it with into a navigation and location-based services tool.
The unit I reviewed is the same as the one sold by AT&T. It came with a wall charger and car charger adapters, and charges via a USB cable just like a BlackBerry, which makes charging easy and the adapters very useful. My review unit came charged, which is always nice. There is nothing worse than waiting for a battery charge before playing with a new toy.
First, the GlobalSat BT-359 Bluetooth GPS Receiver was smaller than I expected, smaller than the BlackBerry Pearl even (see picture - Pearl on left, GlobalSat BT-359 on right).
It has a back door for battery replacement, 3 LED lights, and a power button. One light is the power indicator, letting you know if the battery is low and if the receiver is charging. Another light indicates if the receiver is locked into the GPS satellite network: If it flashes it is connected, if it is solid it is not. The last light is the Bluetooth indicator, a slow flash means it is not connected and a faster flash means it is.
Pairing the receiver with the Pearl was simple. I just went into the Bluetooth menu on the BlackBerry and added the device.
The receiver worked fine with RIM's BlackBerry Maps and Google Maps.
I liked the options available in Google Maps a little better. I tried it with Telenav and Nav4All navigation and tracking applications without any problems at all.
With the receiver, I was able to obtain a connection to the GPS satellites inside my apartment without any problem, as well as everywhere I drove around. When watching the location on the map while driving at interstate speeds the receiver and image on the maps was able to keep up no problem.
The battery is supposed to last for up to 11 hours, in continuous mode. The receiver powers itself down after 10 minutes of inactivity to save power.
In addition to AT&T, you can get the GlobalSat BT-359 Bluetooth GPS receiver through RIM's BlackBerry accessories Web site. It is available for a range of prices from various Web sites, for between $100 and $140.