Drawing a texture-filled text in Swing

Result:

Texture:

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;
       
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                           RenderingHints.VALUE_ANTIALIAS_ON);
 
      Font font = new Font("Serif", Font.PLAIN, 140);
      g2d.setFont(font);
 
      Rectangle2D tr = new Rectangle2D.Double(0, 0, image.getWidth(), image.getHeight());
      TexturePaint tp = new TexturePaint(image, tr);
      g2d.setPaint(tp);
      g2d.drawString("Alicia", 30, 150);
   }
 
   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(410, 180);
      main.setVisible(true);
   }
}

Drawing anti-aliased text in Swing

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private boolean antiAliasing = false;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      final JCheckBox cb = new JCheckBox("Anti-aliased");
      cb.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            antiAliasing = cb.isSelected();
            repaint();
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.NORTH, cb);
   }
 
   public void paint(Graphics g) {
      super.paint(g);
 
      Graphics2D g2d = (Graphics2D) g;
       
      if (antiAliasing) {
         g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                              RenderingHints.VALUE_ANTIALIAS_ON);
      }
 
      Font font = new Font("Serif", Font.PLAIN, 140);
      g2d.setFont(font);
 
      g2d.drawString("W", 60, 150);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}

Zero out all pixels of a RGB band in Swing

Use the class LookupOp and pass it an array of arrays, each representing the change in band. In this example, the G(reen) and B(lue) band don’t change while the R(ed) value is made zero for all intensities.

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);
 
         byte[][] intensity = new byte[3][256];
         for(int i=0; i<256; i++) {
            intensity[0][i] = 0;
            intensity[1][i] = (byte) i;
            intensity[2][i] = (byte) i;
         }
  
         ByteLookupTable blt = new ByteLookupTable(0, intensity);
         LookupOp op = new LookupOp(blt, 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);
   }
}

Image used:

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

Moving the mouse cursor programatically

From JDK1.3, you can use the robot class, very useful for testing purposes.
Following example shows you how to take a desktop screenshot (0,0) –> (200,200)
as well as manipulating the mouse cursor. The cursor will traverse diagonally
from the top left corner to the bottom right.

import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() throws Exception {
      Robot robot = new Robot();
      BufferedImage image = robot.createScreenCapture(new Rectangle(0, 0, 200, 200));
      getContentPane().add(new JLabel(new ImageIcon(image)));
      //setSize(200, 200);
      pack();
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public void animateMouse() throws Exception {
      Robot robot = new Robot();
 
      double w = getSize().getWidth();
      double h = getSize().getHeight();
 
      double x1=0, y1=0;
      double dx = w/h;
      double dy = h/w;
      if (dx > dy) dx = 1; else dy = 1;
      do {
         robot.mouseMove((int) x1, (int) y1);
         x1 += dx;
         y1 += dy;
 
         try { Thread.sleep(10); } catch(InterruptedException e) { }
      } while (x1 < w || y1 < h);
   }
 
   public static void main(String args[]) throws Exception {
      Main main = new Main();
      main.show();
      main.animateMouse();
   }
}

Retrieving the links in an HTML document in Java

You can use the HTMLEditorKit that includes an HTML parser. Have it parse your HTML and then enumerate the href attribute of all the “A” tags:

import javax.swing.text.html.*;
import javax.swing.text.*;
import java.util.*;
import java.net.*;
import java.io.*;
     
public class Main
{ 
   public static void main(String[] args) throws Exception {
      Vector v = getLinks(new URL("http://www.google.com"));
 
      for (int i=0; i<v.size(); i++) {
         System.out.println(v.elementAt(i));
      }
 
      System.exit(0);
   }
 
