Getting the FontMetrics of all available fonts on your system?

This code will display some FontMetrics information about the font you select.

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);
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      FontRendering fr = new FontRendering();
      getContentPane().add(BorderLayout.CENTER, fr);
      getContentPane().add(BorderLayout.NORTH, new FontRenderingControls(fr));
   } 
 
   public static class FontRenderingControls extends JPanel implements ActionListener {
      FontRendering fr;
 
      public FontRenderingControls(FontRendering fr) {
         this.fr = fr;
 
         Vector v = new Vector();
         GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
         Font f[] = ge.getAllFonts();
         for (int i = 0; i < f.length; i++) {
            if (f[i].canDisplayUpTo(f[i].getName()) > 0) {
               v.addElement(f[i].getName());
            }
         }      
 
         final JComboBox fontCombo = new JComboBox(v);
         add(fontCombo);
         fontCombo.addActionListener(this);
      }
 
      public void actionPerformed(ActionEvent e) {
         JComboBox fontCombo = (JComboBox) e.getSource();
         fr.font = (String) fontCombo.getSelectedItem();
         fr.repaint();
      }
   }
 
   public static class FontRendering extends JPanel {
      public String text = "Easter Island";
      public String font = "Helvetica";
 
      public void paint(Graphics g) {
         Graphics2D g2d = (Graphics2D) g;
 
         Font f = g2d.getFont();
  
         g2d.setFont(new Font(font, Font.BOLD, 36));
         g2d.drawString(text, 10, 40); 
 
         FontMetrics fm = g2d.getFontMetrics();
    
         g2d.setFont(f);
         FontMetrics fm2 = g2d.getFontMetrics();
         g2d.drawString("FontMetrics:", 10, 60);
         g2d.drawString("Ascent: "      + 
                          fm.getAscent(), 50, 60 + fm2.getHeight());
         g2d.drawString("Descent: "     + 
                          fm.getDescent(), 50, 60 + fm2.getHeight() * 2);
         g2d.drawString("Height: "      + 
                          fm.getHeight(), 50, 60 + fm2.getHeight() * 3);
         g2d.drawString("Leading: "     + 
                          fm.getLeading(), 50, 60 + fm2.getHeight() * 4);
         g2d.drawString("MaxAdvance: "  + 
                          fm.getMaxAdvance(), 50, 60 + fm2.getHeight() * 5);
         g2d.drawString("MaxAscent: "   + 
                          fm.getMaxAscent(), 50, 60 + fm2.getHeight() * 6);
         g2d.drawString("MaxDescent: "  + 
                          fm.getMaxDescent(), 50, 60 + fm2.getHeight() * 7);
      }
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
      main.setSize(300, 300);
   }
}

Drawing a textured round filled rectangle in Swing

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 BufferedImage image; 
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      image = toBufferedImage(new javax.swing.ImageIcon("c:\djkrush.jpg").getImage());
   }
 
   public void paint(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
 
      Rectangle2D tr = new Rectangle2D.Double(0, 0, image.getWidth(), image.getHeight());
      TexturePaint tp = new TexturePaint(image, tr);
 
      // draw texture filled ellipse, but with antialiasing
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                           RenderingHints.VALUE_ANTIALIAS_ON);
      BasicStroke bs = new BasicStroke(5, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
                           10, null, 0);
      g2d.setStroke(bs);
      g2d.setPaint(tp);
      g2d.drawRoundRect(10, 40, 150, 150, 50, 30);
   }
 
   public 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.setSize(170, 210);
      main.setVisible(true);
   }
}

Image used:

Cropping an image in Swing

Use the class CropImageFilter.

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.awt.*;
 
public class Main extends JFrame {
   private Image image;
   int startx, starty;
   int stopx, stopy;
   int currentx, currenty;
   
   public Main() throws Exception {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      image = new javax.swing.ImageIcon("http://www.esus.com/images/space.jpg").getImage();
 
      this.addMouseListener(new MouseAdapter() {
         public void mousePressed(MouseEvent me) {
            startx = me.getX();
            starty = me.getY();
            stopx = stopy = 0;
            repaint();
         }
 
         public void mouseReleased(MouseEvent me) {
            stopx = me.getX();
            stopy = me.getY();
            currentx = currenty = 0;
            repaint();
            constructFrame(getCroppedImage(image, startx, starty, 
                                           stopx-startx, stopy-starty));
         }
      });
 
      this.addMouseMotionListener(new MouseMotionAdapter() {
         public void mouseDragged(MouseEvent me) {
            currentx = me.getX();
            currenty = me.getY();
            repaint();
         }
      });
   } 
  
   public void constructFrame(final Image img) {
      JFrame frame = new JFrame() {
         public void paint(Graphics g) {
            g.drawImage(img, 0, 15, null);
         }
      };
      frame.setSize(img.getWidth(null), img.getHeight(null));
      frame.setVisible(true);
      frame.invalidate();
   }
 
