Creating a JFormattedTextField that only accepts dates

Main.java and JFormattedDateTextField:

import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
import java.util.*;
 
public class Main extends JFrame 
{
   public Main() throws Exception
   {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
  
 
      final JFormattedDateTextField formattedTf =
                   new JFormattedDateTextField();
      formattedTf.setValue(new Date()); 
 
      final JTextField normalTf = new JTextField(25);
      JButton button = new JButton("Get value");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) { 
            normalTf.setText(""+formattedTf.getValue());
         }
      });
 
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
      getContentPane().add(formattedTf);
      getContentPane().add(button);
      getContentPane().add(normalTf);
 
      formattedTf.setPreferredSize(normalTf.getPreferredSize());
   }
  
   public static void main(String args[]) throws Exception 
   {
      Main main = new Main();
      main.setSize(300, 150);
      main.setVisible(true);
   }
}
 
class JFormattedDateTextField extends JFormattedTextField {
   Format format = new SimpleDateFormat("MM/dd/yyyy"); 
 
   public JFormattedDateTextField() {
      super();
      MaskFormatter maskFormatter = null;
      try {
         maskFormatter = new MaskFormatter("##/##/####");
      } catch (ParseException e) {
         e.printStackTrace();
      }
 
      maskFormatter.setPlaceholderCharacter('_');
      setFormatterFactory(new DefaultFormatterFactory(maskFormatter));
      this.addFocusListener(new FocusAdapter() {
         public void focusGained(FocusEvent e) {
            if (getFocusLostBehavior() == JFormattedTextField.PERSIST)
               setFocusLostBehavior(JFormattedTextField.COMMIT_OR_REVERT);
            }
  
            public void focusLost(FocusEvent e) {
               try {
                  Date date = (Date) format.parseObject(getText());
                  setValue(format.format(date));
               } catch (ParseException pe) {
                  setFocusLostBehavior(JFormattedTextField.PERSIST);
                  setText("");
                  setValue(null);
               }
            }
      });
   }
 
   public void setValue(Date date) {
      super.setValue(toString(date));
   }
 
   private Date toDate(String sDate) {
      Date date = null;
      if (sDate == null) return null;
      try {
         date = (Date) format.parseObject(sDate);
      }
      catch (ParseException pe) {
         // ignore
      }
 
      return date;
   } 
 
   private String toString(Date date) {
      try {
         return format.format(date);
      } catch (Exception e) {
         return "";
      }
   }
}

Creating a JList with icons and text

Main.java:

import java.awt.image.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
  
public class Main 
{
   public static void main(String args[]) {
      JFrame frame = new JFrame("JList ImageIcon Demonstration");
 
      DefaultListModel dlm = new DefaultListModel();
      dlm.addElement(new ListEntry("Audio", new ImageIcon("audio.gif")));
      dlm.addElement(new ListEntry("Control Panel", new ImageIcon("controlpanel.gif")));
      dlm.addElement(new ListEntry("Folder", new ImageIcon("folder.gif")));
      dlm.addElement(new ListEntry("Local Disk (C:)", new ImageIcon("mycomp.gif")));
      dlm.addElement(new ListEntry("doc on '192.168.0.1' (Z:)", new ImageIcon("network.gif")));
 
      JList list = new JList(dlm);
      list.setCellRenderer(new ListEntryCellRenderer());
         
      frame.getContentPane().add(BorderLayout.CENTER, new JScrollPane(list)); 
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setVisible(true);
   }
}
 
class ListEntry 
{
   private String value;
   private ImageIcon icon;
 
   public ListEntry(String value, ImageIcon icon) {
      this.value = value;
      this.icon = icon;
   }
 
   public String getValue() {
      return value;
   }
 
   public ImageIcon getIcon() {
      return icon;
   }
 
   public String toString() {
      return value;
   }
}
 
