Have a Swing Dialog always-on-top

+Please bear in mind that this freeware solution is licensed under the
+GNU General Public License. You must read, accept and enact *all*
+terms of this license in order to use it free of charge.

An excellent class has been written by Mitch Goldstein (Author of HARDCORE JFC) that uses JNI to perform this Windows-specific task.

You can download it here: WInterface.zip

Drawing an oval in Swing

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);
         }
      });
   }
 
   public void paint(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
  
      g2d.drawOval(10, 10, getSize().width-20, getSize().height-20);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(100, 100);
      main.setVisible(true);
   }
}

Drawing a string in a certain font in Swing

Use the method drawString that accepts the String and the x and y parameter. Be aware that the x and y coordinates refer to the baseline, so from the bottom up. If you prefer working from the top down, you can get the font ascent (from the API: the distance between the font’s baseline and the top of most alphanumerical characters) and add it to the y coordinate:

   FontMetrics fm = g2d.getFontMetrics();
   g2d.drawString("GOD'S", 20, 100+fm.getAscent());

Main.java:

import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private Image image;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      }); 
   }
 
   public void paint(Graphics g) {
      g.setColor(Color.black);
      g.fillRect(0, 0, getSize().width, getSize().height);
 
      Graphics2D g2d = (Graphics2D) g;
      Font f = new Font("Courier New", Font.BOLD, 40);
      g2d.setFont(f);
 
      g2d.setColor(Color.white);
 
      g2d.drawString("Small", 20, 60);
      g2d.drawString("and", 20, 110);
      g2d.drawString("Humble", 20, 160);  
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(180, 200);
      main.setVisible(true);
   }
}

Drawing a texture-filled shape 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("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
      Ellipse2D e = new Ellipse2D.Float(20, 50, 80, 120);
      g2d.setPaint(tp);
      g2d.fill(e);
 
      // draw texture filled ellipse, but with antialiasing
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                           RenderingHints.VALUE_ANTIALIAS_ON);
      e = new Ellipse2D.Float(140, 50, 80, 120);
      g2d.setPaint(tp);
      g2d.fill(e);
 
      // draw dashed rectangle with thickness 5
      BasicStroke bs = new BasicStroke(5, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
                           10, new float[] {10}, 0);
      g2d.setStroke(bs);
      g2d.drawRect(260, 50, 80, 120);
 
      // draw filled rectangle with rescaled texture image
      tr = new Rectangle2D.Double(0, 0, image.getWidth()/4, image.getHeight()/4);
      tp = new TexturePaint(image, tr);
      g2d.setPaint(tp);
      g2d.fillRect(380, 50, 80, 120);
   }
 
   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(480, 200);
      main.setVisible(true);
   }
}

Image used:

Shearing an image

Shearing is performing an operation on the image in which the parallel lines will remain parallel while opposite corners are pulled apart (one or two dimensions).

Main.java:

import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private Image image;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      image = Toolkit.getDefaultToolkit().getImage("c:\djkrush.jpg");
      waitForImage(image);
      image = shearImage(image, 1, 0);
      setSize(image.getWidth(null), image.getHeight(null));
   }
 
   public void paint(Graphics g) {
      g.drawImage(image, 0, 0, this);
   }
 
   public void waitForImage(Image image) {
      MediaTracker mt = new MediaTracker(this);
 
      int id = 0;
      mt.addImage(image, id);
 
      try {
         mt.waitForID(id);
      }
      catch(InterruptedException e) {
         System.out.println("Image loading interrupted : " + e);
      }
   }
 
   public Image shearImage(Image image, double shearx, double sheary) {
      BufferedImage bi = toBufferedImage(image);
 
      AffineTransformOp op = new AffineTransformOp(
                   AffineTransform.getShearInstance(shearx, sheary), null); 
 
      return op.filter(bi, null); 
   }
 
   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.setVisible(true);
   }
}

Image used:

