Detecting a double-click on a row in a JTable

Make sure your class implements the MouseListener interface, and use the following code to detect a double-click on a table row:

public void mouseClicked(MouseEvent e) {
   if (e.getClickCount() == 2) {
      JTable target = (JTable)e.getSource();
      int row = target.getSelectedRow();
      ...
   }
}

Creating a JTable with headers with JTooltips

Courtesy of Nobuo Tamemasa (http://www2.gol.com/users/tame/swing/examples/JTableExamples6.html)



ToolTipHeaderTableExample.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

/**
 * @version 1.0 02/25/99
 */
public class ToolTipHeaderTableExample extends JPanel {

  public ToolTipHeaderTableExample(){
    setLayout(new BorderLayout());
    String[] headerStr  = {"default","jw"      ,"ja"      ,"la"   ,"unknown"};
    String[] toolTipStr = {""       ,"Javanese","Japanese","Latin"};
    
    DefaultTableModel dm = new DefaultTableModel(headerStr, 4);
    JTable table = new JTable(dm);
    
    ToolTipHeader header = new ToolTipHeader(table.getColumnModel());
    header.setToolTipStrings(toolTipStr);
    header.setToolTipText("Default ToolTip TEXT");
    table.setTableHeader(header);
    
    JScrollPane pane = new JScrollPane(table);
    add(pane, BorderLayout.CENTER);
  }

  public static void main(String[] args) {
    JFrame f= new JFrame("ToolTipHeaderTable Example");
    f.getContentPane().add(new ToolTipHeaderTableExample(), BorderLayout.CENTER);
    f.setSize(400, 100);
    f.setVisible(true);
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {System.exit(0);}
    });
  }
    
  class ToolTipHeader extends JTableHeader {
    String[] toolTips;
  
    public ToolTipHeader(TableColumnModel model) {
      super(model);
    }
    
    public String getToolTipText(MouseEvent e) {
      int col  = columnAtPoint(e.getPoint());
      int modelCol = getTable().convertColumnIndexToModel(col);
      String retStr;
      try {
        retStr = toolTips[modelCol];
      } catch (NullPointerException ex) {
        retStr = "";
      } catch (ArrayIndexOutOfBoundsException ex) {
        retStr = "";
      }
      if (retStr.length() < 1) {
        retStr = super.getToolTipText(e);
      }
      return retStr;
    }   
    
    public void setToolTipStrings(String[] toolTips) {
      this.toolTips = toolTips;
    } 
  }
}

Creating a JTable with editable headers