class ListEntryCellRenderer
 extends JLabel implements ListCellRenderer
{
   private JLabel label;
 
   public Component getListCellRendererComponent(JList list, Object value,
                                                 int index, boolean isSelected,
                                                 boolean cellHasFocus) {
      ListEntry entry = (ListEntry) value;
 
      setText(value.toString());
      setIcon(entry.getIcon());
  
      if (isSelected) {
         setBackground(list.getSelectionBackground());
         setForeground(list.getSelectionForeground());
      }
      else {
         setBackground(list.getBackground());
         setForeground(list.getForeground());
      } 
 
      setEnabled(list.isEnabled());
      setFont(list.getFont());
      setOpaque(true);
 
      return this;
   }
}

Have two JTrees vertically aligned in a JScrollPane

Main.java:

import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
 
public class Main extends JFrame
{
   public Main() {
      DefaultMutableTreeNode root = createNodes();
      JTree tree1 = new JTree(root);
      JTree tree2 = new JTree(root);
 
      tree1.addTreeSelectionListener(new TreeSelectionListener() {
         public void valueChanged(TreeSelectionEvent e) {         
            TreePath path = e.getPath();
            System.out.println(path.getLastPathComponent());     
         }
      });
 
      tree2.addTreeSelectionListener(new TreeSelectionListener() {
         public void valueChanged(TreeSelectionEvent e) {         
            TreePath path = e.getPath();
            System.out.println(path.getLastPathComponent());     
         }
      });
  
      Box box = Box.createVerticalBox();
      box.add(tree1);
      box.add(tree2);
 
      // bugparade #4833645
      tree1.setMinimumSize(tree1.getPreferredSize());
      tree1.setAlignmentX(0);
      tree2.setMinimumSize(tree2.getPreferredSize());
      tree2.setAlignmentX(0);
 
      getContentPane().setLayout(new BorderLayout());
     
      JScrollPane sp = new JScrollPane(box);
      sp.getViewport().setBackground(Color.white);
 
      getContentPane().add(BorderLayout.NORTH, sp);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
  
   public static DefaultMutableTreeNode createNodes() {
      DefaultMutableTreeNode root = new DefaultMutableTreeNode("Java");
      
      DefaultMutableTreeNode j2se = new DefaultMutableTreeNode("J2SE");
      DefaultMutableTreeNode j2ee = new DefaultMutableTreeNode("J2EE");
      DefaultMutableTreeNode j2me = new DefaultMutableTreeNode("J2ME");
 
      j2se.add(new DefaultMutableTreeNode("http://java.sun.com/j2se/"));
      j2ee.add(new DefaultMutableTreeNode("http://java.sun.com/j2ee/"));
      j2me.add(new DefaultMutableTreeNode("http://java.sun.com/j2me/"));
 
      root.add(j2se);
      root.add(j2ee);
      root.add(j2me);
 
      return root;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Changing the color of the lines between JTable header cells

Main.java:

import javax.swing.plaf.basic.*;
import javax.swing.border.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
 
public class Main extends JFrame 
{
   public Main() {
      String[] header = {"column #1","column #2","column #3", "column #4"};
      String[][] data = {{"1","2","3","4"},
                         {"5","6","7","8"}};
 
      JTable table = new JTable(data, header);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      getContentPane().add(new JScrollPane(table));
 
      MyHeaderRenderer renderer = new MyHeaderRenderer();
      System.out.println(table.getTableHeader().getDefaultRenderer());
      table.getTableHeader().setDefaultRenderer(renderer);
       
      setSize(300,200);
   } 

 
   public static void main( String args[] ) { 
      Main main = new Main();
      main.setVisible(true);
   }
}
 
class MyHeaderRenderer extends DefaultTableCellRenderer 
{
   private static LineBorder border = new LeftColorLineBorder((Color) UIManager.get("Button.focus"));
 
   public java.awt.Component getTableCellRendererComponent(JTable table, Object value,
                                 boolean selected, boolean focus, int row, int col) {
      Component c = super.getTableCellRendererComponent(table, value, selected, focus, row, col);
 


      setHorizontalAlignment(JLabel.CENTER);
      setBorder(border);
      return c;
   }
}
 
class LeftColorLineBorder extends LineBorder
{
   public LeftColorLineBorder(Color color) {
      super(color, 1, false);
   }
 
   public LeftColorLineBorder(Color color, int thickness) {
      super(color, thickness, false);
   }
 
   public LeftColorLineBorder(Color color, int thickness, boolean roundedCorners) {
      super(color, thickness, roundedCorners);
   }
   
   public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
      super.paintBorder(c, g, x, y, width, height);
      g.setColor(Color.black);
      g.fillRect(x, y, x+4, y+height);
      g.fillRect(x+width-4, y, x+width, y+height);
   }
}

Embedding a JTextArea and ImageIcon in a JTable cell

JTextAreaTableExample.java:

import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
  
public class JTextAreaTableExample extends JFrame {
 
  public JTextAreaTableExample() {
    super( "JTextAreaTableExample Example" );
  
    DefaultTableModel dtm = new DefaultTableModel() {
       // make first cell uneditable
       public boolean isCellEditable(int row, int column)
       {
          return !(column == 0);
       }
    };
 
    dtm.setDataVector(new Object[][]{{ "JTextArea1", "This is a testnon long linesn" },
                                     { "JTextArea2", "Hello, world!" }},
                      new Object[]{ "String","JTextArea"});
                     
    JTable table = new JTable(dtm);
    table.getColumn("JTextArea").setCellRenderer(new TextAreaRenderer());
    table.getColumn("JTextArea").setCellEditor(new TextAreaEditor());
 
    table.setRowHeight(80);
    JScrollPane scroll = new JScrollPane(table);
    getContentPane().add(scroll);
 
    setSize( 400, 250 );
    setVisible(true);
  }
 
  public static void main(String[] args) {
    JTextAreaTableExample frame = new JTextAreaTableExample();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
  }
}
  
class TextAreaRenderer extends JScrollPane implements TableCellRenderer
{
   JTextArea textarea;
 
   public TextAreaRenderer() {
      textarea = new JTextArea();
      textarea.setLineWrap(true);
      textarea.setWrapStyleWord(true);
      textarea.setBorder(new TitledBorder("This is a JTextArea"));
      JPanel panel = new JPanel();
      panel.setLayout(new BorderLayout());
      panel.add(BorderLayout.WEST, new JLabel(new ImageIcon("TrafficRed.gif")));
      panel.add(BorderLayout.CENTER, textarea);
      getViewport().add(panel);
   }
 
   public Component getTableCellRendererComponent(JTable table, Object value,
                                  boolean isSelected, boolean hasFocus,
                                  int row, int column)
   {
      if (isSelected) {
         setForeground(table.getSelectionForeground());
         setBackground(table.getSelectionBackground());
         textarea.setForeground(table.getSelectionForeground());
         textarea.setBackground(table.getSelectionBackground());
      } else {
         setForeground(table.getForeground());
         setBackground(table.getBackground());
         textarea.setForeground(table.getForeground());
         textarea.setBackground(table.getBackground());
      }
 
      textarea.setText((String) value); 
      textarea.setCaretPosition(0);
      return this;
   }
}
 
class TextAreaEditor extends DefaultCellEditor {
   protected JScrollPane scrollpane;
   protected JTextArea textarea; 
 
   public TextAreaEditor() {
      super(new JCheckBox());
      scrollpane = new JScrollPane();
      textarea = new JTextArea();  
      textarea.setLineWrap(true);
      textarea.setWrapStyleWord(true);
      textarea.setBorder(new TitledBorder("This is a JTextArea"));
      JPanel panel = new JPanel();
      panel.setLayout(new BorderLayout());
      panel.add(BorderLayout.WEST, new JLabel(new ImageIcon("TrafficRed.gif")));
      panel.add(BorderLayout.CENTER, textarea);
      scrollpane.getViewport().add(panel);
   }
 
   public Component getTableCellEditorComponent(JTable table, Object value,
                                   boolean isSelected, int row, int column) {
      textarea.setText((String) value);
 
      return scrollpane;
   }
 
   public Object getCellEditorValue() {
      return textarea.getText();
   }
}

Image used:

Changing the color of one JTable cell

Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      super("TableModel Demonstration");
  
      // create our own custom TableModel
      WineTableModel wineModel = new WineTableModel();
      JTable table = new JTable(wineModel);
 
      // since we're using values of floats and boolean here, we need
      // to set the cell renderer for every column. 
      for (int i =0; i<wineModel.getColumnCount();i++) {
         table.setDefaultRenderer(table.getColumnClass(i), new WineCellRenderer());
      }
       
      // add rows to our TableModel, each row is represented as a Wine object
      wineModel.addWine(new Wine("Chateau Meyney, St. Estephe", "1994", 18.75f, true));
      wineModel.addWine(new Wine("Chateau Montrose, St. Estephe", "1975", 54.25f, true));
      wineModel.addWine(new Wine("Chateau Gloria, St. Julien", "1993", 22.99f, false));
      wineModel.addWine(new Wine("Chateau Beychevelle, St. Julien", "1970", 61.63f, false));
      wineModel.addWine(new Wine("Chateau La Tour de Mons, Margeaux", "1975", 57.03f, true));
      wineModel.addWine(new Wine("Chateau Brane-Cantenac, Margeaux", "1978", 49.92f, false));
 
      // create the scroll pane and add the table to it. 
      JScrollPane scrollPane = new JScrollPane(table);
 
      // add the scroll pane to this window.
      getContentPane().add(scrollPane, BorderLayout.CENTER);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   }
}
 