Detecting a triple-click in Swing

Use the method getClickCount() as shown in following example.

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.getClickCount() == 3) {
               System.out.println("Button was clicked 3 times!");
            }
         }
      });
   }
  
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}

Detecting what version of Swing is installed

One way to find out is to look at the UIDefaults key/value pairs to see what new keys have been introduced in what version.

Here’s an example, test it thouroughly. If anyone knows a better way, comment it here!

GetSwingVersion.java:

import java.lang.reflect.*;
import java.util.*;
 
public class GetSwingVersion
{
   public static void main(String []args) {
      boolean found = false;
 
      try {
         Class.forName("javax.swing.JButton");
 
         Class manager = Class.forName("javax.swing.UIManager");
         try {
            Method m = manager.getDeclaredMethod("getDefaults", new Class[] { });
            Object defaults = m.invoke(null, new Object[] { });
 
            Method qd = defaults.getClass().getMethod("getString", new Class[] { Object.class });
            Object str = qd.invoke(defaults, new Object[] { "FormattedTextFieldUI" });
            if (str != null) {
               System.out.println("Swing version 1.1.1 JDK1.4 found!");
            }
            else {
               Object str2 = qd.invoke(defaults, new Object[] { "RootPaneUI" });
               if (str2 != null) {
                  System.out.println("Swing version 1.1.1 JDK1.3 found!");
               }
               else {
                  System.out.println("Swing version 1.1.1 JDK1.2.2 found!");
               }
            }
         }
         catch(NoSuchMethodException e) {
         }
         catch(IllegalAccessException e) {
         }
         catch(InvocationTargetException e) {
         }
  
         found = true;
      }
      catch(NoClassDefFoundError e) {
      }
      catch(ClassNotFoundException e) {
      }
 
      if (!found) {  
         try {
            Class.forName("com.sun.java.swing.JButton");
            System.out.println("Swing v1.0.3 found!");
            found = true;
         } 
         catch(NoClassDefFoundError e) {
         }
         catch(ClassNotFoundException e) {
         }
      }   
 
      if (!found) {
         System.out.println("no version of Swing found!");
      }
 
      System.exit(1);
   }
}

Setting the top-left icon in a JFrame

setIconImage (inherited method from java.awt.Frame) does the job!

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

      setIconImage(new ImageIcon("test.gif").getImage());
   }
 
   public static void main(String args[]) {
      new IconFrame().setVisible(true);     
   }
}

Making the scrolling in JScrollPane faster

A new feature has been implemented in Swing 1.1.1 that makes scrolling faster in most cases. The idea is to only update the exposed viewport (the visible region) when scrolling. To enable this, set the property EnableWindowBlit to true.

   scrollpane.getViewport().putClientProperty("EnableWindowBlit", Boolean.TRUE);

Placing an image in a tab of a JTabbedPane

Look at the addTab possibilities in the Javadoc documentation!

Main.java:

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("TrafficGreen.gif");
      createTab("TrafficRed.gif");
 
      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("Change orientation");
      JMenuItem menuItem1 = new JMenuItem("TOP");
      menuItem1.addActionListener(this);
      menu1.add(menuItem1);
      JMenuItem menuItem2 = new JMenuItem("BOTTOM");
      menuItem2.addActionListener(this);
      menu1.add(menuItem2);
      JMenuItem menuItem3 = new JMenuItem("LEFT");
      menuItem3.addActionListener(this);
      menu1.add(menuItem3);
      JMenuItem menuItem4 = new JMenuItem("RIGHT");
      menuItem4.addActionListener(this);
      menu1.add(menuItem4);
      menuBar.add(menu1);
 
      return menuBar;
   }
  
   public void actionPerformed(ActionEvent e) {
      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(String imagefile) {
      ntabs++;
      tabbedPane.addTab("Tab #" + ntabs, new ImageIcon(imagefile), new JLabel("Tab #" + ntabs));
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Images used: