Justifying the text on a JMenuItem

You have a number of functions:setHorizontalAlignment, setHorizontalTextPosition, setVerticalAlignment, setVerticalTextPosition. Look at the API docs for more information about their behaviour.

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("Sex");
      JMenuItem menuItem0 = new JMenuItem("NO ALIGNMENT");
      JMenuItem menuItem1 = new JMenuItem("CENTER");
      JMenuItem menuItem2 = new JMenuItem("LEFT");
      JMenuItem menuItem3 = new JMenuItem("RIGHT");
      JMenuItem menuItem4 = new JMenuItem("LEADING");
      JMenuItem menuItem5 = new JMenuItem("TRAILING");
 
      // add the MenuItems to the Menu 
      menu.add(menuItem0);
      menu.add(menuItem1);
      menu.add(menuItem2);
      menu.add(menuItem3);
      menu.add(menuItem4);
      menu.add(menuItem5);
   
      menuItem1.setHorizontalAlignment(SwingConstants.CENTER);
      menuItem2.setHorizontalAlignment(SwingConstants.LEFT);
      menuItem3.setHorizontalAlignment(SwingConstants.RIGHT);
      menuItem4.setHorizontalAlignment(SwingConstants.LEADING);
      menuItem5.setHorizontalAlignment(SwingConstants.TRAILING);
 
      menuBar.add(menu);
 
      this.setJMenuBar(menuBar); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Enabling a component depending on the text entered in a JTextField

Add a document listener to the JTextField and listen to the characters that are inserted and removed.

Main.java:

import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame implements DocumentListener
{
   private JTextField tf; 
   private JButton button;
 
   public Main() {           
      getContentPane().setLayout(new BorderLayout());
      JPanel northPanel = new JPanel(new GridLayout(1, 2));
      northPanel.add(new JLabel("Enter an integer: "));
      tf = new JTextField();
      northPanel.add(tf);
      getContentPane().add(BorderLayout.NORTH, northPanel);
      button = new JButton("OK"); 
      getContentPane().add(BorderLayout.SOUTH, button);
      // Add a document listener to the textfield
      Document document = tf.getDocument();
      document.addDocumentListener(this);
 
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.exit(1);
         }
      });
      button.setEnabled(false);
 
      pack();
   }
 
   public void insertUpdate(DocumentEvent evt) {
      String s = tf.getText();
 
      try {
         int v = Integer.parseInt(s);
         button.setEnabled(true);
      }
      catch(NumberFormatException e) {
         button.setEnabled(false);
      }
   }
 
   public void removeUpdate(DocumentEvent evt) {
      if (tf.getText().length() == 0) {
         button.setEnabled(false);
      }
      else {
         insertUpdate(evt);
      }
   }
 
   public void changedUpdate(DocumentEvent evt) {
   }
 
   public static void main(String args[]) {
      Main main = new Main();
      main.setVisible(true);
   }
}

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

Validating a textfield using the regex package

You can use a custom InputVerifier in which you try to match the desired regular expression for that textfield.

Main.java:

import java.util.regex.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.text.*;
 
public class Main extends JFrame
{
   public Main() {
      super("JFormattedTextField REGEX example");
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      JFormattedTextField ftf = new JFormattedTextField();
      getContentPane().add(BorderLayout.NORTH, ftf);
      ftf.setInputVerifier(new RegExFieldVerifier("[abcd]+"));
 
      getContentPane().add(BorderLayout.SOUTH, new JTextField("Normal textfield"));
      getContentPane().add(BorderLayout.CENTER, 
                               new JLabel("<HTML>REGEX USED:  [abcd]+   allowed: " +
                                          "one or more of the following characters: " +
                                          "a,b,c or d.<BR>Use the TAB key to switch!</HTML>"));
 
   }
 
   public static void main(String []args) throws Exception {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}
 
class RegExFieldVerifier extends InputVerifier {
   Pattern pattern;
 
   public RegExFieldVerifier(String regex) {
      pattern = Pattern.compile(regex);
   }
 
   public boolean verify(JComponent input) {
      if (input instanceof JFormattedTextField) {
         JFormattedTextField ftf = (JFormattedTextField)input;
         String line = ftf.getText();
         Matcher m = pattern.matcher(line);
         if (!m.matches()) 
            System.out.println("Doesn't match regular expression " + 
                               pattern.pattern());      
         return m.matches();
      }        
      return true;     
   }
 
   public boolean shouldYieldFocus(JComponent input) {
      return verify(input);
   }
}