Read an image resource from a Jar file

Let’s first create an JAR file containing an image. Assuming that you have a GIF file called test.gif, type on the command line:

 
jar cvf Tester.jar test.gif

This will create the file Tester.jar.

Add this jar file to your classpath:

 
set classpath=%classpath%;C:Tester.jar

(“C:” or wherever you put your jar file).

The following piece of code shows you how the classloader is used to locate the resource (in this case “test.gif”) in the search path:

 
import java.net.*;
import javax.swing.*;
 
public class Tester {
    
   public ImageIcon loadImageFromJar(String imagename) {
      ImageIcon image = null;
 
      try {
         URLClassLoader cl = (URLClassLoader) getClass().getClassLoader();
         URL url = cl.findResource(imagename);
         image = new ImageIcon(url);
      } catch (Exception e) {
         System.err.println(e);
         System.exit(1);
      }
  
      return image;
   }   
 
   public static void main(String [] args) {
      Tester tester = new Tester();
 
      ImageIcon image = tester.loadImageFromJar("test.gif");
 
      System.out.println(image);
   }
}

Using java.util.logging MemoryHandler

A MemoryHandler keeps track of a buffer of LogRecords in memory and will pass them on to another handler when a certain PushLevel is triggered. The following example creates a MemoryHandler that keeps track of maximum 5 LogRecords and writes to a ConsoleHandler when an error occurs that is equal or more “dangerous” than Level.WARNING.

Main.java:

import java.util.logging.*;
import java.io.*;

public class Main
{
   public static void main(String argv[]) {
      Logger logger = Logger.getLogger("main");
      logger.setUseParentHandlers(false);
      logger.setLevel(Level.ALL);

      ConsoleHandler ch = new ConsoleHandler();
      ch.setLevel(Level.ALL);

      MemoryHandler mh = new MemoryHandler(ch, 5, Level.WARNING);
      mh.setLevel(Level.ALL);
      logger.addHandler(mh);

      logger.info  ("log message #1");
      logger.info  ("log message #2");
      logger.config("log message #3");
      logger.fine  ("log message #4");
      logger.config("log message #5");
      logger.info  ("log message #6");
      logger.config("log message #7");
      logger.fine  ("log message #8");
      logger.severe("log message #9");
   }
}

outputs:

Jan 20, 2002 4:21:35 PM Main main
CONFIG: log message #5
Jan 20, 2002 4:21:35 PM Main main
INFO: log message #6
Jan 20, 2002 4:21:35 PM Main main
CONFIG: log message #7
Jan 20, 2002 4:21:35 PM Main main
FINE: log message #8
Jan 20, 2002 4:21:35 PM Main main
SEVERE: log message #9

Get started with the 1.4 regex package

If you have no clue about what regular expressions are, check out Introduction to Regular Expressions by Tom Sgouros.

First, define a regular expression:

   Pattern p = Pattern.compile("hol");

Then you can apply that pattern to a sequence of characters (the interface CharSequence, which String, StringBuffer and CharBuffer implement, has been added to JDK1.4.

You can then create a Matcher providing it with a CharSequence to which you want to apply your pattern:

 
   Matcher m = p.matcher("I am the great Cornholio! I am a gringo. " +
                         "(heh-heh) I have no bunghole. (heh-heh) Bungholio.");

Executing matches() returns true when the whole region matches the pattern. find() returns true when there is a subsequence of the region that matches the pattern. You can find the start and end indexes with start() and end().

For example: MatchString.java:

import java.util.regex.*;
import java.io.*;
 
public class MatchString
{
   public static void main(String []args) throws Exception {
      Pattern p = Pattern.compile("[A-Z|a-z]*hol[A-Z|a-z]*");
 
      String line = "I am the great Cornholio! I am a gringo. (heh-heh) " +
                    "I have no bunghole. (heh-heh) Bungholio.";
      Matcher m = p.matcher(line);
 
      while (m.find()) {
         System.out.print(m.group());
         System.out.println("t[" + m.start() + ", " + m.end() + "]");
      }
   }
}

outputs:

Cornholio	[15, 24]
bunghole	[61, 69]
Bungholio	[81, 90]

To test out different regular expressions (find a summary of regular-expression constructs in the Javadoc documentation of Pattern), you can use the following example. It prints out a series of matches, given an input file and a regular expression.

Main.java:

import java.util.regex.*;
import java.io.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      if (args.length != 2) {
         System.err.println("Usage: java Main filename regex");
         System.exit(1);
      }
 
      Pattern p = Pattern.compile(args[1]);
 
      BufferedReader br = new BufferedReader(new FileReader(args[0]));     
      String line = null;
      while ((line = br.readLine()) != null) {
         Matcher m = p.matcher(line);
         while (m.find()) {
            System.out.println(line);
            indent(m.start());
            System.out.print("^");
            indent(m.end()-m.start()-2);
            System.out.println("^");
         }
      } 
      br.close();
   }
 
   public static void indent(int h) {
      for (int i=0; i<h; i++) 
         System.out.print(' ');
   }
}