// a simple object that holds data about a particular wine
class Wine {
   private String  name;
   private String  vintage;
   private float   price;
   private boolean inStock;
 
   public Wine(String name, String vintage, float price, boolean inStock) {
      this.name = name;
      this.vintage = vintage;
      this.price = price;
      this.inStock = inStock;
   }
 
   public String getName()     { return name; }
   public String getVintage()  { return vintage; }
   public float  getPrice()    { return price; } 
   public boolean getInStock() { return inStock; }
 
   public String toString() { 
      return "[" + name + ", " + vintage + ", " + price + ", " + inStock + "]"; }
}
 
class WineTableModel extends AbstractTableModel {
   // holds the strings to be displayed in the column headers of our table
   final String[] columnNames = {"Name", "Vintage", "Price", "In stock?"};
 
   // holds the data types for all our columns
   final Class[] columnClasses = {String.class, String.class, Float.class, Boolean.class};
 
   // holds our data
   final Vector data = new Vector();
  
   // adds a row
   public void addWine(Wine w) {
      data.addElement(w);
      fireTableRowsInserted(data.size()-1, data.size()-1);
   }
 
   public int getColumnCount() {
      return columnNames.length;
   }
         
   public int getRowCount() {
      return data.size();
   }
 
   public String getColumnName(int col) {
      return columnNames[col];
   }
 