Courtesy of Nobuo Tamemasa (http://www2.gol.com/users/tame/swing/examples/JTableExamples9.html)



EditableHeaderTableExample.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
 
/**
 * @version 1.0 08/22/99
 */
public class EditableHeaderTableExample extends JFrame {

  public EditableHeaderTableExample(){
    super( "EditableHeader Example" );
    
    JTable table = new JTable(7, 5);
    TableColumnModel columnModel = table.getColumnModel();
    table.setTableHeader(new EditableHeader(columnModel));
    
    JScrollPane pane = new JScrollPane(table);
    getContentPane().add(pane);
  }

  public static void main(String[] args) {
    EditableHeaderTableExample frame = new EditableHeaderTableExample();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    frame.setSize( 300, 100 );
    frame.setVisible(true);
  }
}

EditableHeader.java:

import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;


/**
 * @version 1.0 08/21/99
 */
public class EditableHeader extends JTableHeader
                         implements CellEditorListener {
  public final int HEADER_ROW = -10;
  transient protected int editingColumn;
  transient protected TableCellEditor cellEditor;
  transient protected Component       editorComp;

  public EditableHeader(TableColumnModel columnModel) {
    super(columnModel);
    setReorderingAllowed(false);
    cellEditor = null;
    recreateTableColumn(columnModel);
  }
  
  public void updateUI(){
    setUI(new EditableHeaderUI());
    resizeAndRepaint();
    invalidate();
  }
  
  protected void recreateTableColumn(TableColumnModel columnModel) {
    int n = columnModel.getColumnCount();
    EditableHeaderTableColumn[] newCols = new EditableHeaderTableColumn[n];
    TableColumn[] oldCols = new TableColumn[n];
    for (int i=0;i<n;i++) {
      oldCols[i] = columnModel.getColumn(i);
      newCols[i] = new EditableHeaderTableColumn();
      newCols[i].copyValues(oldCols[i]);
    }
    for (int i=0;i<n;i++) {
      columnModel.removeColumn(oldCols[i]);
    }
    for (int i=0;i<n;i++) {
      columnModel.addColumn(newCols[i]);
    }
  }

  public boolean editCellAt(int index){
    return editCellAt(index);
  }
  
  public boolean editCellAt(int index, EventObject e){
    if (cellEditor != null && !cellEditor.stopCellEditing()) { 
      return false;
    }
    if (!isCellEditable(index)) {
      return false;
    }    
    TableCellEditor editor = getCellEditor(index);
    
    if (editor != null && editor.isCellEditable(e)) {
      editorComp = prepareEditor(editor, index);
      editorComp.setBounds(getHeaderRect(index));
      add(editorComp);
      editorComp.validate();
      setCellEditor(editor);
      setEditingColumn(index);
      editor.addCellEditorListener(this);

      return true;
    }    
    return false;
  }

  
  public boolean isCellEditable(int index) {
    if (getReorderingAllowed()) {
      return false;
    }
    int columnIndex = columnModel.getColumn(index).getModelIndex();
    EditableHeaderTableColumn col = (EditableHeaderTableColumn)columnModel.getColumn(columnIndex);
    return col.isHeaderEditable();
  }
  
  public TableCellEditor getCellEditor(int index) {
    int columnIndex = columnModel.getColumn(index).getModelIndex();
    EditableHeaderTableColumn col = (EditableHeaderTableColumn)columnModel.getColumn(columnIndex);
    return col.getHeaderEditor();
  }
  
  public void setCellEditor(TableCellEditor newEditor) {
    TableCellEditor oldEditor = cellEditor;
    cellEditor = newEditor;
    
    // firePropertyChange
    
    if (oldEditor != null && oldEditor instanceof TableCellEditor) {
      ((TableCellEditor)oldEditor).removeCellEditorListener((CellEditorListener)this);
    }
    if (newEditor != null && newEditor instanceof TableCellEditor) {
      ((TableCellEditor)newEditor).addCellEditorListener((CellEditorListener)this);
    }
  }

  public Component prepareEditor(TableCellEditor editor, int index) {
    Object       value = columnModel.getColumn(index).getHeaderValue();
    boolean isSelected = true;
    int            row = HEADER_ROW;
    JTable       table = getTable();
    Component comp = editor.getTableCellEditorComponent(table,
                       value, isSelected, row, index);
    if (comp instanceof JComponent) { 
            ((JComponent)comp).setNextFocusableComponent(this);             
    }
    return comp;
  }
  
  public TableCellEditor getCellEditor() {
    return cellEditor;
  }
  
  public Component getEditorComponent() {
    return editorComp;
  }
  
  public void setEditingColumn(int aColumn) {
    editingColumn = aColumn;
  }
  
  public int getEditingColumn() {
    return editingColumn;
  }
  
  public void removeEditor() {
    TableCellEditor editor = getCellEditor();
    if (editor != null) {
      editor.removeCellEditorListener(this);

      requestFocus();
      remove(editorComp);
      
      int index = getEditingColumn();
      Rectangle cellRect = getHeaderRect(index);

      setCellEditor(null);
      setEditingColumn(-1);
      editorComp = null;

      repaint(cellRect);
    }
  }
  
  public boolean isEditing() {
    return (cellEditor == null)? false : true;
  }

  
  //
  // CellEditorListener
  //
  public void editingStopped(ChangeEvent e) {
    TableCellEditor editor = getCellEditor();
    if (editor != null) {
      Object value = editor.getCellEditorValue();
      int index = getEditingColumn();
      columnModel.getColumn(index).setHeaderValue(value);
      removeEditor();
    }
  }

  public void editingCanceled(ChangeEvent e) {
    removeEditor();
  }
  
  
  //
  // public void setReorderingAllowed(boolean b) {
  //   reorderingAllowed = false;
  // }

}

EditableHeaderUI.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import javax.swing.plaf.basic.*;


/**
 * @version 1.0 08/21/99
 */
public class EditableHeaderUI extends BasicTableHeaderUI {
    
  protected MouseInputListener createMouseInputListener() {
    return new MouseInputHandler((EditableHeader)header);
  }

  public class MouseInputHandler extends BasicTableHeaderUI.MouseInputHandler {
    private Component dispatchComponent;
    protected EditableHeader header;

    public MouseInputHandler(EditableHeader header) {
      this.header = header;
    }

    private void setDispatchComponent(MouseEvent e) { 
      Component editorComponent = header.getEditorComponent();
      Point p = e.getPoint();
      Point p2 = SwingUtilities.convertPoint(header, p, editorComponent);
      dispatchComponent = SwingUtilities.getDeepestComponentAt(editorComponent, 
                                                               p2.x, p2.y);
    }

    private boolean repostEvent(MouseEvent e) { 
      if (dispatchComponent == null) {
        return false; 
      }
      MouseEvent e2 = SwingUtilities.convertMouseEvent(header, e, dispatchComponent);
      dispatchComponent.dispatchEvent(e2); 
      return true; 
    }
    
    public void mousePressed(MouseEvent e) {
      if (!SwingUtilities.isLeftMouseButton(e)) {
        return;
      }
      super.mousePressed(e);

      if (header.getResizingColumn() == null) {
        Point p = e.getPoint();
        TableColumnModel columnModel = header.getColumnModel();
        int index = columnModel.getColumnIndexAtX(p.x);
        if (index != -1) {
          if (header.editCellAt(index, e)) {
            setDispatchComponent(e); 
            repostEvent(e); 
          }
        }
      }
    }

    public void mouseReleased(MouseEvent e) {
      super.mouseReleased(e);
      if (!SwingUtilities.isLeftMouseButton(e)) {
        return;
      }
      repostEvent(e); 
      dispatchComponent = null;    
    }
        
  } 
}

EditableHeaderTableColumn.java:

import javax.swing.*;
import javax.swing.table.*;


/**
 * @version 1.0 08/21/99
 */
public class EditableHeaderTableColumn extends TableColumn {

  protected TableCellEditor headerEditor;
  protected boolean isHeaderEditable;

  public EditableHeaderTableColumn() {
    setHeaderEditor(createDefaultHeaderEditor());
    isHeaderEditable = true;
  }
  
  public void setHeaderEditor(TableCellEditor headerEditor) {
    this.headerEditor = headerEditor;
  }
  
  public TableCellEditor getHeaderEditor() {
    return headerEditor;
  }
  
  public void setHeaderEditable(boolean isEditable) {
    isHeaderEditable = isEditable;
  }
  
  public boolean isHeaderEditable() {
    return isHeaderEditable;
  }
  
  public void copyValues(TableColumn base) {    
    modelIndex     = base.getModelIndex();
    identifier     = base.getIdentifier();
    width          = base.getWidth();
    minWidth       = base.getMinWidth();
    setPreferredWidth(base.getPreferredWidth());
    maxWidth       = base.getMaxWidth();
    headerRenderer = base.getHeaderRenderer();
    headerValue    = base.getHeaderValue();
    cellRenderer   = base.getCellRenderer();
    cellEditor     = base.getCellEditor();
    isResizable    = base.getResizable();
  }
  
  protected TableCellEditor createDefaultHeaderEditor() {
    return new DefaultCellEditor(new JTextField());
  }
  
}

Adding a background to a JTextArea

Make sure the opaqueness property of your JTextArea component is false. You can then override the paintComponent method that draws the background image and calls super.paintComponent. Here’s an example:

import javax.swing.*;
import java.awt.*;
 
public class Main {
   public static void main(String args[]) {
      JFrame frame = new JFrame("JTextArea Background Demonstration");
      final ImageIcon imageIcon = new ImageIcon("esuslogo.gif");
 
      JTextArea textArea = new JTextArea() {
         Image image = imageIcon.getImage();
         { 
            setOpaque(false);
            image = image.getScaledInstance(400, 300, Image.SCALE_DEFAULT);
         }
         public void paintComponent (Graphics g) {
            g.drawImage(image, 0, 0, this);
            setForeground(Color.blue);
            super.paintComponent(g);
         }
      };
      textArea.setFont(new Font("Helvetica", Font.BOLD, 16));
 
      frame.getContentPane().add(BorderLayout.CENTER, new JScrollPane(textArea));
      frame.setDefaultCloseOperation(3);
      frame.setSize(400, 300);
      frame.setVisible(true);
      frame.setResizable(false);
   }
}

Having a JTextArea as a node of a JTree

Main.java:

import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame
{
   public Main() {
      DefaultMutableTreeNode root = createNodes();
      JTree tree = new JTree(root);
      //tree.setCellEditor(new DefaultCellEditor(new JTextField())); 
      tree.setCellRenderer(new DelegateDefaultCellRenderer());
      tree.setRowHeight(-1);
 
      getContentPane().add(new JScrollPane(tree));
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static DefaultMutableTreeNode createNodes() {
      DefaultMutableTreeNode root = new DefaultMutableTreeNode(&amp;amp;quot;Java&amp;amp;quot;);
      
      DefaultMutableTreeNode j2se = new DefaultMutableTreeNode(&amp;amp;quot;J2SE&amp;amp;quot;);
      DefaultMutableTreeNode j2ee = new DefaultMutableTreeNode(&amp;amp;quot;J2EE&amp;amp;quot;);
      DefaultMutableTreeNode j2me = new DefaultMutableTreeNode(&amp;amp;quot;J2ME&amp;amp;quot;);
 
      j2se.add(new DefaultMutableTreeNode(&amp;amp;quot;http://java.sun.com/j2se/&amp;amp;quot;));
      j2ee.add(new DefaultMutableTreeNode(&amp;amp;quot;http://java.sun.com/j2ee/&amp;amp;quot;));
      j2me.add(new DefaultMutableTreeNode(&amp;amp;quot;http://java.sun.com/j2me/&amp;amp;quot;));
 
      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);
   }
}
 
class DelegateDefaultCellRenderer extends DefaultTreeCellRenderer 
{
   TextAreaRenderer taRenderer = new TextAreaRenderer();
 
   public DelegateDefaultCellRenderer() {
      taRenderer.setBackgroundNonSelectionColor(getBackgroundNonSelectionColor());
      taRenderer.setBackgroundSelectionColor(getBackgroundSelectionColor());
      taRenderer.setTextNonSelectionColor(getTextNonSelectionColor());  
      taRenderer.setTextSelectionColor(getTextSelectionColor()); 
   }
 
   public Component getTreeCellRendererComponent(JTree tree, Object value,
                                  boolean selected, boolean expanded, boolean leaf,
                                  int row, boolean hasFocus)
   {
      if (!leaf) {
         return super.getTreeCellRendererComponent(tree, value, selected, 
                                                   expanded, leaf, row, hasFocus);
      }
      else {
         return taRenderer.getTreeCellRendererComponent(tree, value, selected, 
                                                        expanded, leaf, row, hasFocus);
      }
   }
}   
 
class TextAreaRenderer extends JScrollPane implements TreeCellRenderer
{
   JTextArea textarea;
   Color backgroundNonSelectionColor;
   Color backgroundSelectionColor;
   Color textNonSelectionColor;
   Color textSelectionColor;
 
   public TextAreaRenderer() {
      textarea = new JTextArea(3, 40);
      textarea.setLineWrap(true);
      textarea.setWrapStyleWord(true);
      textarea.setBorder(new TitledBorder(&amp;amp;quot;This is a JTextArea&amp;amp;quot;));
      getViewport().add(textarea);
   }
 
   public void setBackgroundNonSelectionColor(Color c) {
      this.backgroundNonSelectionColor = c;
   }
 
   public void setBackgroundSelectionColor(Color c) {
      this.backgroundSelectionColor = c;
   }
  
   public void setTextNonSelectionColor(Color c) {
      this.textNonSelectionColor = c;
   }
  
   public void setTextSelectionColor(Color c) {
      this.textSelectionColor = c;
   }
 
   public Component getTreeCellRendererComponent(JTree tree, Object value,
                                  boolean selected, boolean expanded, boolean leaf,
                                  int row, boolean hasFocus)
   {
      if (selected) {
         setForeground(textSelectionColor);
         setBackground(backgroundSelectionColor);
         textarea.setForeground(textSelectionColor);
         textarea.setBackground(backgroundSelectionColor);
      } else {
         setForeground(textNonSelectionColor);
         setBackground(backgroundNonSelectionColor);
         textarea.setForeground(textNonSelectionColor);
         textarea.setBackground(backgroundNonSelectionColor);
      }
 
      textarea.setText(&amp;amp;quot;&amp;amp;quot;+((DefaultMutableTreeNode) value).getUserObject()); 
      textarea.setCaretPosition(0);
 
      return this;
   }
}

Adding a popup listener to a JTable row

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();
      final JTable table = new JTable(wineModel);
 
      // 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);
 
      final TablePopup tablePopup = new TablePopup(table);
      table.addMouseListener(new MouseAdapter() {
         public void mouseReleased(MouseEvent me) {
            int row = table.rowAtPoint(me.getPoint());
            System.out.println("You clicked at row " + row);
            // possibly use row variable here to do something specific with your popup menu
            if (me.isPopupTrigger()) {
               tablePopup.show(me.getComponent(), me.getX(), me.getY());
            }
         }
      });
 
      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 boolean isCellEditable(int row, int col) {
      return false;
   }
}
 
class TablePopup extends JPopupMenu {
   public TablePopup(JTable tree) {
      JMenuItem itemEdit = new JMenuItem("Edit");
      JMenuItem itemDelete = new JMenuItem("Delete");
      itemEdit.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println("Edit child");
         }
      });
      itemDelete.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println("Delete selected");
         }
      });
 
      add(itemEdit);
      add(new JSeparator());
      add(itemDelete);
   }
}

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

