Switching to another display mode

From JDK1.4, you can use the class DisplayMode. Either instantiate a DisplayMode object by specifying width, height, bitdepth and refreshrate, or get a list of available DisplayModes by calling the method getDisplayModes on the current GraphicsDevice.

When you’ve made up your mind about the display mode, call the method setFullScreenWindow to get the device into “full-screen exclusive mode” (necessary) and the method setDisplayMode to perform the display change.

Main.java:

import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   DisplayMode oldDm;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment (); 
      final GraphicsDevice gd = ge.getDefaultScreenDevice ();
 
      oldDm = gd.getDisplayMode();
      final DisplayMode dm[] = gd.getDisplayModes();
 
      Vector v = getDisplayModesAsStrings(dm);
      final JComboBox cb = new JComboBox(v);
      cb.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            int selectedIndex = cb.getSelectedIndex();
            gd.setFullScreenWindow(Main.this);
        
            if (gd.isDisplayChangeSupported()) {
               try {
                  gd.setDisplayMode(dm[selectedIndex]); 
               } catch(Exception e) {
                  gd.setDisplayMode(oldDm);
               }
            }
            else {
               System.out.println("Display change not supported!");
            }            
         }
      });
 
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
      getContentPane().add(new JLabel("Change to display mode:"));
      getContentPane().add(cb);
      pack();  
   }
 
   public Vector getDisplayModesAsStrings(DisplayMode dm[]) {
      Vector v = new Vector();
 
      for (int i=0; i<dm.length; i++) {
         int width = dm[i].getWidth();
         int height = dm[i].getHeight();
         int bitDepth = dm[i].getBitDepth();
         int refreshRate = dm[i].getRefreshRate();
         v.add("" + width + "x" + height + " " + bitDepth + "bit " + 
                              (refreshRate == 0 ? "unknown" : ""+refreshRate + "hz"));
      }
 
      return v;
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.setVisible(true);
   } 
}

Checking for a mouseclick on a Swing shapes

This following example create an arbitrary shape using GeneralPath and allows you to click anywhere on the JFrame. If the mouseclick x and y coordinate are within the shape, e method contains will return true.

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private GeneralPath gp;
  
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      constructShape();
  
      addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent me) {
            me.translatePoint(-150, -150);
 
            if (gp.contains(me.getX(), me.getY())) {
               System.out.println(me.getX() + ", " + me.getY() + 
                                  " lies within the shape.");
            }
            else {
               System.out.println(me.getX() + ", " + me.getY() + 
                                  " lies not within the shape.");
            }
         }
      });
   }
 
   public void constructShape() {
      gp = new GeneralPath();
      gp.moveTo(   0,  100);
      gp.quadTo( -75,   25,    0, -100);
      gp.quadTo(  75,   25,    0,  100);
      gp.lineTo( -50,  -50);
      gp.lineTo(  50,  -50);
      gp.closePath();
   }   
 
   public void paint(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
 
      // set origin to middle of window
      g2d.translate(150f, 150f);
 
      g2d.draw(gp);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}

