Java FAQ

Contents

Display my JRE properties in an applet
JDK vers: 1.0.x+
Platform: All platforms
Get the source: SystemApplet.java

How do I create a status bar ?
JDK vers: 1.2.x+
Platform: All platforms
Win2K screenshot
Information icon Information icon
Warning icon Warning icon
Error icon Error icon
/*                         hjembaek.com                          */

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

/**
 * A simple StatusBar that displays an icon and a text message to
 * the operator. The icon indicates the type of message:
 * information, warning or error.
 *
 * @author  Michael Hjembaek
 *
 * @see     JLabel
 * @since   1.4
 */
class StatusBar extends JLabel {
    /**
     * Holds an information icon.
     */
    private ImageIcon aInfoIcon;

    /**
     * Holds an warning icon.
     */
    private ImageIcon aWarnIcon;

    /**
     * Holds an error icon.
     */
    private ImageIcon aErrorIcon;

    /**
     * Indicates information level.
     */
    public static final int INFO = 0;

    /**
     * Indicates warning level.
     */
    public static final int WARN = 1;

    /**
     * Indicates error level.
     */
    public static final int ERROR = 2;

    /**
     * Creates a StatusBar instance that display the default
     * message:
     * <code>Status OK</code>.
     */
    public StatusBar() {
        this("Status OK");
    }

    /**
     * Creates a StatusBar instance with the specified text.
     *
     * @param text The text message to display.
     */
    public StatusBar(String text) {
        setText(text);

        // Create nicer looking statusbar - the default lowered
        // bevel border is just to thick
        Color bgColor = UIManager.getColor("Panel.background");

        setBorder(BorderFactory.createBevelBorder(
        BevelBorder.LOWERED, SystemColor.controlLtHighlight,
        bgColor, bgColor, SystemColor.controlShadow));
        loadIcons();
        setIcon(aInfoIcon);
    }

    private void loadIcons() {
        try {
            aInfoIcon = new ImageIcon(
            StatusBar.class.getResource("info.gif"));
            aErrorIcon = new ImageIcon(
            StatusBar.class.getResource("error.gif"));
            aWarnIcon = new ImageIcon(
            StatusBar.class.getResource("warn.gif"));
        } catch (Exception ex) {
            ; // ignore
        }
    }

    /**
     * Overridden to set the icon and tooltip text automatically
     * when setText() is called. The message is displayed as an
     * information message.
     *
     * @param  message The text to display in the status bar.
     */
    public void setText(String message) {
        setText(message, INFO);
    }

    /**
     * Displays a message with an icon corresponding to the
     * specified level.
     *
     * @param  message A text message to display.
     * @param  level The type of message to display.
     */
    public void setText(String message, int level) {
        super.setText(message);
        super.setToolTipText(message);

        switch (level) {
            case INFO:
            setIcon(aInfoIcon);
            break;
            case WARN:
            setIcon(aWarnIcon);
            break;
            case ERROR:
            setIcon(aErrorIcon);
            break;
            default:
            setIcon(aInfoIcon);
            break;
        }
    }

    /**
     * Paints a triangular shape in the bottom right of the
     * statusbar.
     *
     * @param  g The Graphics object used for painting the border.
     */
    public void paintBorder(Graphics g) {
        super.paintBorder(g);

        Component c = this;

        int gOffset = 1;
        int width = this.getWidth() + gOffset;
        int height = this.getHeight() + gOffset;

        // Set background color
        g.setColor(c.getBackground());

        // Draw 90 degrees angle: _|
        g.drawLine(width - 14, height - 2, width - 2, height - 2);
        g.drawLine(width - 2, height - 14, width - 2, height - 2);

        // Draw three 45 degrees angle lines in different colors
        for (int idx = 1, count = 4; idx < count; idx++) {
            int offset = count * idx + 2;

            // Set highlight color
            g.setColor(SystemColor.controlLtHighlight);
            int d = 3;
            g.drawLine(width - offset, height - d, width - d,
            height - offset);

            // Set shadow color
            g.setColor(SystemColor.controlShadow);
            g.drawLine(width - offset + 1, height - d, width - d,
            height - offset + 1);
            g.drawLine(width - offset + 2, height - d, width - d,
            height - offset + 2);

            // Set background color
            g.setColor(c.getBackground());
            g.drawLine(width - offset + 3, height - d, width - d,
            height - offset + 3);
        }
    }

