Getting the HWND handle of a Canvas

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.java:

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

Drawing a rounded rectangle in Swing

Use the method drawRoundRect that accepts (x, y) coordinates (top-left), the width and size, and the width and height of the arc.

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.drawRoundRect(10, 50, 150, 150, 50, 30);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}

Different types of join styles 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.drawString("JOIN_BEVEL", 20, 35); 
      g2d.setStroke(new BasicStroke(15f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
      g2d.drawRect(20, 50, 80, 80);
 
      g2d.drawString("JOIN_MITER", 140, 35); 
      g2d.setStroke(new BasicStroke(15f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
      g2d.drawRect(140, 50, 80, 80);       
 
      g2d.drawString("JOIN_ROUND", 260, 35); 
      g2d.setStroke(new BasicStroke(15f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
      g2d.drawRect(260, 50, 80, 80);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(360, 160);
      main.setVisible(true);
   }
}

Drawing a gradient filled rectangle 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.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                           RenderingHints.VALUE_ANTIALIAS_ON);
 
      GradientPaint gp = new GradientPaint(20, 50, Color.orange, 
                                           100, 130, Color.red, true);
      g2d.setPaint(gp);
      g2d.fillRect(20, 50, 80, 80);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(120, 180);
      main.setVisible(true);
   }
}

Drawing a rotated image

Work directly on the class Graphics2D or use the class AffineTransform that allows you to create your own transformation matrixes.

Directly on Graphics2D

Main.java:

import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private Image image;
   private boolean firstTime = true;
   private int degrees = 0;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      image = Toolkit.getDefaultToolkit().getImage("c:\djkrush.jpg");
      waitForImage(image);
 
      getContentPane().setLayout(new BorderLayout());
      JButton button = new JButton("rotate by 10 degrees");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            degrees += 10;
            repaint();
         }
      });
 
      getContentPane().add(BorderLayout.SOUTH, button);
   }
 
   public void paint(Graphics g) {
      super.paint(g);
 
      Graphics2D g2d = (Graphics2D) g;
 
      double radians = degrees * (Math.PI / 180);
      g2d.translate(getSize().width/2, getSize().height/2);
      g2d.rotate(radians); 
      g2d.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 static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Using AffineTransform

Main.java:

import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private Image image;
   private boolean firstTime = true;
   private int degrees = 0;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      image = Toolkit.getDefaultToolkit().getImage("c:\djkrush.jpg");
      waitForImage(image);
 
      getContentPane().setLayout(new BorderLayout());
      JButton button = new JButton("rotate by 10 degrees");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            degrees += 10;
            repaint();
         }
      });
 
      getContentPane().add(BorderLayout.SOUTH, button);
   }
 
   public void paint(Graphics g) {
      super.paint(g);
 
      if (degrees == 0) {
         g.drawImage(image, getSize().width/2, getSize().height/2, this);
      }
      else {  
         Graphics2D g2d = (Graphics2D) g;
 
         double radians = degrees * (Math.PI / 180);
         AffineTransform at = new AffineTransform();
         at.translate(getSize().width/2, getSize().height/2);
         at.rotate(radians);
         g2d.drawImage(image, at, 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 static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

image used:

Make the speaker beep in Java

The first example simply beeps the speaker through an ASCII code:

public class Main {
   public static void main(String args[]) {
      System.out.print("7");
      System.out.flush();
   }
}

The second example makes use of the AWT Toolkit’s method beep. Note that even though we only use the AWT to make a beep, it automatically creates a non-daemon thread that keeps the program alive when it reaches the end of the main method. This is why there is a call to System.exit.

import java.awt.*;
 
public class beep {
   public static void main(String args[]) {
      Toolkit.getDefaultToolkit().beep();     
      System.exit(1);
   }
}

Creating an auto-complete JComboBox

Main.java:

import javax.swing.plaf.basic.*;
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().setLayout(new FlowLayout(FlowLayout.LEFT));
 
      String[] elements = new String[] { "arthur", "brian", "chet", "danny", "dave",  
                                         "don", "edmond", "eddy", "glen", "gregory", "john",
                                         "ken", "malcolm", "pete", "stephanie", "yvonne" };
 
      JComboBox comboBox = new AutoCompleteComboBox(elements);
      getContentPane().add(comboBox);
   }
      
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}
 
class AutoCompleteComboBox extends JComboBox
{
   public int caretPos=0;
   public JTextField inputField=null;
 
   public AutoCompleteComboBox(final Object elements[]) {
      super(elements);
      setEditor(new BasicComboBoxEditor());
      setEditable(true);
   }
 
   public void setSelectedIndex(int index) {
      super.setSelectedIndex(index);
 
      inputField.setText(getItemAt(index).toString());
      inputField.setSelectionEnd(caretPos + tf.getText().length());
      inputField.moveCaretPosition(caretPos);
   }
 
   public void setEditor(ComboBoxEditor editor) {
      super.setEditor(editor);
      if (editor.getEditorComponent() instanceof JTextField) {
         inputField = (JTextField) editor.getEditorComponent();
 
         inputField.addKeyListener(new KeyAdapter() {
            public void keyReleased( KeyEvent ev ) {
               char key=ev.getKeyChar();
               if (! (Character.isLetterOrDigit(key) || Character.isSpaceChar(key) )) return;
 
               caretPos=inputField.getCaretPosition();
               String text="";
               try {
                  text=inputField.getText(0, caretPos);
               }
               catch (javax.swing.text.BadLocationException e) {
                  e.printStackTrace();
               }
 
               for (int i=0; i<getItemCount(); i++) {
                  String element = (String) getItemAt(i);
                  if (element.startsWith(text)) {
                     setSelectedIndex(i);
                     return;
                  }
               }
            }
         });
      }
   }
}

Have a JDialog 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

Adding a JPanel with a null layout to a JScrollPane

Make sure you set the preferredSize of the JPanel. Invoke the method setViewportView on JScrollPane.

Main.java:

import java.awt.event.*;
import javax.swing.border.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      JPanel panel = createContactPanel();
 
      JScrollPane sp = new JScrollPane();
      sp.setViewportView(panel);
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(sp, BorderLayout.CENTER); 
   }
 
   public JPanel createContactPanel() {
      JLabel titleLbl      = new JLabel("Title");
      JLabel firstNameLbl  = new JLabel("First name");
      JLabel lastNameLbl   = new JLabel("Last name");
      JLabel addressLbl    = new JLabel("Address");
      JLabel cityLbl       = new JLabel("City");
      JLabel zipLbl        = new JLabel("Postal code");
      JLabel countryLbl    = new JLabel("Country");
      JLabel phoneLbl      = new JLabel("Phone number");
      JLabel faxLbl        = new JLabel("Fax number");
      JLabel emailLbl      = new JLabel("E-mail");
      JLabel birthdayLbl   = new JLabel("Birthdate");
      JLabel pickchoiceLbl = new JLabel("Pick a choice");
      JLabel creditCardTypeLbl     = new JLabel("Credit card type");
      JLabel creditCardNumberLbl   = new JLabel("Credit card number");
      JLabel expirationLbl         = new JLabel("Expiration date");
 
      JComboBox titleCombo = new JComboBox(
             new String[] { "-", "Mr", "Mrs", "Miss" });
      JTextField firstNameTf    = new JTextField();
      JTextField lastNameTf     = new JTextField();
      JTextField address1Tf     = new JTextField();
      JTextField address2Tf     = new JTextField();
      JTextField cityTf         = new JTextField();
      JTextField zipTf          = new JTextField();
      JTextField countryTf      = new JTextField();
      JTextField phoneTf        = new JTextField();
      JTextField faxTf          = new JTextField();
      JTextField emailTf        = new JTextField();
      JComboBox bd1Combo = new JComboBox();
      for (int i=1; i<=12; i++) bd1Combo.addItem(""+i);
      JComboBox bd2Combo = new JComboBox();
      for (int i=1; i<=31; i++) bd2Combo.addItem(""+i);
      JComboBox bd3Combo = new JComboBox();
      for (int i=1900; i<2000; i++) bd3Combo.addItem(""+i);
      JComboBox referCombo = new JComboBox();
      referCombo.addItem("Friend");
      referCombo.addItem("Search engine");
      referCombo.addItem("Print Media");
      referCombo.addItem("Banner Add");
      referCombo.addItem("Other");
      JComboBox creditCardTypeCombo = new JComboBox();
      creditCardTypeCombo.addItem("VISA");
      creditCardTypeCombo.addItem("MasterCard");
      creditCardTypeCombo.addItem("American Express");
      JTextField creditCardNumberTf = new JTextField();
      JComboBox expiration1Combo = new JComboBox();
      for (int i=1; i<=12; i++) expiration1Combo.addItem(""+i);
      JComboBox expiration2Combo = new JComboBox();
      for (int i=1; i<=31; i++) expiration2Combo.addItem(""+i);
      JComboBox expiration3Combo = new JComboBox();
      for (int i=1900; i<=2000; i++) expiration3Combo.addItem(""+i);
 
      JPanel panelGeneral = new JPanel();
      panelGeneral.setLayout(null);
      panelGeneral.add(titleLbl);
      panelGeneral.setBorder(new TitledBorder("General Information"));
      titleLbl.setBounds(20, 20, 150, 20);
      panelGeneral.add(firstNameLbl);
      firstNameLbl.setBounds(20, 50, 150, 20);
      panelGeneral.add(lastNameLbl);
      lastNameLbl.setBounds(20, 80, 150, 20);
      panelGeneral.add(addressLbl);
      addressLbl.setBounds(20, 110, 150, 20);
      panelGeneral.add(cityLbl);
      cityLbl.setBounds(20, 170, 150, 20);
      panelGeneral.add(zipLbl);
      zipLbl.setBounds(20, 200, 150, 20);
      panelGeneral.add(countryLbl);
      countryLbl.setBounds(20, 230, 150, 20);
      panelGeneral.add(phoneLbl);
      phoneLbl.setBounds(20, 260, 150, 20);
      panelGeneral.add(faxLbl);
      faxLbl.setBounds(20, 290, 150, 20);
      panelGeneral.add(emailLbl);
      emailLbl.setBounds(20, 320, 150, 20);
      panelGeneral.add(birthdayLbl);
      birthdayLbl.setBounds(20, 350, 150, 20); 
      panelGeneral.add(titleCombo);
      titleCombo.setBounds(150, 20, 60, 20);
      panelGeneral.add(firstNameTf);
      firstNameTf.setBounds(150, 50, 200, 20);
      panelGeneral.add(lastNameTf);
      lastNameTf.setBounds(150, 80, 200, 20);
      panelGeneral.add(address1Tf);
      address1Tf.setBounds(150, 110, 200, 20);  
      panelGeneral.add(address2Tf);
      address2Tf.setBounds(150, 140, 200, 20);  
      panelGeneral.add(cityTf);
      cityTf.setBounds(150, 170, 200, 20);
      panelGeneral.add(zipTf);
      zipTf.setBounds(150, 200, 200, 20);
      panelGeneral.add(countryTf);
      countryTf.setBounds(150, 230, 200, 20);
      panelGeneral.add(phoneTf);
      phoneTf.setBounds(150, 260, 200, 20);
      panelGeneral.add(faxTf);
      faxTf.setBounds(150, 290, 200, 20);
      panelGeneral.add(emailTf);
      emailTf.setBounds(150, 320, 200, 20);
      panelGeneral.add(bd1Combo);
      bd1Combo.setBounds(150, 350, 60, 20);
      panelGeneral.add(bd2Combo);
      bd2Combo.setBounds(220, 350, 60, 20);
      panelGeneral.add(bd3Combo);
      bd3Combo.setBounds(290, 350, 60, 20);
 
      JPanel panelReferral = new JPanel();
      panelReferral.setLayout(null);
      panelReferral.setBorder(new TitledBorder("Where did you hear about us?"));
      panelReferral.add(pickchoiceLbl);
      pickchoiceLbl.setBounds(20, 20, 150, 20);
      panelReferral.add(referCombo);
      referCombo.setBounds(150, 20, 100, 20);
 
      JPanel panelCreditCard = new JPanel();
      panelCreditCard.setLayout(null);
      panelCreditCard.setBorder(new TitledBorder("Payment method"));
      panelCreditCard.add(creditCardTypeLbl);
      creditCardTypeLbl.setBounds(20, 20, 150, 20);
      panelCreditCard.add(creditCardNumberLbl);
      creditCardNumberLbl.setBounds(20, 50, 150, 20);
      panelCreditCard.add(expirationLbl);
      expirationLbl.setBounds(20, 80, 150, 20);
 
      panelCreditCard.add(creditCardTypeCombo);
      creditCardTypeCombo.setBounds(150, 20, 100, 20);
      panelCreditCard.add(creditCardNumberTf);
      creditCardNumberTf.setBounds(150, 50, 150, 20);
      panelCreditCard.add(expiration2Combo);
      expiration2Combo.setBounds(220, 80, 60, 20);
      panelCreditCard.add(expiration3Combo);
      expiration3Combo.setBounds(290, 80, 60, 20);
 
      JPanel panel = new JPanel();
      panel.setLayout(null);
      panel.add(panelGeneral);
      panelGeneral.setBounds(10, 20, 370, 400);
      panel.add(panelReferral);
      panelReferral.setBounds(10, 430, 370, 50);
      panel.add(panelCreditCard);
      panelCreditCard.setBounds(10, 490, 370, 120);
      
      panel.setPreferredSize(new Dimension(380, 620)); 
 
      return panel;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Creating a nested JTabbedPane

The following example nests JTabbedPanes recursively until 10 levels deep:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.beans.*;
 
public class Main extends JFrame {
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
      JTabbedPane tabbedPane = new JTabbedPane();
 
      getContentPane().add(BorderLayout.CENTER, tabbedPane);
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      setTitle("JTabbedPane Nested Demonstration");
      setSize(new Dimension(400, 400));
 
      createTab(tabbedPane, 0);
   }
 
   protected void createTab(JTabbedPane jtp, int ct) {
      if (ct > 10) return;
      JTabbedPane tp = new JTabbedPane();
      tp.setTabPlacement(getNextOrientation(jtp.getTabPlacement()));
      jtp.addTab("TabLevel #" + ct, tp);
      createTab(tp, ct+1);
   }
 
   private int getNextOrientation(int tabPlacement) {
      if (tabPlacement == JTabbedPane.TOP) return JTabbedPane.RIGHT;
      if (tabPlacement == JTabbedPane.RIGHT) return JTabbedPane.BOTTOM;
      if (tabPlacement == JTabbedPane.BOTTOM) return JTabbedPane.LEFT;
      else return JTabbedPane.TOP;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}