Java : File Dialogs 01 October 2001 at 00:00
To show a standard windows dialog box, you need to import the java.awt.FileDialog class, which can be used to display files on your machine int he following way:
  FileDialog dlg = new FileDialog(this, "What file do you want to save?", FileDialog.SAVE);
  dlg.setFile("*.java");		// file extension filter
  dlg.setDirectory(".");		// initial directory
  dlg.show();
  String saveFile;
  if((saveFile = d.getFile()) != null) {
    filename.setText(saveFile);
    myTextField.setText(d.getDirectory());
  }
Alternatively, if you want to maintain a standard swing look and feel, you can import the javax.swing.JFileChooser class, which can be used in the same way.
  JFileChooser chooser = new JFileChooser(".");
  // chooser.setFileFilter(filter); 
  chooser.setFileHidingEnabled(false);
  int returnVal = chooser.showOpenDialog(parent); 
  if(returnVal == JFileChooser.APPROVE_OPTION) { 
    System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName()); 
    System.out.println("You chose to open this directory: " + chooser.getCurrentDirectory()); 
  } 
To save files using the swing set, use the following code:
  JFileChooser saver = new JFileChooser(".");
  saver.setFileHidingEnabled(false);
  int returnVal = saver.showSaveDialog(parent); 
  if (returnVal == JFileChooser.APPROVE_OPTION) {
    File selFile = saver.getSelectedFile();
    if (selFile.exists()) {
      int sel = JOptionPane.showConfirmDialog(parent, "Overwrite file " + 
        selFile.getAbsolutePath() + "?", "File exists",
        JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE);
      if (sel == JOptionPane.NO_OPTION) {
        // do NO overwrite action here
        return;
      }
    }
    // do save action here
  } 
Threading with Java 02 October 2001 at 00:00
Threads in Java can be very simple if you just stick to the basics. To run a thread in your class, you should implement the Runnable interface, and then place your thread code into the start(), stop() and run() methods. For example, you want to create a dialog that returns a value to the calling class:
public class myClass extends Dialog implements Runnable {

    private Thread timer;      // class-wide reference to thread object

    // run method from Runnable interface - this method runs until a 
    // specified condition is true - so you would probably want to have 
    // another variable which checks, for example, that the user has clicked 
    // a Cancel or OK button
    public void run() {
        while (this.isVisible()) {
            try {
                // user has not yet closed the window - sleep and loop again
                Thread.currentThread().sleep(500);
            } 
            catch (InterruptedException ie) {
            }
        }
    }

    // method which will return the value - makes the dialog visible, starts 
    // the Thread, and then when the thread dies a result is returned
    public int setVisible() {
        this.show();
        this.start();
        return result;
    }

    // implemented from Runnable interface - initiates a new thread
    public void start() {
        timer = new Thread(this);
        timer.start();
    }
    
    // cleans up objects when the Thread completes
    public void stop() {
        timer = null;
    }

}
Even more simply, if you want to run a single line in your class as a thread, you can do the following (taking away the pain of implementing the Runnable interface):
  public void doStuff() {
    Thread runner = new Thread() {
      public void run() {
         // do thread stuff here
      }
    };
    runner.start();
  }
Java : Setting the look and feel with Swing 04 October 2001 at 00:00
To set the look and feel for your swing application, you can use the following code:
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (Exception ie) { 
            System.out.println("UI not supported.");
        }
        new MyClass();
    }
which will apply the platform standard look and feel.

However, this look and feel may not be supported so when coding your interface, be sure to make it look decent with the default swing interface. Possible values to pass the UIManager.setLookAndFeel() method are:

  • "javax.swing.plaf.metal.MetalLookAndFeel" - standard Java Look & Feel
  • "com.sun.java.swing.plaf.windows.WindowsLookAndFeel" - windows (only works on Win32 systems)
  • "com.sun.java.swing.plaf.motif.MotifLookAndFeel" - CDE/Motif Look & Feel
  • "javax.swing.plaf.mac.MacLookAndFeel" - Mac (only works on Macintosh)
To get a list of all the look and feel classes installed on your system, use the following:
  UIManager.LookAndFeelInfo[] laf = UIManager.getInstalledLookAndFeels();
  for (int i=0; i < laf.length; i++) {
    System.out.println(laf[i].getClassName());
  }

To update the UI after your application has loaded, use the following code:

  try {
    UIManager.setLookAndFeel("lookandfeelclassname");
    SwingUtilities.updateComponentTreeUI(frame);
  }
  catch (Exception exc) {
    System.out.println("Unable to change look and feel: " + exc.getMessage());
  }

Removing bold font with Metal Look and Feel

The metal look and feel has a font that defaults to bold - if you want to turn this off, add the following line before you call UIManager.setLookandFeel(..):

  UIManager.put("swing.boldMetal", Boolean.FALSE);
Java Double-click Events 04 October 2001 at 00:00
  private class YourMouseListener extends MouseAdapter {

    public void mouseClicked(MouseEvent event) {
      Object object = event.getSource();
      //Perform actions on double-click events
      if (event.getClickCount() == 2) {
        // do action here
      }
    }
  }

Java Swing Dialog Boxes 05 October 2001 at 00:00
Dialog boxes using the swing set can be created using a combination of the JOptionPane and JDialog classes. For example, to create an error box:
  JOptionPane pane = new JOptionPane(msg, JOptionPane.ERROR_MESSAGE);
  JDialog dialog = pane.createDialog(owner, title); 
  dialog.show();
How to show File Dialog boxes 01 October 2001 at 00:00
To show a standard windows dialog box, you need to import the java.awt.FileDialog class, which can be used to display files on your machine in the following way:
  FileDialog dlg = new FileDialog(this, "What file do you want to save?", FileDialog.SAVE);
  dlg.setFile("*.java");		// file extension filter
  dlg.setDirectory(".");		// initial directory
  dlg.show();
  String saveFile;
  if((saveFile = d.getFile()) != null) {
    filename.setText(saveFile);
    myTextField.setText(d.getDirectory());
  }
Alternatively, if you want to maintain a standard swing look and feel, you can import the javax.swing.JFileChooser class, which can be used in the same way.
  JFileChooser chooser = new JFileChooser(".");
  // chooser.setFileFilter(filter); 
  chooser.setFileHidingEnabled(false);
  int returnVal = chooser.showOpenDialog(parent); 
  if(returnVal == JFileChooser.APPROVE_OPTION) { 
    System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName()); 
    System.out.println("You chose to open this directory: " + chooser.getCurrentDirectory()); 
  } 
To save files using the swing set, use the following code:
  JFileChooser saver = new JFileChooser(".");
  saver.setFileHidingEnabled(false);
  int returnVal = saver.showSaveDialog(parent); 
  if (returnVal == JFileChooser.APPROVE_OPTION) {
    File selFile = saver.getSelectedFile();
    if (selFile.exists()) {
      int sel = JOptionPane.showConfirmDialog(parent, "Overwrite file " + 
        selFile.getAbsolutePath() + "?", "File exists",
        JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE);
      if (sel == JOptionPane.NO_OPTION) {
        // do NO overwrite action here
        return;
      }
    }
    // do save action here
  }