    public static void main(String[] arguments) {
        try {
            UIManager.setLookAndFeel(
            UIManager.getSystemLookAndFeelClassName());
        }
        catch (Exception ex) {
            // Could catch:
            // ClassNotFoundException
            // InstantiationException
            // IllegalAccessException
            // UnsupportedLookAndFeelException
        }

        JFrame frame = new JFrame("StatusBar test");
        frame.setDefaultCloseOperation(
        WindowConstants.EXIT_ON_CLOSE);

        Container contentPane = frame.getContentPane();
        contentPane.add(new StatusBar(), BorderLayout.SOUTH);
        frame.setSize(200, 100);
        frame.setVisible(true);
    }
}
Get the source: StatusBar.java

How can I convert a Vector to an array ?
JDK vers: 1.2.x+
Platform: All platforms
/*                         hjembaek.com                          */

import java.util.Vector;

class VectorToArray {

    public static void main(String[] args) {
        Vector v = new Vector();
        v.add(new Float(1.0));
        v.add(new Float(2.0));

        Float[] f = (Float[])v.toArray(new Float[0]);

        for (int x=0; x < f.length; x++) {
            System.out.println("Float["+x+"]: "+f[x]);
        }
    }
}
Get the source: VectorToArray.java

How do I capture a snaphot of a portion of the screen ?
JDK vers: 1.3.x+
Platform: All platforms
/*                         hjembaek.com                          */

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

class ScreenCapture {

    public static void main(String[] args) {
        Robot robot = null;

        try {
            robot = new Robot();
        }
        catch(AWTException ae) {
            /*
            the platform configuration does not
            allow low-level input control
             */
            ae.printStackTrace();
        }

        /*
        Grab the portion of the screen at offset (x,y)=(0,0)
        800 pixels wide and 600 pixels high.
         */
        Rectangle area = new Rectangle(0,0,800,600);
        BufferedImage image = robot.createScreenCapture(area);

        // Stuff the grabbed image into a label
        JLabel screenshot = new JLabel(new ImageIcon(image));

        JFrame frame = new JFrame("Captured area");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(810,630);

        // Add the label to the frame content pane
        frame.getContentPane().add(screenshot);
        frame.setVisible(true);
    }
}
Get the source: ScreenCapture.java

How do I center a Window ?
JDK vers: 1.2.x+
Platform: All platforms
/*                         hjembaek.com                          */

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

class CenterWindow {
    /**
     * Centers a window on screen.
     *
     * @param window a window
     */
    public static void centerFrame(Window window) {
        Dimension windowSize = window.getSize();
        Dimension screenSize =
        Toolkit.getDefaultToolkit().getScreenSize();

        if (windowSize.height > screenSize.height) {
            windowSize.height = screenSize.height;
        }

        if (windowSize.width > screenSize.width) {
            windowSize.width = screenSize.width;
        }

        window.setLocation(
        (screenSize.width - windowSize.width)/2,
        (screenSize.height - windowSize.height)/2);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("CenterWindow");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200, 150);
        frame.setLocation(200, 200);

        // Center the frame on screen
        CenterWindow.centerFrame(frame);

        frame.setVisible(true);
    }
}
Get the source: CenterWindow.java

How do I maximize a JFrame ?
JDK vers: 1.3.x+
Platform: Windows
/*                         hjembaek.com                          */

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

public class RobotDemo {