   public Class getColumnClass(int c) {
      return columnClasses1;
   }
 
   public Object getValueAt(int row, int col) {
      Wine wine = (Wine) data.elementAt(row);
      if (col == 0)      return wine.getName();
      else if (col == 1) return wine.getVintage();
      else if (col == 2) return new Float(wine.getPrice());
      else if (col == 3) return new Boolean(wine.getInStock());
      else return null;
   }
 
   public Object getValueAtRow(int row) {
      Wine wine = (Wine) data.elementAt(row);
      return wine;
   }
 
   public boolean isCellEditable(int row, int col) {
      return false;
   }
}
 
class WineCellRenderer extends DefaultTableCellRenderer {
   public Component getTableCellRendererComponent(
            JTable table, Object value, boolean isSelected,
            boolean hasFocus, int row, int column)
   {
      WineTableModel wtm = (WineTableModel) table.getModel();
      Wine wine = (Wine) wtm.getValueAtRow(row);
 
      if (column == 3 && wine.getInStock() == false) {
         setBackground(Color.red);
      }
      else {
         setBackground(Color.white);
      }
 
      return super.getTableCellRendererComponent(table, value, isSelected, 
                                                 hasFocus, row, column);
   }
}

Get a private key from a keystore

This example extracts a private key from a keystore and prints it out in PEM format.

