Loading Java preferences

Specify the node.

Main.java:

import java.util.prefs.*;
 
public class Main
{
   public static final String APPLICATIONPATH = "applicationpath";
   public static final String USERFONT        = "userfont";
   public static final String LASTUSERLOGIN   = "lastuserlogin";
   public static final String LDAPURL         = "ldapurl";
 
   public static void main(String []args) {
      String nodename = "/com/esus/examples/preferences";
 
      Preferences preferences = Preferences.userRoot().node(nodename);
      System.out.println(preferences.get(APPLICATIONPATH, ""));
      System.out.println(preferences.get(USERFONT, ""));
      System.out.println(preferences.get(LASTUSERLOGIN, ""));
      System.out.println(preferences.get(LDAPURL, ""));
   }
}

outputs:

c:application
Courier New
Joris Van den Bogaert
ldap://localhost:389

Assuming you ran the example given in this answer and filled in the values.

Using a ResourceBundle

Suppose we have a .properties file called LabelsBundle_nl_BE and assume also our default locale is en_US. To get access to that bundle, you can invoke ResourceBundle.getBundle(“LabelsBundle”, “nl”, “BE”). Notice that a resource bundle consists of two parts: a family name and a locale part. The locale part contains a language code, a country code and an optional variant code.

In our example, it will try to locate the bundle in the following way:

	class LabelsBundle_nl_BE		NOTFOUND
	file LabelsBundle_nl_BE.properties      OK
	class LabelsBundle_nl			NOTFOUND
	file LabelsBundle_nl.properties		NOTFOUND
	class LabelsBundle			NOTFOUND
	file LabelsBundle.properties		NOTFOUND

Notice that once the .propreties file has been located, it will still continue to look for parent resourcebundles by shortening the locale part delimited by an underscore.

Now assume we only have a .properties file called LabelsBundle_en and we invoke ResourceBundle.getBundle(“LabelsBundle”, “nl”, “BE”). Notice here that it will start from our desired locale and build its way up the tree, including searching for a match with the default locale.

	class LabelsBundle_nl_BE		NOTFOUND
	file LabelsBundle_nl_BE.properties	NOTFOUND
	class LabelsBundle_nl			NOTFOUND
	file LabelsBundle_nl.properties		NOTFOUND
	class LabelsBundle_en_US		NOTFOUND
	file LabelsBundle_en_US.properties	NOTFOUND
	class LabelsBundle_en			NOTFOUND
	file LabelsBundle_en.propertes		OK
	class LabelsBundle			NOTFOUND
	file LabelsBundle.properties		NOTFOUND

Assume we have a .properties file called LabelsBundle_nl_BE.properties and a .properties file called LabelsBundle.properties.

	class LabelsBundle_nl_BE		NOTFOUND
	file LabelsBundle_nl_BE.properties	OK
	class LabelsBundle_nl			NOTFOUND
	file LabelsBundle_nl.properties		NOTFOUND
	class LabelsBundle			NOTFOUND
	file LabelsBundle.properties		OK

In this example, LabelsBundle.properties has become a parent resource bundle of LabelsBundle_nl_BE. You can use the property keys from both these files through the instance that you get back from invoking ResourceBundle.getBundle(…). Also notice that if the resource bundle has been found using the desired locale, the default locale will not be used in looking for a parent. The default locale is only used if locating a bundle with the desired locale failed.

As a last note, you must specify the fully qualified name for the family name (or baseclass) when requesting a resource bundle object. For example, if LabelsBundle_nl_BE.properties is in the package mypackage, you will have to say:

	ResourceBundle.getBundle("mypackage.LabelsBundle", "nl", "BE");

Decompressing using the GZIP algorithm at runtime

Use the standard API class GZIPInputStream. Internally, it uses Inflater to decompress data. The following example asks the user a file to decompress and writes the decompressed stream of data to file.def.

Main.java:

import java.util.zip.*;
import java.io.*;
 
public class Main {
   public static void main(String args[]) {
      if (args.length != 1) {
         System.out.println("Usage: java Main <file.gzip>");
         System.out.println("<file.gzip>.def will be created");
         System.exit(1);
      }
 
      try {
         FileInputStream fis = new FileInputStream(args[0]);
         FileOutputStream fos = new FileOutputStream(args[0] + ".def");
 
         GZIPInputStream gis = new GZIPInputStream(fis);
         byte []buffer = new byte[1024];
         int l;
         while ((l = gis.read(buffer)) >= 0) {
            fos.write(buffer, 0, l);
         }
  
         gis.close();
         fos.close();
      }
      catch(IOException e) {
         System.out.println(e);
      }
   }
}

