Displaying image metadata with ImageIO

IIOMetadata contains meta information about the image, so not the actual pixels, but stuff like for example compression, keywords, comments, … If you convert from one format to another, you don’t want to loose this information. A ImageTranscoder understands this meta data and maps it onto another format. Internally, Metadata is stored as a bunch of IIOMetadataNodes (they implement the org.w3c.dom.Element interface). The format of this DOM tree is plug-in dependent: the native format (as format features are different), but plug-ins may support the plug-in neutral format. The following example program displays (using the XSLT transformation package) the plug-in neutral format.

Main.java:

import javax.imageio.metadata.*; 
import javax.imageio.stream.*;
import javax.imageio.*;
 
import java.awt.image.*;
import java.util.*;
import java.io.*;
  
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.*;
import javax.xml.parsers.*;
  
import org.w3c.dom.*; 
  
public class Main
{
   public static void main(String []args) throws Exception {
      Iterator readers = ImageIO.getImageReadersByFormatName("png");
      ImageReader reader = (ImageReader) readers.next();
 
      ImageInputStream iis = ImageIO.createImageInputStream(new File("coverpng.png"));
      reader.setInput(iis, true);
      BufferedImage bi = reader.read(0);

      IIOMetadata metadata = reader.getImageMetadata(0);
      Node node = (Node) metadata.getAsTree(metadata.getNativeMetadataFormatName());
 
      // use the XSLT transformation package to output the DOM tree we just created
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer();
      transformer.transform(new DOMSource(node), new StreamResult(System.out));
   }
}

outputs:

<? xml version="1.0" encoding="UTF-8"?>
<javax_imageio_png_1.0>
   <IHDR width="50" height="66" bitDepth="4" colorType="Palette" 
         compressionMethod="deflate" filterMethod="adaptive" 
         interlaceMethod="none"/>
   <PLTE>
      <PLTEEntry index="0" red="0" green="0" blue="0"/>
      <PLTEEntry index="1" red="128" green="192" blue="184"/>
      <PLTEEntry index="2" red="8" green="0" blue="0"/>
      <PLTEEntry index="3" red="248" green="252" blue="248"/>
      <PLTEEntry index="4" red="176" green="176" blue="176"/>
      <PLTEEntry index="5" red="184" green="220" blue="216"/>
      <PLTEEntry index="6" red="120" green="120" blue="120"/>
      <PLTEEntry index="7" red="16" green="152" blue="136"/>
      <PLTEEntry index="8" red="88" green="168" blue="160"/>
      <PLTEEntry index="9" red="72" green="72" blue="72"/>
      <PLTEEntry index="10" red="0" green="0" blue="0"/>
      <PLTEEntry index="11" red="0" green="0" blue="0"/>
      <PLTEEntry index="12" red="0" green="0" blue="0"/>
      <PLTEEntry index="13" red="0" green="0" blue="0"/>
      <PLTEEntry index="14" red="0" green="0" blue="0"/>
      <PLTEEntry index="15" red="0" green="0" blue="0"/>
   </PLTE>
</javax_imageio_png_1.0>

coverpng.png:

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 full screen JFrame

From 1.4, call the method setFullScreenMode on the default screen device.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame implements ActionListener
{
   public Main()
   {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      Button maxButton = new Button("Make this JFrame full-screen");
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
      getContentPane().add(maxButton);
      maxButton.addActionListener(this);
   }
 
   public void actionPerformed(ActionEvent ae) {     
      GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
      device.setFullScreenWindow(this);
   }
 
   public static void main(String args[])
   {
      Main main = new Main();
      main.setSize(300, 150);
      main.setVisible(true);
   }
}

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() );
      }
   }
}

Creating a JInternalFrame without a title bar

Try this:

   javax.swing.plaf.InternalFrameUI ui = frame.getUI();
   ((javax.swing.plaf.basic.BasicInternalFrameUI)ui).setNorthPane(null);

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;

public class Main extends JFrame
{
   JDesktopPane desktop;
 
