Logging AWT events

You can do so by subclassing EventQueue and adding logging functionality. Then replace the system event queue with that logging queue.

Main.java:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
class Main extends JFrame
{
   public Main() {
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
      getContentPane().add(new JButton("Test button"));
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.setDefaultCloseOperation(EXIT_ON_CLOSE);
      main.setSize(200, 200);
 
      main.getToolkit().getSystemEventQueue().push(new LoggingEventQueue());
 
      main.setVisible(true);
   }
}

LoggingEventQueue.java:

import java.awt.*;
 
public class LoggingEventQueue extends EventQueue
{
   protected void dispatchEvent(AWTEvent event) {
      super.dispatchEvent(event);
      System.out.println(event);
   }
}

Getting a list of all display modes

From JDK1.4, you can use the class DisplayMode. Get the current GraphicsDevice, and call the method getDisplayModes.

Main.java:

import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   public static void main(String[] args) {
      GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment ();
 
      GraphicsDevice gd = ge.getDefaultScreenDevice ();
 
      DisplayMode dp[] = gd.getDisplayModes();
 
      for (int i=0; i<dp.length; i++) {
         int width = dp[i].getWidth();
         int height = dp[i].getHeight();
         int bitDepth = dp[i].getBitDepth();
         int refreshRate = dp[i].getRefreshRate();
         System.out.println(width + "x" + height + " " + 
                            bitDepth + "bit " + 
                            (refreshRate == 0 ? "unknown" : ""+refreshRate + "hz"));
      }
   } 
}

outputs on my machine:

640x480 8bit unknown
800x600 8bit unknown
1024x768 8bit unknown
1152x864 8bit unknown
1280x1024 8bit unknown
640x480 16bit unknown
800x600 16bit unknown
1024x768 16bit unknown
1152x864 16bit unknown
1280x1024 16bit unknown
640x480 32bit unknown
800x600 32bit unknown
1024x768 32bit unknown
1152x864 32bit unknown
1280x1024 32bit unknown

Combining two shapes in Swing

Cast the shapes to areas where you have the methods add, subtract, intersect and exclusiveOr.

Main.java:

import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      }); 
   }
 
   public void paint(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
 
      Shape shape1 = new Rectangle2D.Double(80, 50, 40, 40);
      Shape shape2 = new Rectangle2D.Double(20, 60, 160, 20);
 
      g2d.setColor(Color.black); 
      g2d.drawString("normal:", 20, 40);
      g2d.draw(shape1); 
      g2d.draw(shape2); 
 
      g2d.translate(0, 70);
      g2d.setColor(Color.yellow); 
      g2d.fill(combine("add", shape1, shape2));
      g2d.setColor(Color.black); 
      g2d.drawString("area add:", 20, 40);
      g2d.draw(shape1); 
      g2d.draw(shape2); 
 
      g2d.translate(0, 70);
      g2d.setColor(Color.yellow); 
      g2d.fill(combine("subtract", shape1, shape2));
      g2d.setColor(Color.black); 
      g2d.drawString("area subtract:", 20, 40);
      g2d.draw(shape1); 
      g2d.draw(shape2); 
 
      g2d.translate(0, 70);
      g2d.setColor(Color.yellow); 
      g2d.fill(combine("intersect", shape1, shape2));
      g2d.setColor(Color.black); 
      g2d.drawString("area intersect:", 20, 40);
      g2d.draw(shape1); 
      g2d.draw(shape2); 
 
      g2d.translate(0, 70);
      g2d.setColor(Color.yellow); 
      g2d.fill(combine("exclusiveOr", shape1, shape2));
      g2d.setColor(Color.black); 
      g2d.drawString("area exclusiveOr:", 20, 40);
      g2d.draw(shape1); 
      g2d.draw(shape2); 
   }
 
   public Shape combine(String op, Shape shape1, Shape shape2) {
      Area area1 = new Area(shape1);
      Area area2 = new Area(shape2);
      
      if (op.equals("add")) area1.add(area2);
      else if (op.equals("subtract")) area1.subtract(area2);
      else if (op.equals("intersect")) area1.intersect(area2);
      else if (op.equals("exclusiveOr")) area1.exclusiveOr(area2);
 
      return area1;
   }
  
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(200, 400);
      main.setVisible(true);
   }
}

Drawing a paragraph of text in Swing

Main.java:

import java.awt.event.*;
import java.awt.geom.*;
import java.awt.font.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
 