Prevent the user from closing a JOptionPane with the X button

Embed your JOptionPane in a JDialog. Set the default close operation on that JDialog to DO_NOTHING_ON_CLOSE and add a PropertyChangeListener in which you listen for VALUE_PROPERTY and INPUT_VALUE_PROPERTY and hide the JDialog.

Main.java:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
  
public class Main
{
   public static void main(String []args) {
      JFrame frame = new JFrame();
 
      final JOptionPane pane = new JOptionPane("Are you sure you want to import this file?n" +
                                               "(try presssing the x button!)", 
                                               JOptionPane.QUESTION_MESSAGE,
                                               JOptionPane.YES_NO_CANCEL_OPTION);
      final JDialog dialog = new JDialog(frame, "Question", true);
      dialog.setContentPane(pane);
 
      dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
 
      pane.addPropertyChangeListener(new PropertyChangeListener() {
         public void propertyChange(PropertyChangeEvent e) {
            String prop = e.getPropertyName();
            if (dialog.isVisible() 
             && (e.getSource() == pane)
             && (prop.equals(JOptionPane.VALUE_PROPERTY) ||
                 prop.equals(JOptionPane.INPUT_VALUE_PROPERTY)))
            {
               System.out.println("Caught, JOptionPane is ready to close!");
               dialog.setVisible(false);
            }
         }
      });
 
      dialog.pack();
      dialog.setVisible(true);
      Object value = pane.getValue();
      System.out.println("Option " + value + " selected!");
      
      System.exit(1);
   }
}

Displaying an image as the background of a JPanel

Override the JPanel’s method paintComponent, draw the image using g.drawImage and call the superclass’ paintComponent. Make sure the JPanel is opaque.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JPanel panel = createPanel();
 
      getContentPane().add(BorderLayout.CENTER, panel);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static JPanel createPanel() {
      JPanel panel = new JPanel() {
         public void paintComponent(Graphics g) {
            ImageIcon img = new ImageIcon("c:\mong.jpg");
            System.out.println(g.drawImage(img.getImage(), 0, 0, null));
            super.paintComponent(g);
         }
      };
      panel.setOpaque(false);
      panel.setLayout(new GridLayout(20, 4, 10, 10));
 
      for (int i=0; i<20; i++) {
         for (int j=0; j<4; j++) {
            JLabel label = new JLabel("label " + i + ", " + j);
            label.setFont(new Font("Helvetica", Font.PLAIN, 30));
            panel.add(label);            
         }
      }
 
      return panel;
   }
 
   public static void main(String [] args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   } 
} 

BTW, here’s the image I used:



Creating a nested JTabbedPane

The following example nests JTabbedPanes recursively until 10 levels deep:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.beans.*;
 
public class Main extends JFrame {
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
      JTabbedPane tabbedPane = new JTabbedPane();
 
      getContentPane().add(BorderLayout.CENTER, tabbedPane);
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      setTitle("JTabbedPane Nested Demonstration");
      setSize(new Dimension(400, 400));
 
      createTab(tabbedPane, 0);
   }
 
   protected void createTab(JTabbedPane jtp, int ct) {
      if (ct > 10) return;
      JTabbedPane tp = new JTabbedPane();
      tp.setTabPlacement(getNextOrientation(jtp.getTabPlacement()));
      jtp.addTab("TabLevel #" + ct, tp);
      createTab(tp, ct+1);
   }
 
   private int getNextOrientation(int tabPlacement) {
      if (tabPlacement == JTabbedPane.TOP) return JTabbedPane.RIGHT;
      if (tabPlacement == JTabbedPane.RIGHT) return JTabbedPane.BOTTOM;
      if (tabPlacement == JTabbedPane.BOTTOM) return JTabbedPane.LEFT;
      else return JTabbedPane.TOP;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Hiding a JToolBar that has been made floatable

Here’s an example that will hide a JToolBar, whether or not they have been made floatable.

Main.java:

import javax.swing.border.*;
import javax.swing.plaf.basic.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.awt.*;
  
public class Main extends JFrame {
   public Main() {
      super("JToolBar hide/show example");
 
      final JTextArea textArea = new JTextArea(5, 30);
      final MyJToolBar toolBar = new MyJToolBar();
 
      JButton gifButton = new JButton(new ImageIcon("gifIcon.gif"));
      JButton jpgButton = new JButton(new ImageIcon("jpgIcon.gif"));
      JButton tiffButton = new JButton(new ImageIcon("tiffIcon.gif"));
 
      gifButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("gifButton clicked!n");
         }
      });
  
      jpgButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("jpgButton clicked!n");
         }
      });
        
      tiffButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("tiffButton clicked!n");
         }
      });
 
      toolBar.add(gifButton);
      toolBar.add(new JToolBar.Separator());
      toolBar.add(jpgButton);
      toolBar.add(new JToolBar.Separator());
      toolBar.add(tiffButton);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.NORTH, toolBar);
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(textArea));
 
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("Toolbar");
      final JMenuItem hideShowMenuItem = new JCheckBoxMenuItem("Hide");
      menu.add(hideShowMenuItem);
      menuBar.add(menu);
      setJMenuBar(menuBar);
   
      hideShowMenuItem.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            toolBar.setVisible(!hideShowMenuItem.isSelected());
         }
      });
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}
 