   public Main() {
      desktop = new JDesktopPane(); 
      setContentPane(desktop);
      setBackgroundImage();
 
      // create internal frame with title bar
      createInternalFrame(true);
 
      // create internal frame without title bar
      createInternalFrame(false);
 
      setSize(new Dimension(500, 300));
      setLocation(100, 100);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0); 
         }
      });
   }
 
   protected void setBackgroundImage() {
      try {
         ImageIcon icon = new ImageIcon(new URL("http://www.esus.com/images/mong.jpg"));
         JLabel label = new JLabel(icon);
         label.setBounds(0, 0, icon.getIconWidth(), icon.getIconHeight());
  
         desktop.add(label, new Integer(Integer.MIN_VALUE));
      } catch(MalformedURLException e) {
         System.out.println(e);
      }
   }
  
   protected void createInternalFrame(boolean titlebar) {
 
      JInternalFrame frame = new JInternalFrame("InternalFrame", 
         true,    // resizable
         true,    // closable
         true,    // maximizable
         true);   // iconifiable
      if (!titlebar) {
         javax.swing.plaf.InternalFrameUI ui = frame.getUI();
            ((javax.swing.plaf.basic.BasicInternalFrameUI)ui).setNorthPane(null);
      }
 
      frame.setVisible(true); 
      desktop.add(frame);
      frame.setSize(200, 200);
      try {
         frame.setSelected(true);
      } catch (java.beans.PropertyVetoException e) {}
   }
 
   public static void main(String []args) throws Exception {
      Main main = new Main();
      main.show();      
   }
}

Detecting a state change on my JCheckBox

Add an ItemListener and put your behavior in itemStateChanged.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      final JCheckBox cb = new JCheckBox("Sample jcheckbox");
      cb.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            System.out.println("Checkbox state is now " + cb.isSelected());
         }
      });
 
      getContentPane().add(BorderLayout.NORTH, cb);
   } 
  
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 100);
      main.setVisible(true);
   }
}

Detecting a selection change on a JComboBox

Use an ActionListener.

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame { 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      }); 
 
      Vector v = new Vector();
      v.add(&quot;first element&quot;);
      v.add(&quot;second element&quot;);
      v.add(&quot;third element&quot;);
      v.add(&quot;fourth element&quot;);
      v.add(&quot;fifth element&quot;);
 
      final JComboBox cb = new JComboBox(v);
      cb.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println(cb.getSelectedItem());
         }
      });
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
      getContentPane().add(new JLabel(&quot;Select element:&quot;));
      getContentPane().add(cb);
   } 
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
      main.setSize(300, 150);
   }
}

Creating a sorted JList

This example shows you a method sortList that gets the JList data, puts them in an array, sorts them using Arrays.sort and updates the list model:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
  
public class Main extends JFrame {
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
 
      final DefaultListModel listModel = new DefaultListModel();   
 
      // populate listmodel
      Random r = new Random();
      for (int i=0; i<50; i++) {
         listModel.addElement("list item # " + (Math.abs(r.nextInt()) % 100));
      }
 
      final JList list = new JList(listModel); 
 
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(list));    
      JButton sortButton = new JButton("Sort");
      sortButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            sortList(list);
         }
      });
      getContentPane().add(BorderLayout.SOUTH, sortButton);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public void sortList(JList list) {
      ListModel model = list.getModel();
 
      int n = model.getSize();
      String[] data = new String[n]; 
 
      for (int i=0; i<n; i++) { 
         data[i] = (String) model.getElementAt(i); 
      }
 
      Arrays.sort(data); 
 
      list.setListData(data); 
   }
   
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Creating a JMenuItem with an image

Two constructors of JMenuItem take an Icon as parameters. Try the following example with these animated! GIFs:

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("menu");
      JMenuItem menuItem1 = new JMenuItem("male", new ImageIcon("male.gif"));
      JMenuItem menuItem2 = new JMenuItem("female", new ImageIcon("female.gif"));
      menu.add(menuItem1);
      menu.add(menuItem2);
      menuBar.add(menu);
 
      this.setJMenuBar(menuBar); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}