   public void paint(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
 
      g2d.drawImage(image, 0, 0, this);
 
      if (startx != 0 && currentx != 0) {
         g2d.setColor(Color.white);
         BasicStroke bs = new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
                                            5, new float[] {10}, 0);
         g2d.setStroke(bs);
         g2d.drawRect(startx, starty, currentx-startx, currenty-starty);
      }
 
   }
 
   public Image getCroppedImage(Image img, int x, int y, int w, int h) {
      CropImageFilter cif = new CropImageFilter(x, y, w, h);
      FilteredImageSource fis = new FilteredImageSource(img.getSource(), cif);
      Image croppedImage = getToolkit().createImage(fis);
 
      MediaTracker tracker = new MediaTracker(this);
      tracker.addImage(croppedImage, 0);
      try {
         tracker.waitForID(0);
      } catch (Exception e) { 
         e.printStackTrace(); 
      } 
         
      return croppedImage;
   }
 
   public static void main(String []args) throws Exception {
      Main main = new Main();
      main.setSize(500, 400);
      main.setVisible(true);
   }
}

Differentiating between left, middle, right mouse click

Here’s some sample code.

Main.java:

import javax.swing.event.*;
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);
         }
      });
 
      getContentPane().addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent me) {
            if ((me.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
               System.out.print("Left");
            }
            else if ((me.getModifiers() & InputEvent.BUTTON2_MASK) != 0) {
               System.out.print("Middle");
            }
            else if ((me.getModifiers() & InputEvent.BUTTON3_MASK) != 0) {
               System.out.print("Right");
            }
            System.out.println(" mouse button was clicked!");
         }
      });
   }
  
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}

Using the BorderFactory in Swing

If you have lots of components with borders in your Swing GUI, you could create a Border instance for every component. The BorderFactory class provides a way to share border instances among different components. When using the class for the first time, it creates a number of static borders that it reuses and returns when you call one of the static create methods that the class exposes.

Main.java:

import javax.swing.border.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
 
      JLabel label1 = new JLabel("Label 1");
      label1.setBorder(BorderFactory.createLoweredBevelBorder()); 
 
      // reuse border
      JLabel label2 = new JLabel("Label 2");
      label2.setBorder(BorderFactory.createLoweredBevelBorder()); 
 
      getContentPane().add(label1);
      getContentPane().add(label2);
      
      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);
   } 
} 

Disabling the maximize-icon in a JFrame

First thing you can try is changing the resizable property from the Frame class:

 
import javax.swing.*;
import java.awt.*;
  
public class DisableMax extends JFrame {
 
   public DisableMax() {
      setSize(100, 100);

      setResizable(false);
   }
 
   public static void main(String args[]) {
      new DisableMax().setVisible(true);     
   }
}

However, in this example the maximize icons will still be there. Moreover, the frame will not be resizable anymore (might not be the functionality you want!).
Extend from a JDialog instead and your window will only have the X icon visible.

 
import javax.swing.*;
import java.awt.*;
   
public class DisableMax2 extends JDialog {
 
   public DisableMax2() {
      setSize(100, 100);
 
      setResizable(false);
   }
 
   public static void main(String args[]) {
      new DisableMax2().setVisible(true);     
   }
}

Scrolling a JScrollPane to the bottom programmatically

Call the method scrollRectToVisible of the component that is added to the JScrollPane container as shown in following example:

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() throws Exception {
      getContentPane().setLayout(new BorderLayout());
 
      final JPanel panel = createPanel(); 
      final JScrollPane scrollpane = new JScrollPane(panel);
 
      JButton button = new JButton("Scroll to bottom!");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            panel.scrollRectToVisible(
              new Rectangle(0, panel.getHeight()-1, 1, 1));
         }
      });
 
      getContentPane().add(BorderLayout.NORTH, button);
      getContentPane().add(BorderLayout.CENTER, scrollpane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static JPanel createPanel() throws Exception {
      JPanel panel = new JPanel();
      panel.setLayout(new GridLayout(50, 20, 10, 10));
 
      for (int i=0; i<50; i++) {
         for (int j=0; j<20; j++) {
            JLabel label = new JLabel("label " + i + ", " + j);
            panel.add(label);    
         }
      }
 
      return panel;
   }
 
   public static void main(String [] args) throws Exception  {
      Main main = new Main();
      main.setSize(600, 600);
      main.setVisible(true);
   } 
} 

Programmatically selecting a tab of a JTabbedPane

Use the method setSelectedIndex and pass it the index of the tab that you want to be selected. Here’s an example:

import java.awt.event.*;
import javax.swing.*;
import java.util.*;
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("Select tab");
      JMenuItem menuItem2 = new JMenuItem("Random tab");
      menuItem2.addActionListener(this);
      menu2.add(menuItem2);
      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("Random tab")) {
         selectRandomTab();
      }
   }
 
   protected void createTab() {
      ntabs++;
      tabbedPane.addTab("Tab #" + ntabs, new JLabel("Tab #" + ntabs));
   }
 
   protected void selectRandomTab() {
      Random r = new Random();
      int tabToSelect = r.nextInt(ntabs);
      tabbedPane.setSelectedIndex(tabToSelect);
   }
  
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Creating a JToolBar with a drop-down menu as one of the items