    public static void main(String args[]) throws AWTException {
        JFrame frame = new JFrame("RobotDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200, 150);
        frame.setLocation(200, 200);
        frame.setVisible(true);

        // create a robot to feed in GUI events
        Robot rob = new Robot();

        // move cursor to the top, left corner
        Point p = frame.getLocationOnScreen();
        rob.mouseMove(p.x + 5, p.y + 5);

        // press and release left mouse button
        rob.mousePress(InputEvent.BUTTON1_MASK);
        rob.mouseRelease(InputEvent.BUTTON1_MASK);

        // send an 'x' key press
        rob.keyPress(KeyEvent.VK_X);
    }
}
Get the source: RobotDemo.java

How can I execute DOS commands from my Java application ?
JDK vers: 1.2.x+
Platform: Windows
/*                         hjembaek.com                          */

import java.lang.*;
import java.io.*;

public class RuntimeExecTest {

    public static void main(String[] args) {
        Runtime rt = Runtime.getRuntime();

        /*
        This corresponds to what you type in DOS prompt
        add another String like "C:\\Test\\Test.txt" as
        a parameter to the program you want to start.
        In this case you want to start notepad - with no
        arguments.
         */
        //String[] callAndArgs = { "Notepad.exe","C:\\Test.txt" };

        // We can start another JVM using the following arguments
        //String[] callAndArgs = { "cmd", "/c start java Test" };
        String[] callAndArgs = { "cmd", "/c start telnet" };

        try {

            /*
            Call the runtime environment and ask it to execute the
            contents in callAndArgs.
             */
            Process child = rt.exec(callAndArgs);
            child.waitFor();
            /*
            Return an error code.
            If it is 0 - the command was executed properly
            If it is 1 or more an error occured.
             */
            System.out.println("Process exit code is:"
            + child.exitValue());
        }
        catch (IOException e) {
            System.err.println("IOException starting process!");
        }
        catch (InterruptedException e) {
            System.err.println("Interrupted waiting for process");
        }
    }
}
Get the source: RuntimeExecTest.java

How do I determine whether Num Lock and Caps Lock is ON/OFF ?
JDK vers: 1.3.x+
Platform: All platforms
/*                         hjembaek.com                          */

import java.awt.*;
import java.awt.event.*;

class LockingKeyTest {

    public static void main(String[] args) {
        Toolkit tk = Toolkit.getDefaultToolkit();

        System.out.println( "Is CAPS LOCK on: "
        + tk.getLockingKeyState(KeyEvent.VK_CAPS_LOCK));

        System.out.println( "Is NUM LOCK on : "
        + tk.getLockingKeyState(KeyEvent.VK_NUM_LOCK));
    }
}
Get the source: LockingKeyTest.java

How do I make a filechooser that accepts XML files ?
JDK vers: 1.2.x+
Platform: All platforms
/*                         hjembaek.com                          */

import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.*;

class XMLFileChooserTest {

    /**
     * A FileChooser extension for showing XML files
     */
    private class XMLFileChooser extends JFileChooser {
        public XMLFileChooser() {
            super();

            // Set the XML filter for this filechooser
            setFileFilter(new XMLFileFilter());
        }

        /**
         * Overridden to remove the "All-files (*.*)" filter
         */
        public FileFilter getAcceptAllFileFilter() {
            return null;
        }
    }

    /**
     * A FileFilter that only shows directories and XML files
     */
    private class XMLFileFilter extends FileFilter {
        public boolean accept(File pathname) {
            if (pathname.isDirectory()) {
                return true;
            }

            String ext = getExtension(pathname);

            if (ext.equalsIgnoreCase("xml")) {
                return true;
            } else {
                return false;
            }
        }

        public String getDescription() {
            return "XML file format (*.xml)";
        }

        private String getExtension(File file) {
            String filename = file.getName();
            int index = filename.lastIndexOf('.');

            String ext = null;
            if (index > 0 &&  index < filename.length() - 1) {
                ext = filename.substring(index+1).toLowerCase();
            }

            return ext;
        }
    }

    /**
     * Just a short test method :o)
     */
    private void test() {
        JFrame frame = new JFrame();
        XMLFileChooser fc = new XMLFileChooser();
        fc.showOpenDialog(frame);
    }