   public static Vector getLinks(URL url) throws Exception {
      Vector v = new Vector();
 
      URLConnection conn = url.openConnection();
      Reader r = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      HTMLEditorKit editorKit = new HTMLEditorKit();
      Document doc = editorKit.createDefaultDocument();
 
      // The Document class does not yet handle charset's properly.
      doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
 
      try {
         editorKit.read(r, doc, 0);
 
         // loop through the HTML A tag elements 
         ElementIterator it = new ElementIterator(doc);
         Element elem;
         while ((elem = it.next()) != null) {
            SimpleAttributeSet s = (SimpleAttributeSet) elem.getAttributes().getAttribute(HTML.Tag.A);
            if (s != null) {
               v.addElement(s.getAttribute(HTML.Attribute.HREF));
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
 
      return v;
   }
}

Getting the HWND handle of a Window

Sometimes, you need the HWND handle for example to pass it on with JNI to a
native function. See related links, where the mousewheel support is implemented
using this method.
This example shows you how to get the handle of a window as well as a Canvas.
HwndCanvas:

import java.awt.*;
import sun.awt.*;
 
public class HwndCanvas extends Canvas
{
   public int getHwnd() {
      int hwnd = 0;
                            
      DrawingSurfaceInfo w = ((DrawingSurface)(getPeer())).getDrawingSurfaceInfo();
                               
      if (w != null) {
         w.lock();
         Win32DrawingSurface win32 = (Win32DrawingSurface) w.getSurface();
         hwnd = win32.getHWnd();
         w.unlock();
      }
       
      return hwnd;
   }                    
}

Main.java:

import java.awt.event.*;
import java.awt.*;
import sun.awt.*;
 
public class Main extends Frame
{
   public HwndCanvas hwndCanvas = new HwndCanvas();
 
   public Main() {
      setLayout(new BorderLayout());
      add(BorderLayout.CENTER, hwndCanvas);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });      
 
      setSize(100, 100);
   }
 
   public int getHwnd() { 
      int hwnd = 0;
                            
      DrawingSurfaceInfo w = ((DrawingSurface)(getPeer())).getDrawingSurfaceInfo();
                               
      if (w != null) {
         w.lock();
         Win32DrawingSurface win32 = (Win32DrawingSurface) w.getSurface();
         hwnd = win32.getHWnd();
         w.unlock();
      }
      
      return hwnd;
   } 
 
   public static void main(String []args) {
      Main m = new Main();
 
      m.show();
 
      System.out.println("HWND of Frame = " + m.getHwnd());
      System.out.println("HWND of Canvas = " + m.hwndCanvas.getHwnd());
   }
}

Force the scrollbars to be there even when they’re not needed

   int hPolicy = JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS;
   int vPolicy = JScrollPane.VERTICAL_SCROLLBAR_ALWAYS;
 
   JPanel drawSurface = new JPanel();
   JScrollPane editorField;

= = = = = = = = = = = = =
(in constructor….)