Main.java:

import sun.misc.BASE64Encoder;
import java.security.cert.Certificate;
import java.security.*;
import java.io.File;
import java.io.FileInputStream;
 
class Main {
   public static void main(String args[]) throws Exception{
      if (args.length != 3) {
         System.out.println("Extracts private key in PEM format from a JKS keystore");
         System.out.println("Usage: java Main <keystore> <alias> <passphrase>");
         System.exit(1);
      }
 
      String keystore = args[0];
      String alias = args[1];
      String password = args[2];      
 
      KeyStore ks = KeyStore.getInstance("JKS");
      char[] passphrase = password.toCharArray();
      BASE64Encoder base64Encoder = new BASE64Encoder();
 
      ks.load(new FileInputStream(keystore), passphrase);
 
      PrivateKey privateKey = getPrivateKey(ks, alias, passphrase);
 
      String sPrivateKey = base64Encoder.encode(privateKey.getEncoded());
 
      System.out.println("-----BEGIN PRIVATE KEY-----");
      System.out.println(sPrivateKey);
      System.out.println("-----END PRIVATE KEY-----");
   }
 
   public static PrivateKey getPrivateKey(KeyStore keystore, String alias, char[] password) {
      try {
         Key key = keystore.getKey(alias, password);
         if (key instanceof PrivateKey) {
            Certificate cert = keystore.getCertificate(alias);
            PublicKey publicKey = cert.getPublicKey();
 
            KeyPair kp = new KeyPair(publicKey, (PrivateKey)key);
 
            return kp.getPrivate();
         }
      } catch (UnrecoverableKeyException e) {
         e.printStackTrace();
      } catch (NoSuchAlgorithmException e) {
         e.printStackTrace();
      } catch (KeyStoreException e) {
         e.printStackTrace();
      }
 
      return null;
   }
}

Aligning the text in a JComboBox to the right

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      this.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
      Object []items = new Object[] { "one", "two", "three", "four", 
                                      "five", "six", "seven" };
      JComboBox comboBox = new JComboBox(items);
      getContentPane().add(comboBox);
 
      DefaultListCellRenderer listRenderer = new DefaultListCellRenderer();
      listRenderer.setHorizontalAlignment(DefaultListCellRenderer.RIGHT);
      comboBox.setRenderer(listRenderer);      
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(200, 200);
      main.setVisible(true);
   }
}

Writing a custom FocusTraversalPolicy

[JDK 1.4+] Extend from FocusTraversalPolicy and implement the abstract methods!

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
  
public class Main extends JFrame
{
   JLabel label = new JLabel("Forward: TAB or alt-f, Backward: SHIFT-TAB or alt-b");
   ArrayList textfields = new ArrayList();
   JRadioButton leftToRight = new JRadioButton("Left to right", true);
   JRadioButton topToBottom = new JRadioButton("Top to bottom");
  