    /**
     * Main method for starting up the works !
     */
    public static void main (String[] args) {
        new XMLFileChooserTest().test();
    }
}
Get the source: XMLFileChooserTest.java

What is it with those for-loops in text books ?
JDK vers: 1.0.x+
Platform: All platforms
/*                         hjembaek.com                          */

/**
 * This class tests the performance of two "similar" for-loop
 * constructs:
 *
 * 1. 	for (int x=0, loops=longOperation(); x < loops; x++) {
 *  		doPrint(x); // singleLoop
 *  	}
 *
 * 2. 	for (int x = 0; x < longOperation(); x++) {
 *  		doPrint(x); // singleLoop
 *  	}
 *
 * QUESTION:
 * Now which of the two methods is the fastest, if the
 * longOperation method returns a constant integer value ?
 *
 * See answer below.
 */
class ForLoopTest {
    /** 200 ms operation  */
    private int longOperation() {
        int loops = 10; // used for clarification only!

        try {
            Thread.sleep(200);
        } catch (InterruptedException ignore) {}

        return loops;
    }

    /**
     * Execution speed = longOperation + singleLoop * loops
     */
    private void testTwoVaribleForLoop() {
        for (int x=0, loops=longOperation(); x < loops; x++) {
            doPrint(x); // singleLoop
        }
    }

    /**
     * Execution speed = (longOperation + singleLoop) * loops
     *
     * Why is it that some java books use this compact version of
     * for-loop in their text book examples ?
     */
    private void testCompactForLoop() {
        for (int x = 0; x < longOperation(); x++) {
            doPrint(x); // singleLoop
        }
    }

    /** Time consuming printers  */
    private void doPrint(int x) {
        System.out.print(x);
    }
    private void doPrint(String text, long time) {
        System.out.println(" "+text+time+" ms");
    }

    /** Ugly testbed  */
    private void testForLoop() {
        long start, timeSpent;

        start = System.currentTimeMillis();
        testTwoVaribleForLoop();
        timeSpent = System.currentTimeMillis() - start;
        doPrint("testTwoVaribleForLoop()  ", timeSpent);

        start = System.currentTimeMillis();
        testCompactForLoop();
        timeSpent = System.currentTimeMillis() - start;
        doPrint("testCompactForLoop()    ", timeSpent);
    }

    /**
     * ANSWER: Executing this program produces:
     *
     * 0123456789 testTwoVaribleForLoop()  200 ms
     * 0123456789 testCompactForLoop()    2203 ms
     */
    public static void main(String[] args) {
        new ForLoopTest().testForLoop();
    }
}
Get the source: ForLoopTest.java

Static versus Instance initializers
JDK vers: 1.1.x+
Platform: All platforms
/*                         hjembaek.com                          */

/**
 * This class shows how to use static / instance initializers.
 */
class InitializerTest {
    { // instance initializer
        System.out.println("..Creating InitializerTest");
    }

    /**
     * Static initializers are executed once only, in the order
     * they are declared. They can not be used in inner classes.
     */
    static { // static initializer
        System.out.println(".Executed once");
    }

    /**
     * Every class can have as many instance initialisers as you
     * like. They are executed before the constructor, in the
     * order that they are declared.
     *
     * Instance initializers are extremely useful in anonymous
     * inner classes, which cannot have a constructor but
     * may nevertheless need initialization code.
     */
    private class InstanceInitializer {
        { // instance initializer
            System.out.println("..Creating InstanceInitializer");

            (new Runnable() {
                public void run() {
                    System.out.println("Running");
                }

                { // executed before the constructor
                    System.out.println("..Creating Runnable");
                }
            }).run();
        }
    }