Main.java:

import javax.swing.border.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
  
public class Main extends JFrame {
   public Main() {
      super("JToolBar example");
 
      try {
         UIManager.setLookAndFeel(
   	    "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
      }
      catch(Exception e) { }
 
      final JTextArea textArea = new JTextArea(5, 30);
      JToolBar toolBar = new JToolBar();
      toolBar.setLayout(new FlowLayout(FlowLayout.LEFT));
 
      JButton actionButton = new JButton("Back", new ImageIcon("backdis.gif"));
      actionButton.setRolloverIcon(new ImageIcon("backen.gif"));
      actionButton.setRolloverEnabled(true);
 
      JPopupMenu popupMenu = new JPopupMenu();
      popupMenu.add("JToolBar (Java 2 Platform SE v1.4.0)");
      popupMenu.add("Overview (Java 2 Platform SE v1.4.0)");
      popupMenu.add("Google");
 
      DropDownButton dropDownButton = new DropDownButton(actionButton, popupMenu);
 
      toolBar.add(dropDownButton);
      toolBar.add(new JButton("Forward"));
      toolBar.add(new JButton("Stop"));
      toolBar.add(new JButton("Home"));
      toolBar.setRollover(true);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.NORTH, toolBar);
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(textArea));
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}
 
class DropDownButton extends AbstractButton
{
   JButton actionButton;
   JToggleButton menuButton;
   JPopupMenu popupMenu;
 
   public DropDownButton(JButton _actionButton, JPopupMenu _popupMenu) {
      this.popupMenu = _popupMenu;
      this.actionButton = _actionButton;
 
      setLayout(new BorderLayout());
      actionButton.setBorderPainted(false);
      add(BorderLayout.CENTER, actionButton);
      menuButton = new JToggleButton(new ImageIcon("down.jpg"));
      menuButton.setPreferredSize(new Dimension(15, 10));
      add(BorderLayout.EAST, menuButton);
      menuButton.setBorderPainted(false);
  
      MouseAdapter ma = new MouseAdapter() {
         public void mouseClicked(MouseEvent me) { }
         public void mousePressed(MouseEvent me) { 
            if (me.getSource() == actionButton) {
               menuButton.setSelected(true);
            }
         }
         public void mouseReleased(MouseEvent me) {
            if (me.getSource() == actionButton) {
               menuButton.setSelected(false);
            }
         }
         public void mouseEntered(MouseEvent me) { 
            setRolloverBorder(); 
         }
         public void mouseExited(MouseEvent me) { 
            unsetRolloverBorder();
         }
      };
 
      actionButton.addMouseListener(ma);
      menuButton.addMouseListener(ma);
 
      menuButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            popupMenu.show(actionButton, 0, actionButton.getSize().height);
         }
      });
   }  
 
   protected void setRolloverBorder() {
      actionButton.setBorderPainted(true);
      menuButton.setBorderPainted(true);
   }
 
   protected void unsetRolloverBorder() {
      actionButton.setBorderPainted(false);
      menuButton.setBorderPainted(false);
   }
}

Images used:

backdis.gif:
backen.gif:
down.jpg:

Capturing a close event on a JInternalFrame

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.util.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame {
   JDesktopPane desktop;
   int nframes = 0;
  
   public Main() {
      desktop = new JDesktopPane(); 
      setContentPane(desktop);
      setJMenuBar(createMenuBar());
      createInternalFrame(); 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   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;
      MyJInternalFrame frame = new MyJInternalFrame(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) {}
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(500, 300);
      main.setVisible(true);
   }
} 
 
class MyJInternalFrame extends JInternalFrame 
                       implements VetoableChangeListener { 
   public MyJInternalFrame(String title, boolean resizable, 
                           boolean closable, boolean maximizable, 
                           boolean iconifiable) { 
      super(title, resizable, closable, maximizable, iconifiable); 
      addVetoableChangeListener(this); 
   } 
 
   public void vetoableChange(PropertyChangeEvent pce) 
                                 throws PropertyVetoException { 
      if (pce.getPropertyName().equals(IS_CLOSED_PROPERTY)) { 
         boolean changed = ((Boolean) pce.getNewValue()).booleanValue(); 
         if (changed) { 
            int option = JOptionPane.showOptionDialog(this, "Close " + 
                                                       getTitle() + "?", 
                                                       "Close Confirmation", 
                                                       JOptionPane.YES_NO_OPTION, 
                                                       JOptionPane.QUESTION_MESSAGE, 
                                                       null, null, null); 
            if (option != JOptionPane.YES_OPTION) { 
               throw new PropertyVetoException("Cancelled",null); 
            } 
         } 
      } 
   }
}