   editorField = new JScrollPane(drawSurface);
   editorField.setHorizontalScrollBarPolicy(hPolicy);
   editorField.setVerticalScrollBarPolicy(vPolicy);

= = = = = = = = = = = = = = = = = = = = =
in essence all you need to do is set the individual scroll
bar policies to the constants defined in JScrollPane.

Changing the color of the selected tab of a JTabbedPane


With UIManager.put, change the “TabbedPane.selected” property to the desired color as shown in following example.

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());
 
      UIManager.put("TabbedPane.selected", Color.red);
 
      tabbedPane = new JTabbedPane();
      createTab();
 
      getContentPane().add(BorderLayout.CENTER, tabbedPane);
      setJMenuBar(createMenuBar());
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      setTitle("JTabbedPane Selected Color 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);
      menuBar.add(menu1);
 
      return menuBar;
   }
 
   public void actionPerformed(ActionEvent e) {
      if (e.getActionCommand().equals("Create new tab")) {
         createTab();
      }
   }
  
   protected void createTab() {
      ntabs++;
      tabbedPane.addTab("Tab #" + ntabs, new JLabel("Tab #" + ntabs));
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Perform outline-dragging with JInternalFrame

Outline dragging is a JDesktopPane client property that provides the user with a outline rectangle when JInternalFrames are dragged instead of displaying the full contents of the JInternalFrame, making dragging internal frames a lot more performant. To perform outline dragging, set the property JDesktopPane.dragMode to outline. Swing 1.1.1 had added fast implementation for fast dragging. Put the client property to “faster”.
Here’s an example:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame implements ActionListener {
   JDesktopPane desktop;
   int nframes = 0;
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
      desktop = new JDesktopPane(); 
      createInternalFrame();
      getContentPane().add(BorderLayout.CENTER, desktop);
      setJMenuBar(createMenuBar());
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   
      setTitle(&quot;Outline Dragging Demonstration&quot;);
      setSize(new Dimension(400, 400));
   }
 
   protected JMenuBar createMenuBar() {
      JMenuBar menuBar = new JMenuBar();

      JMenu menu = new JMenu(&quot;JDesktopPane&quot;);
      JMenuItem menuItem1 = new JMenuItem(&quot;Create new JInternalFrame&quot;);
      menuItem1.addActionListener(this);
      menu.add(menuItem1);
      menu.add(new JSeparator());
      JMenuItem menuItem2 = new JMenuItem(&quot;Outline dragging normal&quot;);
      menuItem2.addActionListener(this);
      menu.add(menuItem2);
      JMenuItem menuItem3 = new JMenuItem(&quot;Outline dragging on&quot;);
      menuItem3.addActionListener(this);
      menu.add(menuItem3);
      JMenuItem menuItem4 = new JMenuItem(&quot;Fast dragging&quot;);
      menuItem4.addActionListener(this);
      menu.add(menuItem4);
      menuBar.add(menu);

      return menuBar;
   }
 
   public void actionPerformed(ActionEvent e) {
      if (e.getActionCommand().equals(&quot;Create new JInternalFrame&quot;)) {
         createInternalFrame();
      }
      else if (e.getActionCommand().equals(&quot;Outline dragging normal&quot;)) {
         desktop.putClientProperty(&quot;JDesktopPane.dragMode&quot;, &quot;normal&quot;);
      }
      else if (e.getActionCommand().equals(&quot;Outline dragging on&quot;)) {
         // Make dragging faster
         desktop.putClientProperty(&quot;JDesktopPane.dragMode&quot;, &quot;outline&quot;);
      }
      else if (e.getActionCommand().equals(&quot;Fast dragging&quot;)) {
         desktop.putClientProperty(&quot;JDesktopPane.dragMode&quot;, &quot;faster&quot;);
      }
   }
 
   protected void createInternalFrame() {
      JInternalFrame frame = new JInternalFrame(&quot;InternalFrame&quot;, 
         true,    // resizable
         true,    // closable
         true,    // maximizable
         true);   // iconifiable
      frame.setVisible(true); 
      desktop.add(frame);
      frame.setSize(200, 200);
      frame.setLocation(30*nframes, 30*nframes);
      nframes++;
      try {
         frame.setSelected(true);
      } catch (java.beans.PropertyVetoException e) {}
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Overlapping swing components

MainFrame.java:

import  java.awt.FlowLayout;
import  java.awt.Dimension;
import  javax.swing.*;
 
public class MainFrame
{
   public static void main (String[] args) {
      //Window-Frame
      JFrame frame       = new JFrame ( "Test LayeredPane" );
 
      //cast the JContentPane to JPanel
      JPanel contentPane = (JPanel) frame.getContentPane ();
 
      //the panel that is on top
      JPanel topPanel    = new JPanel ( new FlowLayout () );
 
      frame.setSize(new Dimension(305, 115));
 
      //add Components to the topPanel
      topPanel.add ( new JLabel( "This is a JLabel" ) );
      topPanel.add ( new JTextField ( "This is a JTextField" ) );
 
      //setOpaque(false) sets the Panels transparent
      topPanel.setOpaque    ( false );
      contentPane.setOpaque ( false );
 
      //add the topPanel to the frames contentPane
      contentPane.add ( topPanel );
 
      //Select an ImageIcon to use as Background-Image
      ImageIcon bgimage = new ImageIcon ( "O:\undecon1.gif" );
 
      //get the ScreenSize
      Dimension screendim = frame.getToolkit ().getScreenSize ();
      double xfaktor = screendim.getWidth  () / bgimage.getIconWidth ();
      double yfaktor = screendim.getHeight () / bgimage.getIconHeight ();
 
      //background-panel
      JPanel bgpanel = new JPanel ( null );
      JLabel bglabel = null;
 
      //add as much labels with the selected imageIcon that the panel fits
      //the full screen (needed when frame is resized)
      for ( int x = 0; x <= xfaktor; x++ ) {
         for ( int y = 0; y <= yfaktor; y++ ) {
            bglabel = new JLabel ( bgimage );
            bgpanel.add ( bglabel );
            bglabel.setBounds ( x * bgimage.getIconWidth  (),
                                y * bgimage.getIconHeight (),
                                bgimage.getIconWidth  (),
                                bgimage.getIconHeight () );
         }
      }
 
      //set the background panel's size to screenSize
      bgpanel.setBounds ( 0, 0, (int)screendim.getWidth(), (int)screendim.getHeight() );
 
      //get the frame's layeredPane and add the background panel
      JLayeredPane layeredPane = frame.getLayeredPane ();
      layeredPane.add ( bgpanel, new Integer ( Integer.MIN_VALUE ) );
 
      //display frame
      frame.setVisible(true);
   }
}