Example:

   c:jdk1.4binjava Main Main.java "[a-z]*fer"

outputs:

      BufferedReader br = new BufferedReader(new FileReader(args[0]));
       ^   ^
      BufferedReader br = new BufferedReader(new FileReader(args[0]));
                               ^   ^

Create my own java.util.zip checksum class

Implement the Checksum interface. This interface defines the following methods:

   long getValue();
   void reset();
   void update(byte[] b, int off, int len);
   void update(int b);

The following example creates a checksum that is based on the following algorithm:

   take remainder of (the sum of the byte values divided by 999999)

The distribution of this checksum is pretty bad, but that’s not the point :)

Main.java:

import java.util.zip.*;
import java.io.*;
 
public class Main {
   public static void main(String args[]) throws Exception {
      CheckedOutputStream cis = new CheckedOutputStream(new FileOutputStream("testfile"), 
                                                        new MyChecksum());
 
      cis.write("abcdef".getBytes());
      cis.close();
 
      System.out.println("Checksum of outputstream = " + 
                               + cis.getChecksum().getValue());
    }
}
 
class MyChecksum implements Checksum
{
   long value = 0;
 
   public long getValue() {
      return value % 999999;
   }
 
   public void update(int b) {
      value += b;
   }
 
   public void update(byte[] b, int off, int len) {
      for (int i=0; i<len; i++) {
         value += (int) b[off+i];
      }
   }
 
   public void reset() {
      value = 0;
   }
}

outputs:

597 			(since "abcdef" = 97+98+99+100+101+102 = 597)

Localizing a JOptionPane

You can do so by changing the UI Look and Feel default values. The following text values are changeable:

   OptionPane.cancelButtonText
   OptionPane.noButtonText
   OptionPane.okButtonText
   OptionPane.yesButtonText

You can change them by adjusting the default value in the hashtable contained in UIManager class. The program below an example. As a side note, the other default keys that are used by JOptionPane and can be customized to fit your needs are these:

   OptionPane.background
   OptionPane.border
   OptionPane.buttonAreaBorder
   OptionPane.cancelButtonText
   OptionPane.errorIcon
   OptionPane.fontOptionPane.foreground
   OptionPane.informationIcon
   OptionPane.messageAreaBorder
   OptionPane.messageForeground
   OptionPane.minimumSize
   OptionPane.noButtonText
   OptionPane.okButtonText
   OptionPane.questionIcon
   OptionPane.warningIcon
   OptionPane.yesButtonText

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      UIManager.put("OptionPane.yesButtonText", "Ja");
      UIManager.put("OptionPane.noButtonText", "Neen");
 
      Button button = new Button("Show JOptionPane");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            JOptionPane.showConfirmDialog(Main.this, "Does this JOptionPane " +
                "contain Dutch buttons?", "Question", JOptionPane.YES_NO_OPTION);
         }
      });
 
      getContentPane().add(button);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String [] args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   } 
} 

Creating a tooltip for the JFrame’s title bar

You can’t, with pure Java. JFrame extends from Frame, a heavy-weight component. The JFrame title bar is controlled in by native peers. For example, in Windows, to ensure a consistent look and feel, you can set title bar fonts and window colors via the Control Panel Display.

Changing the orientation of a JTabbedPane