Adding a vertical line separator to a JToolBar

The method addSeparator in the JToolBar class only adds blank space. You could add JSeparator components to your JToolBar with add but then you run into trouble when changing the orientation. In the following example, this has been solved by listening to propertyChangeEvents and changing the JSeparator orientation so that they are opposite to the JToolBar’s orientation.

Main.java:

import javax.swing.border.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.awt.*;
  
public class Main extends JFrame {
   public Main() {
      super("JToolBar example");
 
      final JTextArea textArea = new JTextArea(5, 30);
      MyJToolBar toolBar = new MyJToolBar();
 
      JButton gifButton = new JButton(new ImageIcon("gifIcon.gif"));
      JButton jpgButton = new JButton(new ImageIcon("jpgIcon.gif"));
      JButton tiffButton = new JButton(new ImageIcon("tiffIcon.gif"));
 
      gifButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("gifButton clicked!n");
         }
      });
  
      jpgButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("jpgButton clicked!n");
         }
      });
        
      tiffButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("tiffButton clicked!n");
         }
      });
 
      toolBar.add(gifButton);
      toolBar.add(new JToolBar.Separator());
      toolBar.add(new JSeparator(JSeparator.VERTICAL));
      toolBar.add(new JToolBar.Separator());
      toolBar.add(jpgButton);
      toolBar.add(new JToolBar.Separator());
      toolBar.add(new JSeparator(JSeparator.VERTICAL));
      toolBar.add(new JToolBar.Separator());
      toolBar.add(tiffButton);
 
      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 MyJToolBar extends JToolBar
{
   public MyJToolBar() {
      super();
      listenForOrientationChange();
   }
 
   public MyJToolBar(int orientation) {
      super(orientation);
      listenForOrientationChange();
   }
 
   public MyJToolBar(String name) {
      super(name);
      listenForOrientationChange();
   }
 
   public MyJToolBar(String name, int orientation) {
      super(name, orientation);
      listenForOrientationChange();
   }
 
   protected void listenForOrientationChange() {
      addPropertyChangeListener(new PropertyChangeListener() {
         public void propertyChange(PropertyChangeEvent evt) {
            MyJToolBar toolBar = MyJToolBar.this;
            Component[] components = toolBar.getComponents();
            for (int i=0; i<components.length; i++) {
               if (components[i] instanceof javax.swing.JSeparator) {
                  JSeparator separator = (JSeparator) components[i];
                  if (toolBar.getOrientation() == SwingConstants.HORIZONTAL) {
                     separator.setOrientation(JSeparator.VERTICAL);      
                     separator.setMaximumSize(new Dimension(2,
                                              toolBar.getPreferredSize().width));
                  }
                  else {
                     separator.setOrientation(JSeparator.HORIZONTAL);
                     separator.setMaximumSize(new Dimension(
                                              toolBar.getPreferredSize().height, 2));
                  }
               }
            }
         }
      });
   }
}

Capturing an event when a JInternalFrame is selected

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_SELECTED_PROPERTY)) { 
         boolean selected = ((Boolean) pce.getNewValue()).booleanValue(); 
         if (selected) { 
            System.out.println(getTitle() + " is selected!");
         } 
      } 
   }
} 

Trapping a drop-down event on a JComboBox

Since JDK1.4, you can add a PopupMenuListener to your JComboBox and receive the events.

Main.java:

import javax.swing.event.*;
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);
         }
      }); 
 
      Vector v = new Vector();
      v.add("first element");
      v.add("second element");
      v.add("third element");
      v.add("fourth element");
      v.add("fifth element");
 
      final JComboBox cb = new JComboBox(v);
      cb.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println(cb.getSelectedItem());
         }
      });
 
      cb.addPopupMenuListener(new PopupMenuListener() {
         public void popupMenuCanceled(PopupMenuEvent e) {
            System.out.println("PopupMenuCancel Event");
         }
 
         public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            System.out.println("popupMenuWillBecomeVisible");
         }
 
         public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            System.out.println("popupMenuWillBecomeInvisible");
         }
      });
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
      getContentPane().add(new JLabel("Select element:"));
      getContentPane().add(cb);
   } 
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
      main.setSize(300, 150);
   }
}