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.

Adding a JButton inside my JSplitPane divider

Main.java:

import javax.swing.plaf.basic.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.awt.*;
 
public class Main extends JFrame
{
   JSplitPane splitPane;
  
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, 
                                 new JPanel(), new JPanel());
      splitPane.setDividerSize(20);
  
      JButton button = new JButton("Exit!");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.exit(0);
         }
      });
 
      setJMenuBar(getMainMenuBar());
 
      splitPane.setUI(new ButtonDividerUI(button));
 
      getContentPane().add(splitPane);
 
      addComponentListener(new ComponentAdapter() {
         public void componentShown(ComponentEvent event) {
            splitPane.setDividerLocation(0.5);  
                
            removeComponentListener(this);
         }
      });
   }
 
   public JMenuBar getMainMenuBar() {
      JMenuBar mainBar = new JMenuBar();
      JMenu menu = new JMenu("JSplitPane");
      JMenuItem item1 = new JMenuItem("HORIZONTAL_SPLIT");
      JMenuItem item2 = new JMenuItem("VERTICAL_SPLIT");
      menu.add(item1);
      menu.add(item2);
      mainBar.add(menu);
 
      item1.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
         }
      });
 
      item2.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
         }
      });
 
      return mainBar;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}
 
class ButtonDividerUI extends BasicSplitPaneUI
{
   protected JButton button;
 
   public ButtonDividerUI(JButton button) {
      this.button = button;
   }
 
   public BasicSplitPaneDivider createDefaultDivider() {
      BasicSplitPaneDivider divider = new BasicSplitPaneDivider(this) {
         public int getDividerSize() { 
            if (getOrientation() == JSplitPane.HORIZONTAL_SPLIT) {
               return button.getPreferredSize().width; 
            }
            return button.getPreferredSize().height;
         }
      };
 
      divider.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
      divider.add(button);
 
      return divider;
   }
}

Adding a close (X) button to tabs in a JTabbedPane

Here’s a quick hack.

Main.java:

import javax.swing.plaf.metal.*;
import javax.swing.plaf.*;
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();
      tabbedPane.setUI(new CustomTabbedPaneUI());
      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();
   }
}
 
class CustomTabbedPaneUI extends MetalTabbedPaneUI 
{
   Rectangle xRect;
 
   protected void installListeners() {
      super.installListeners();
      tabPane.addMouseListener(new MyMouseHandler());
   }
 
   protected void paintTab(Graphics g, int tabPlacement,
                           Rectangle[] rects, int tabIndex, 
                           Rectangle iconRect, Rectangle textRect) {
      super.paintTab(g, tabPlacement, rects, tabIndex, iconRect, textRect);
 
      Font f = g.getFont();
      g.setFont(new Font("Courier", Font.BOLD, 10));
      FontMetrics fm = g.getFontMetrics(g.getFont());
      int charWidth = fm.charWidth('x');
      int maxAscent = fm.getMaxAscent();
      g.drawString("x", textRect.x + textRect.width - 3, textRect.y + textRect.height - 3);
      g.drawRect(textRect.x+textRect.width-5,
                 textRect.y+textRect.height-maxAscent, charWidth+2, maxAscent-1);
      xRect = new Rectangle(textRect.x+textRect.width-5, 
                 textRect.y+textRect.height-maxAscent, charWidth+2, maxAscent-1);
      g.setFont(f);
    }
 
    public class MyMouseHandler extends MouseAdapter {
        public void mousePressed(MouseEvent e) {
            System.out.println(e);
            if (xRect.contains(e.getPoint())) {
               JTabbedPane tabPane = (JTabbedPane)e.getSource();
               int tabIndex = tabForCoordinate(tabPane, e.getX(), e.getY());
               tabPane.remove(tabIndex);
            }
        }
    } 
}