Drawing a tilted text in Swing

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.font.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame { 
   JSlider hslider, vslider;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      hslider = new JSlider(JSlider.HORIZONTAL, 0, 20, 10);
      hslider.addChangeListener(new ChangeListener() {
         public void stateChanged(ChangeEvent ce) {
            repaint();
         }
      });
 
      vslider = new JSlider(JSlider.VERTICAL, 0, 20, 10);
      vslider.addChangeListener(new ChangeListener() {
         public void stateChanged(ChangeEvent ce) {
            repaint();
         }
      });
  
      hslider.setMajorTickSpacing(1);
      hslider.setPaintTicks(true);
      hslider.setPaintLabels(true);
 
      vslider.setMajorTickSpacing(1);
      vslider.setPaintTicks(true);
      vslider.setPaintLabels(true);
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.SOUTH, hslider);
      getContentPane().add(BorderLayout.WEST, vslider);
   }
  
   public void paint(Graphics g) {
      super.paint(g); 
  
      Graphics2D g2d = (Graphics2D) g;

      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                           RenderingHints.VALUE_ANTIALIAS_ON);
  
      String text = "90% of all statistics are made up!";
 
      int w = getSize().width;
      int h = getSize().height;
 
      AffineTransform atShear = new AffineTransform();
      atShear.shear((hslider.getValue()-10)/10.0, -(vslider.getValue()-10)/10.0);
 
      FontRenderContext frc = g2d.getFontRenderContext();
      Font font = new Font("Serif", Font.BOLD, 24);
      Font derivedFont = font.deriveFont(atShear);
      TextLayout tl = new TextLayout(text, derivedFont, frc);
 
      AffineTransform at = new AffineTransform();
      at.setToTranslation(70, h/2);
      g2d.transform(at);
 
      g2d.setColor(Color.blue);
      tl.draw(g2d, 0f, 0f);
 
      g2d.setColor(Color.black);
      g2d.drawString("Shear x:" + (hslider.getValue()-10)/10.0, 60, 50-h/2);
      g2d.drawString("Shear y:" + -(vslider.getValue()-10)/10.0, 150, 50-h/2);
   }
   
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(550, 400);
      main.setVisible(true);
   }
}

Setting individual pixels in a BufferedImage in Swing

You can use the method setRGB. This example goes through a loop painting each pixel of the BufferedImage individually.

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private boolean firstTime = true;
   private BufferedImage bufferedImage;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      }); 
   } 
 
   public void paint(Graphics graphics) {
      Graphics2D g2d = (Graphics2D) graphics;
  
      g2d.drawString("Please wait...", 100, 100);
      if (firstTime) {
         bufferedImage = (BufferedImage) createImage(getSize().width, getSize().height);
 
         int x=0, y=0;
         for (int r=0; r<=255; r+=4) {
            for (int g=0; g<=255; g+=4) {
               for (int b=0; b<=255; b+=4) {
                  x++; if (x>getSize().width) { y++; x = 0; }
                  Color c = new Color(r, g, b);
                  bufferedImage.setRGB(x, y, c.getRGB());
               }
            }
         }
 
         firstTime = false;
      }
 
      g2d.drawImage(bufferedImage, 0, 0, this);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
      main.setSize(512, 512);
   }
}

Performing edge detection of an image in Swing

Apply an edge detection filter using the class ConvolveOp.

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private boolean firstTime = true;
   private BufferedImage sourceBi;
   private BufferedImage destBi;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      }); 
   } 
 
   public void paint(Graphics graphics) {
      Graphics2D g2d = (Graphics2D) graphics;
  
      if (firstTime) {
         Image img = new javax.swing.ImageIcon("djkrush.jpg").getImage(); 
         sourceBi = toBufferedImage(img);
         destBi = new BufferedImage(sourceBi.getWidth(), sourceBi.getHeight(), 
                                    BufferedImage.TYPE_INT_RGB);
         setSize(sourceBi.getWidth(), sourceBi.getHeight()*2);
 
         Kernel kernel = new Kernel(3, 3, new float[] 
                                            { 1, 1, 1,
                                              1,-2, 1,
                                             -1,-1,-1 });
         ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
         cOp.filter(sourceBi, destBi);
 
         firstTime = false;
      }
 
      g2d.drawImage(sourceBi, 0, 0, this);
      g2d.drawImage(destBi, 0, sourceBi.getHeight(), this);
   }
 
   public static BufferedImage toBufferedImage(Image image) {
      BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), 
                                           BufferedImage.TYPE_INT_RGB); 
 
      // copy the original image
      Graphics g = bi.createGraphics();
    
      g.drawImage(image, 0, 0, null);
      g.dispose();
 
      return bi;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
      main.setSize(300, 150);
   }
}

Image used:

To learn more about image processing,
check out this expensive but excellent book:

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