   public Main() {
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
      Container contentPane = getContentPane();
      contentPane.setLayout(new BorderLayout(10, 10));
  
      JPanel topPanel = new JPanel(new GridLayout(3, 1));
      topPanel.add(new JLabel("Change the focus traversal policy"));
 
      ButtonGroup group = new ButtonGroup();
      group.add(leftToRight);
      group.add(topToBottom);
      topPanel.add(leftToRight); 
      topPanel.add(topToBottom);
 
      JPanel bottomPanel = new JPanel(new GridLayout(4, 2));
      for (int i=0; i<4; i++) {
         for (int j=0; j<2; j++) { 
            JTextField textfield = new JTextField("" + i + ", " + j);
            textfields.add(textfield);
            bottomPanel.add(textfield);
         }
      }     
  
      contentPane.add(BorderLayout.NORTH, topPanel);
      contentPane.add(BorderLayout.SOUTH, bottomPanel);
  
      bottomPanel.setFocusTraversalPolicy(new MyFocusTraversalPolicy());
      bottomPanel.setFocusCycleRoot(true);
   } 
  
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(350, 200);
      main.setVisible(true);
   }
 
   class MyFocusTraversalPolicy extends FocusTraversalPolicy
   {
      // Returns the Component that should receive the focus after aComponent.
      public Component getComponentAfter(Container focusCycleRoot, Component aComponent) {
         if (leftToRight.isSelected()) {
            int index = textfields.indexOf(aComponent);
            return (Component) textfields.get((index + 1) % textfields.size());
         }
         else if (topToBottom.isSelected()) {
            int index = textfields.indexOf(aComponent);
            int nextIndex = (index + 2) % textfields.size();
            if (nextIndex == 0) nextIndex = 1;
            else if (nextIndex == 1) nextIndex = 0;
            return (Component) textfields.get(nextIndex);
         }
 
         if (!aComponent.isEnabled()) {
            return getComponentAfter(focusCycleRoot, aComponent);
         }          
 
         return aComponent;
      }
  
      // Returns the Component that should receive the focus before aComponent.
      public Component getComponentBefore(Container focusCycleRoot, Component aComponent) {
         if (leftToRight.isSelected()) {
            int index = textfields.indexOf(aComponent);
            index--;
            if (index < 0) index = textfields.size() - 1;
            return (Component) textfields.get(index);
         }
         else if (topToBottom.isSelected()) {
            int index = textfields.indexOf(aComponent);
            index -= 2;
            if (index < 0) index = textfields.size() - 3 - index;
            //else if (index == 0) index = textfields.size() - 1;
            //else if (index == 1) index = textfields.size() - 2;
            return (Component) textfields.get(index);
         }
 
         return aComponent;
      }
  
      // Returns the default Component to focus.
      public Component getDefaultComponent(Container focusCycleRoot) {
         return (Component) textfields.get(0);
      }
 
      // Returns the first Component in the traversal cycle.
      public Component getFirstComponent(Container focusCycleRoot) {
         return (Component) textfields.get(0);
      }
 
      // Returns the Component that should receive the focus when a Window is made visible for the first time. 
      public Component getInitialComponent(Window window) {
         return leftToRight;
      }
 
      // Returns the last Component in the traversal cycle. 
      public Component getLastComponent(Container focusCycleRoot) {
         return (Component) textfields.get(textfields.size() - 1);
      }
   }
}

Changing the traversal keys that control focus

In 1.4, you can use the following method.

Main.java:

import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame
{
   JLabel label = new JLabel("Forward: TAB or alt-f, Backward: SHIFT-TAB or alt-b");
   JButton button = new JButton("Button");
   JTextField textfield1 = new JTextField();
   JTextField textfield2 = new JTextField();
 
   public Main() {
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
      Container contentPane = getContentPane();
      contentPane.setLayout(new BorderLayout());
      JPanel panel = new JPanel(new GridLayout(4, 1, 10, 10));
      panel.add(label);
      panel.add(textfield1);   
      panel.add(textfield2);   
      panel.add(button);
      contentPane.add(BorderLayout.NORTH, panel);
 
      // add "alt f" as an alternative to TAB 
      Set set = contentPane.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
      KeyStroke altf = KeyStroke.getKeyStroke("alt F");
      set = new HashSet(set);
      set.add(altf);
      contentPane.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, set);
 
      // add "alt b" as an alternative to SHIFT-TAB 
      set = contentPane.getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
      KeyStroke altb = KeyStroke.getKeyStroke("alt B");
      set = new HashSet(set);
      set.add(altb);
      contentPane.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, set);
   } 
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(350, 200);
      main.setVisible(true);
   }
}