class MyJToolBar extends JToolBar
{
   public MyJToolBar() {
      super();
   }
 
   public MyJToolBar(int orientation) {
      super(orientation);
   }
 
   public MyJToolBar(String name) {
      super(name);
   }
 
   public MyJToolBar(String name, int orientation) {
      super(name, orientation);
   }
 
   public void setVisible(boolean visible) {
      boolean isFloating = false;
      if (getUI() instanceof BasicToolBarUI) {
         isFloating = ((BasicToolBarUI) ui).isFloating();
      }
 
      if (isFloating) {
         SwingUtilities.getRoot(this).setVisible(visible);
      }
      else {
         super.setVisible(visible);
      }
   }
}

Preventing a JInternalFrame from being closed

Just specify so when you create a JInternalFrame, in the constructor, or call the method setClosable(false).

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame {
   JDesktopPane desktop;
   int nframes = 0;
  
   public Main() {
      desktop = new JDesktopPane(); 
      setContentPane(desktop);
      setJMenuBar(createMenuBar());
      createInternalFrame(); 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   protected JMenuBar createMenuBar() {
      JMenuBar menuBar = new JMenuBar();
 
      JMenu createMenu = new JMenu("Create");
      createMenu.setMnemonic(KeyEvent.VK_C);
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            createInternalFrame();
         }
      }); 
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      createMenu.add(newMenuItem);
      menuBar.add(createMenu);
 
      return menuBar;
   }
 
   protected void createInternalFrame() {
      nframes++;
      String title = "JInternalFrame #" + nframes;
      JInternalFrame frame = new JInternalFrame(title,
         true,    // resizable
         true,    // closable
         true,    // maximizable
         true);   // iconifiable
      frame.setVisible(true); 
 
      // disable closing the frame
      frame.setClosable(false);
 
      desktop.add(frame);
      frame.setSize(200, 200);
      frame.setLocation(30*nframes, 30*nframes);
      try {
         frame.setSelected(true);
      } catch (java.beans.PropertyVetoException e) {}
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(500, 300);
      main.setVisible(true);
   }
}

Assigning a shortcut key to a JCheckBox

Swings JButton inherits from AbstractButton that defines a method setMnemonic.
You can use it as follows:

import javax.swing.*;
import java.util.*;
import java.awt.*;
   
public class Main extends JFrame
{
   public Main() throws Exception {
      JCheckBox cbox1 = new JCheckBox("Check me or press ALT-C");
      JCheckBox cbox2 = new JCheckBox("Check me or press ALT-D");
      cbox1.setMnemonic('C');
      cbox2.setMnemonic('D');
 
      getContentPane().setLayout(new GridLayout(2, 1));
      getContentPane().add(cbox1);
      getContentPane().add(cbox2);
      pack();
 
      cbox1.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
            System.out.println("First JCheckBox checked!");
         }
      });

      cbox2.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
            System.out.println("Second JCheckBox checked!");
         }
      });
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String args[]) throws Exception {
      Main main = new Main();
      main.show();
   }
}

Creating an editable JComboBox

Use the method setEditable. Here’s an example:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame
{ 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
      final JComboBox combobox = new JComboBox();
      final JList list = new JList(new DefaultListModel());
 
      getContentPane().add(BorderLayout.NORTH, combobox);
      getContentPane().add(BorderLayout.CENTER, list); 
 
      combobox.setEditable(true);
      combobox.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent ie) {
            if (ie.getStateChange() == ItemEvent.SELECTED) {
               ((DefaultListModel) list.getModel()).addElement(combobox.getSelectedItem());
               combobox.insertItemAt(combobox.getSelectedItem(), 0);
            }
         }
      });
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });      
   
      setSize(new Dimension(200, 200));
   } 
 
   public static void main(String[] args) throws Exception {
      Main main = new Main();
      main.setVisible(true);
   }
}