    /**
     * When this code is executed the following happens:
     * .  = static initializer used
     * .. = instance initializer used
     * -------------------------------------------------
     *	.Executed once
     *	..Creating InitializerTest
     *	..Creating InstanceInitializer
     *	..Creating Runnable
     *	Running
     *	..Creating InitializerTest
     *	..Creating InstanceInitializer
     *	..Creating Runnable
     *	Running
     */
    public static void main(String[] args) {
        new InitializerTest().new InstanceInitializer();
        new InitializerTest().new InstanceInitializer();
    }
}
Get the source: InitializerTest.java

How do I create a JComboBox with selection from the keys typed ?
JDK vers: 1.2.x+
Platform: All platforms
/*                         hjembaek.com                          */

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

/**
 * Creates a key listener for use by JComboBox instances.
 * A JComboBox using the SearchComboBoxKeyListener enables the
 * operator to type in a search string.
 * The SearchComboBoxKeyListener searches the list of JComboBox
 * items and selects any item that starts with the typed search
 * string.
 * <p>
 * Usage:
 * <pre>
 *     comboBox.addKeyListener(new SearchComboBoxKeyListener());
 * </pre>
 *
 * @author  Michael Hjembaek
 * @version 1.0
 */
class SearchComboBoxKeyListener extends KeyAdapter {
    private StringBuffer aBuffer = new StringBuffer();
    private long aLastKeyTypedTime;
    private static final long DELAY = 1000;

    /**
     * Called back when a key is typed in the JComboBox.
     *
     * @param  event The event generated by the key typed.
     */
    public void keyTyped(KeyEvent event) {
        long now = System.currentTimeMillis();

        if (now > aLastKeyTypedTime + DELAY) {
            aBuffer.setLength(0);
        }
        aBuffer.append(event.getKeyChar());

        JComboBox comboBox = (JComboBox) event.getSource();
        DefaultComboBoxModel model = (DefaultComboBoxModel)
        comboBox.getModel();

        int size = model.getSize();

        for (int idx = 0; idx < size; idx++) {
            Object element = model.getElementAt(idx);

            String elementStr = element.toString().toLowerCase();

            if (elementStr.startsWith(aBuffer.toString())) {
                model.setSelectedItem(element);
                break;
            }
        }

        aLastKeyTypedTime = System.currentTimeMillis();
    }
}

How do I create a simple sorted JTree ?
JDK vers: 1.2.x+
Platform: All platforms
/*                         hjembaek.com                          */

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

/**
 * The SortedTreeModel sorts on the toString() representation of
 * nodes using the String compareTo(String) method.
 *
 * @author Michael Hjembaek
 *
 * @see    String#compareTo(String)
 */
public class SortedTreeModel extends DefaultTreeModel {

    /**
     * Creates a new SortedTreeModel instance using the supplied
     * TreeNode instance as root node.
     *
     * @param  root The TreeNode instance to use as root
     *         node.
     */
    public SortedTreeModel(TreeNode root) {
        super(root);
    }

    /**
     * Overriden DefaultTreeModel method.
     *
     * @param  newChild The new child node to insert.
     * @param  parent The parent of the new child.
     * @param  index The index to insert at - not used.
     */
    public void insertNodeInto(
    MutableTreeNode newChild,
    MutableTreeNode parent, int index) {

        parent.insert(newChild, 0);

        int childCount = parent.getChildCount();

        for (int idx = 0; idx < childCount; idx++) {
            Object child = parent.getChildAt(idx);
            String current = child.toString();
            int result = newChild.toString().compareTo(current);

            if (result > 0) {
                parent.insert(newChild, idx);
            }
        }

        // Notify the view
        nodeStructureChanged(parent);
    }

    /**
     * Used for testing purposes only.
     *
     * @param  args A list of command line arguments.
     */
    public static void main(String[] args) {
        JFrame frame = new JFrame("Sorted Tree Model");
        frame.setDefaultCloseOperation(
        WindowConstants.EXIT_ON_CLOSE);
        Container contentPane = frame.getContentPane();

        MutableTreeNode rootNode = new DefaultMutableTreeNode(
        "Root");

        DefaultTreeModel model = new SortedTreeModel(rootNode);

        JTree tree = new JTree(model);
        contentPane.add(new JScrollPane(tree));

        frame.setSize(400, 300);
        frame.setVisible(true);

        String[] names = {"A", "B", "C", "C", "B", "A"};

        for (int idx = 0; idx < names.length; idx++) {
            String name = names[idx];
            MutableTreeNode node = new DefaultMutableTreeNode(
            name);
            model.insertNodeInto(node, rootNode, 0);
        }
    }
}
Get the source: SortedTreeModel.java

How do I create a multiline JLabel ?
JDK vers: 1.2.x+
Platform: All platforms
/*                         hjembaek.com                          */

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

/**
 * A label that is able to display multiple lines of text.<p>
 * The <code>MultiLineJLabel</code> is a specialization of
 * <code>JTextArea</code> that uses the border, color and font
 * of the JLabel's Look & Feel.
 *
 * @author Michael Hjembæk
 */
public class MultiLineJLabel extends JTextArea {
    /**
     * Creates a new MultiLineJLabel instance.
     */
    public MultiLineJLabel() {
        super();
    }