Use the method setTabPlacement in JTabbedPane. As a parameter, you can pass JTabbedPane.TOP, JTabbedPane.BOTTOM, JTabbedPane.LEFT, JTabbedPane.RIGHT.
Here’s an example:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame implements ActionListener {
   JTabbedPane tabbedPane;
   int ntabs = 0;
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
      tabbedPane = new JTabbedPane();
      createTab();
 
      getContentPane().add(BorderLayout.CENTER, tabbedPane);
      setJMenuBar(createMenuBar());
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   
      setTitle("JTabbedPane Orientation Demonstration");
      setSize(new Dimension(400, 400));
   }
 
   protected JMenuBar createMenuBar() {
      JMenuBar menuBar = new JMenuBar();
 
      JMenu menu1 = new JMenu("JTabbedPane");
      JMenuItem menuItem1 = new JMenuItem("Create new tab");
      menuItem1.addActionListener(this);
      menu1.add(menuItem1);
      JMenu menu2 = new JMenu("Change orientation");
      JMenuItem menuItem2 = new JMenuItem("TOP");
      menuItem2.addActionListener(this);
      menu2.add(menuItem2);
      JMenuItem menuItem3 = new JMenuItem("BOTTOM");
      menuItem3.addActionListener(this);
      menu2.add(menuItem3);
      JMenuItem menuItem4 = new JMenuItem("LEFT");
      menuItem4.addActionListener(this);
      menu2.add(menuItem4);
      JMenuItem menuItem5 = new JMenuItem("RIGHT");
      menuItem5.addActionListener(this);
      menu2.add(menuItem5);
      menuBar.add(menu1);
      menuBar.add(menu2);
 
      return menuBar;
   }
  
   public void actionPerformed(ActionEvent e) {
      if (e.getActionCommand().equals("Create new tab")) {
         createTab();
      }
      else if (e.getActionCommand().equals("TOP")) {
         tabbedPane.setTabPlacement(JTabbedPane.TOP);
      }
      else if (e.getActionCommand().equals("BOTTOM")) {
         tabbedPane.setTabPlacement(JTabbedPane.BOTTOM);
      }
      else if (e.getActionCommand().equals("LEFT")) {
         tabbedPane.setTabPlacement(JTabbedPane.LEFT);
      }
      else if (e.getActionCommand().equals("RIGHT")) {
         tabbedPane.setTabPlacement(JTabbedPane.RIGHT);
      }
   }
 
   protected void createTab() {
      ntabs++;
      tabbedPane.addTab("Tab #" + ntabs, new JLabel("Tab #" + ntabs));
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Changing the border of a JToolBar

ToolBarTest.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class ToolBarTest extends JFrame implements ActionListener
{
   JToolBar myToolBar = null;
 
   public ToolBarTest ()
   {
      /**
       * create the Toolbar
       */
      myToolBar = new JToolBar( JToolBar.HORIZONTAL );
      myToolBar.setFloatable( false );
 
      /**
       * first Toolbar-Button
       */
      JButton button1 = new JButton( "BevelBorder" );
      button1.addActionListener( this );
      myToolBar.add( button1 );
 
      /**
       * second Toolbar-Button
       */
      JButton button2 = new JButton( "LineBorder"  );
      button2.addActionListener( this );
      myToolBar.add( button2 );
 
      /**
       * third Toolbar-Button
       */
      JButton button3 = new JButton( "No Border"   );
      button3.addActionListener( this );
      myToolBar.add( button3 );
 
      /**
       * set BorderLayout for the contentPane and add the toolbar
       */
      getContentPane().setLayout( new BorderLayout() );
      getContentPane().add( myToolBar, BorderLayout.NORTH );
      pack();
   }
 
   public static void main ( String args[] )
   {
      /**
       * create the ToolBarTest-frame
       */
      ToolBarTest frame = new ToolBarTest();
 
      frame.addWindowListener(new WindowAdapter() {
         public void windowClosing (WindowEvent e) {
            System.exit( 0 );
         }
      });
 
      /**
       * display the frame
       */
      frame.pack();
      frame.setVisible( true );
   }
 
   public void actionPerformed ( ActionEvent e )
   {
      /**
       * set the specified Border with BorderFactory...
       */
 	 
      if ( e.getActionCommand().equals( "BevelBorder" ) )
      {
         myToolBar.setBorder( BorderFactory.createRaisedBevelBorder() );
      }
      else if ( e.getActionCommand().equals( "LineBorder" ) )
      {
         myToolBar.setBorder( BorderFactory.createLineBorder( Color.black, 2 ) );
      }
      else if ( e.getActionCommand().equals( "No Border" ) )
      {
         myToolBar.setBorder( BorderFactory.createEmptyBorder() );
      }
   }
}

Preventing a JInternalFrame from being moved

You can subclass the protected class BorderListener that is defined in BasicInternalFrameUI and provide an empty implementation for mouseDragged. In the following example, it is done so for the Metal look and feel.

Main.java:

import javax.swing.plaf.basic.*;
import javax.swing.plaf.metal.*;
import javax.swing.event.*;
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;
 
   JMenu internalFrameMenu;
 
   public Main() {
      desktop = new JDesktopPane(); 
      setContentPane(desktop);
      setJMenuBar(createMenuBar());
      createInternalFrame(); 
   }
 
   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); 
      desktop.add(frame);
      frame.setSize(200, 200);
      frame.setLocation(30*nframes, 30*nframes);
      try {
         frame.setSelected(true);
      } catch (java.beans.PropertyVetoException e) {}
 
      frame.setUI(new MyMetalInternalFrameUI(frame));
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(500, 300);
      main.setVisible(true);
   }
}
 
class MyMetalInternalFrameUI extends MetalInternalFrameUI {
   public MyMetalInternalFrameUI(JInternalFrame b) { super(b); }
 
   protected MouseInputAdapter createBorderListener(JInternalFrame w) {
      return new MyBorderListener();
   }
 
   protected class MyBorderListener extends BasicInternalFrameUI.BorderListener {
      public void mouseDragged(MouseEvent e) {  }
   }
}

Putting a Image on a JButton

Check out the API! You’ll see that there is a constructor taking an Icon object as parameter. Here’s an example showing two buttons with the following animated gifs on them:

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
  
public class Main extends JFrame implements ActionListener {
   JList list; 
 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JButton mbutton = new JButton("female", new ImageIcon("male.gif"));
      JButton fbutton = new JButton("male", new ImageIcon("female.gif"));
      mbutton.addActionListener(this);
      fbutton.addActionListener(this);
      getContentPane().add(mbutton);
      getContentPane().add(fbutton);
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public void actionPerformed(ActionEvent ae) {
      System.out.println("Your pressed the " + ae.getActionCommand() + " button");
   }
   
   public static void main(String[] args) {
      (new Main()).show();
   }
}