public class Main extends JFrame {
   private String text;
   LineBreakMeasurer lineMeasurer;
   int beginIndex, endIndex;
   
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });  
 
      text = "It is, in fact, nothing short of a miracle that the modern methods " +
             "of instruction have not yet entirely strangled the holy curiosity " +
             "of inquiry; for this delicate little plant, aside from stimulation, " +
             "stands mainly in need of freedom; without this it goes to wrack and " +
             "ruin without fail. It is a very grave mistake to think that the " +
             "enjoyment of seeing and searching can promoted by means of coercion " +
             "and sense of duty. To the contrary, I believe that it would be " +
             "possible to rob even a healthy beast of prey of its voraciousness, " +
             "if it were possible, with the aid of a whip, to force the beast to " +
             "devour continuously, even when not hungry,especiallyif the food, " +
             "handed out under such coercion, were to be selected accordingly." +
             "n" +
             "Albert Einstein";
 
      AttributedString as = new AttributedString(text);
      AttributedCharacterIterator aci = as.getIterator();
 
      FontRenderContext frc = new FontRenderContext(null, false, false);
 
      beginIndex = aci.getBeginIndex();
      endIndex = aci.getEndIndex();
 
      // Create a new LineBreakMeasurer from the paragraph.
      lineMeasurer = new LineBreakMeasurer(aci, frc);
   }
 
   public void paint(Graphics g) {
      super.paint(g);
 
      Graphics2D g2d = (Graphics2D) g;
 
      Dimension size = getSize();
      float width = (float) size.width - 40;
 
      float x=10, y=30;
 
      g2d.setFont(new Font("Serif", Font.PLAIN, 24));
      lineMeasurer.setPosition(beginIndex);
      while (lineMeasurer.getPosition() < endIndex) {
         TextLayout layout = lineMeasurer.nextLayout(width);
 
         x = 10;   
         y += layout.getAscent() + layout.getDescent() + layout.getLeading();
       
         layout.draw(g2d, x, y);
     }
   }
   
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(420, 230);
      main.setVisible(true);
   }
}

Converting an Image to a BufferedImage in Swing

This following example reads a JPEG imgage from disk, converts it to a bufferedimage and displays it onto the screen.

import java.awt.event.*;
import java.awt.image.*;
import java.awt.color.*;
import javax.swing.*;
import java.awt.*;
                           
public class Main extends JFrame
{
   public Main() throws Exception {
      BufferedImage bi = createBufferedImage("ally.jpg");
                       
      // add the image inside a JLabel component to the window
      getContentPane().add(new JLabel(new ImageIcon(bi)));
      pack();
                         
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public BufferedImage createBufferedImage(String filename) {
      Image img = Toolkit.getDefaultToolkit().getImage(filename);
      try {
         MediaTracker tracker = new MediaTracker(this);
         tracker.addImage(img, 0);
         tracker.waitForID(0);
      }
      catch ( Exception e ) {} 
 
      BufferedImage bi = 
         new BufferedImage(img.getWidth(this), img.getHeight(this),
                        BufferedImage.TYPE_INT_RGB);
      Graphics2D g2d = bi.createGraphics();
      g2d.drawImage(img, 0, 0, this);
 
      return bi;
   }
 
   public static void main(String args[]) throws Exception {
      Main main = new Main();
      main.show();
   }
}

Posterizing an image in Swing


Will reduce the number of colors used!

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);
 
         short[] posterize = new short[256];
         for(int i=0; i<256; i++) {
            posterize[i] = (short) (i - (i % 32));
         }
  
         ShortLookupTable slt = new ShortLookupTable(0, posterize);
         LookupOp op = new LookupOp(slt, null);
         destBi = op.filter(sourceBi, null);
 
         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);
   }
}

Example of an ImageIO transcoder

A transcoder is responsible for converting one particular image type to another and is designed in such a way that metadata specific to that image type is not lost.

The following example outputs all transcoders that are defined for converting gif to jpg. Currently there are none, but since ImageIO is pluggable, third-party transcoders should become available soon.

Main.java:

import javax.imageio.stream.*;
import javax.imageio.*;
import java.util.*;
  
public class Main
{
   public static void main(String []args) {
      Iterator readers = ImageIO.getImageReadersByFormatName("gif");
      ImageReader reader = (ImageReader) readers.next();
 
      Iterator writers = ImageIO.getImageWritersByFormatName("jpg");
      ImageWriter writer = (ImageWriter) writers.next();
 
      Iterator transcoders = ImageIO.getImageTranscoders(reader, writer);
      while (transcoders.hasNext()) {
         ImageTranscoder tc = (ImageTranscoder) transcoders.next();
         System.out.println(tc);
      }
   }
}

Having the Enter key activate the default button on a JDialog

Use getRootPane() and setDefaultButton to make a button on a JDialog respond to the ‘enter’ key. I’ve included code that allows which ever button has focus to be the default.

   ... begin snippet ...
   JButton ok = new JButton("OK");
   JButton cancel = new JButton("CANCEL");
 
   //kicks off when component gains focus
   ok.addFocusListener(new buttonfocusEventHandler());
 
   //kicks off when component gains focus
   cancel.addFocusListener(new buttonfocusEventHandler()); 
 
   ... end snippet ...

   class buttonfocusEventHandler extends FocusAdapter {

      /** Checks buttons on dialog for focus
       * and makes that button the default
       * 
       * @param evt Holds event
       */
      public void focusGained(FocusEvent evt) {
 
         JButton button = (JButton) evt.getSource();
           
         if (button == ok) {
            JRootPane root = getRootPane();
            root.setDefaultButton(button);
         } //end if
            
         if (button == cancel){
            JRootPane root = getRootPane();
            root.setDefaultButton(button);
         } // end if
      }             
}  //  end buttonfocusEventHandler

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