    /**
     * Creates a new MultiLineJLabel instance.
     *
     * @param  text The text to display.
     */
    public MultiLineJLabel(String text) {
        super(text);
    }

    /**
     * Overridden to make the JTextArea appear like a JLabel.
     */
    public void updateUI() {
        super.updateUI();

        // Turn on wrapping, disable editing, highlighting and
        // focus
        setLineWrap(true);
        setWrapStyleWord(true);
        setHighlighter(null);
        setEditable(false);
        setRequestFocusEnabled(false);

        // Set the text area's border, colors and font to that of
        // a JLabel
        LookAndFeel.installBorder(this, "Label.border");
        LookAndFeel.installColorsAndFont(this, "Label.background",
        "Label.foreground", "Label.font");
    }

    // Used for testing purposes
    public static void main(String[] args) {
        JFrame frame = new JFrame("MultiLineJLabel test");
        frame.setDefaultCloseOperation(
        WindowConstants.EXIT_ON_CLOSE);
        Container contentPane = frame.getContentPane();

        String text = "This\nis\na\ntest ...";
        MultiLineJLabel label = new MultiLineJLabel(text);
        contentPane.add(label);
        contentPane.setLayout(new FlowLayout(FlowLayout.CENTER));
        contentPane.setBackground(Color.orange);

        frame.pack();
        frame.setVisible(true);
    }
}
Get the source: MultiLineJLabel.java

How do I create toggle selection in a JList ?
JDK vers: 1.2.x+
Platform: All platforms
/*                         hjembaek.com                          */

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

/**
 * The ToggleSelectionModel class enables selection and
 * deselection of list elements using the mouse <b>without</b>
 * holding Crtl down.<p>
 *
 * ToggleSelectionModel is based upon Sun's implementation of
 * <code>BasicListUI&#36;MouseInputHandler</code>, and inspiration
 * from the article:
 * <a href="http://java.sun.com/products/jfc/tsc/tech_topics/
 * jlist_1/jlist.html">Advanced JList Programming</a>
 *
 * @see  javax.swing.plaf.basic.BasicListUI
 *       #createMouseInputListener()
 */
class ToggleSelectionModel
extends DefaultListSelectionModel {
    boolean gestureStarted = false;

    public void setSelectionInterval(int index0, int index1) {
        if (isSelectedIndex(index0) && !gestureStarted) {
            super.removeSelectionInterval(index0, index1);
        }
        else {
            super.addSelectionInterval(index0, index1);
        }
        gestureStarted = true;
    }

    public void setValueIsAdjusting(boolean isAdjusting) {
        if (isAdjusting == false) {
            gestureStarted = false;
        }
    }
}

class TestToggleSelectionModel {
    public static void main(String[] args) {
        JFrame frame = new JFrame("ToggleSelectionModel test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container contentPane = frame.getContentPane();
        JList list = new JList();
        list.setSelectionModel(new ToggleSelectionModel());
        list.setListData(new String[] {"Michael", "was", "here!"});
        JScrollPane scrollPane = new JScrollPane(list);
        contentPane.add(scrollPane);
        frame.pack();
        frame.setVisible(true);
    }
}
Get the source: ToggleSelectionModel.java

Notes
  • The syntax highlighting may sometimes display incorrect colors.
  • The comments may not display correctly.
  • Strings containing double slashes do not display correctly.
  • The source is formatted so its 66 chars at most to make it printable.
  • If the code contains errors - mail me
 

October 2004

Michael Hjembæk