Putting a component in a TitledBorder?

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

CompTitledPaneExample1.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
 
/**
 * @version 1.0 08/12/99
 */  
public class CompTitledPaneExample1 extends JFrame {
 
  String title = "<html>Title (" 
               + "<font color="#ffffff"><i>JLabel</i></font>"
               + ")";
 
  public CompTitledPaneExample1() {
    super("CompTitledPaneExample1");
    JLabel titleLabel = new JLabel(title);
    CompTitledPane p1 = new CompTitledPane(titleLabel);
    JPanel p = p1.getContentPane();
    p.setLayout(new BorderLayout());
    p.add(new SwitchPanel(p1), BorderLayout.CENTER);
    getContentPane().add(p1, BorderLayout.CENTER);
  }
  
  class SwitchPanel extends JPanel implements ActionListener {
    String[] posStr = {"", "ABOVE_TOP"   , "TOP"   , "BELOW_TOP"
                         , "ABOVE_BOTTOM", "BOTTOM", "BELOW_BOTTOM"};
    String[] jusStr = {"", "LEFT"        , "CENTER", "RIGHT"};
    TitledBorder border;
    CompTitledPane panel;
    
    SwitchPanel(CompTitledPane panel) {
      this.panel = panel;
      this.border = (TitledBorder)panel.getBorder();
      add(createPanel("Position"     ,posStr, 2));
      add(createPanel("Justification",jusStr, 1));
    }
    
    JPanel createPanel(String str, String[] strs, int selectPos) {
      JPanel p = new JPanel();
      p.setLayout(new GridLayout(strs.length, 1));
      p.add(new JLabel(str));
      ButtonGroup g = new ButtonGroup();
      for (int i=1;i<strs.length;i++) {
        JRadioButton b = new JRadioButton(strs[i]);
        if (i == selectPos) {
          b.setSelected(true);
        }
        p.add( b );
        g.add( b );
        b.addActionListener(this);
      }
      return p;
    }
    
    public void actionPerformed(ActionEvent e) {
      JRadioButton b = (JRadioButton)e.getSource();
      String label = b.getText();
      for (int i=1; i<posStr.length; i++) {
        if (label.equals(posStr[i])) {
          border.setTitlePosition(i);
          panel.revalidate();
          panel.repaint();
          return;
        }    
      }
      for (int i=1; i<jusStr.length; i++) {
        if (label.equals(jusStr[i])) {
          border.setTitleJustification(i);
          panel.revalidate();
          panel.repaint();
          return;
        }    
      }
    }   
  }
 
  public static void main (String args[]) {
    CompTitledPaneExample1 frame = new CompTitledPaneExample1();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
	System.exit(0);
      }
    });
    frame.setSize(280, 230);
    frame.setVisible(true);
  }
}

CompTitledPane.java:

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
    
/**
 * @version 1.0 08/12/99
 */
public class CompTitledPane extends JPanel {
  protected CompTitledBorder border;
  protected JComponent component;
  protected JPanel panel;
  protected boolean transmittingAllowed;
  protected StateTransmitter transmitter;
  
  public CompTitledPane() {
    this(new JLabel("Title"));
    // debug
    // JLabel label = (JLabel)getTitleComponent();
    // label.setOpaque(true);
    // label.setBackground(Color.yellow);
  }
  
  public CompTitledPane(JComponent component) {
    this.component = component;
    border = new CompTitledBorder(component);
    setBorder(border);
    panel = new JPanel();
    setLayout(null);
    add(component);
    add(panel); 
    transmittingAllowed = false;
    transmitter = null;
  }
  
  public JComponent getTitleComponent() {
    return component;
  }
  
  public void setTitleComponent(JComponent newComponent) {
    remove(component);
    add(newComponent);
    border.setTitleComponent(newComponent);
    component = newComponent;
  }
  
  public JPanel getContentPane() {
    return panel;
  }
  
  public void doLayout() {
    Insets insets = getInsets();
    Rectangle rect = getBounds();
    rect.x = 0;
    rect.y = 0;
 
    Rectangle compR = border.getComponentRect(rect,insets);
    component.setBounds(compR);
    rect.x += insets.left;
    rect.y += insets.top;
    rect.width  -= insets.left + insets.right;
    rect.height -= insets.top  + insets.bottom;
    panel.setBounds(rect);   
  }
   
  public void setTransmittingAllowed(boolean enable) {
    transmittingAllowed = enable;
  }
  
  public boolean getTransmittingAllowed() {
    return transmittingAllowed;
  }
  
  public void setTransmitter(StateTransmitter transmitter) {
    this.transmitter = transmitter;
  }
  
  public StateTransmitter getTransmitter() {
    return transmitter;
  }
  
  public void setEnabled(boolean enable) {
    super.setEnabled(enable);
    if (transmittingAllowed && transmitter != null) {
      transmitter.setChildrenEnabled(enable);
    }
  } 
    
}

StateTransmitter.java:

/**
 * @version 1.0 08/12/99
 */
public interface StateTransmitter {

  public void setChildrenEnabled(boolean enable);
  
}

// sample
//
//  public void setChildrenEnabled(boolean enable) {
//    
//    Component[] children = panel.getComponents();
//    for(int i=0; i<children.length; i++) { 
//      System.out.println(" " + i + 
//                         " " + children[i].getClass().getName() +
//                         " " + enable);
//      children[i].setEnabled(enable); 
//    }
//  }
//

CompTitledBorder.java:

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
  
/**
 * @version 1.0 08/12/99
 */
public class CompTitledBorder extends TitledBorder { 
  protected JComponent component;
  
  public CompTitledBorder(JComponent component) {
    this(null, component, LEFT, TOP);
  }
  
  public CompTitledBorder(Border border) {
    this(border, null, LEFT, TOP);
  }
  
  public CompTitledBorder(Border border, JComponent component) {
    this(border, component, LEFT, TOP);
  }
    
  public CompTitledBorder(Border     border,
                          JComponent component,
                          int        titleJustification,
                          int        titlePosition)      {
    super(border, null, titleJustification,
                        titlePosition, null, null);
    this.component = component;
    if (border == null) {
      this.border = super.getBorder();
    }
  }
  
  
  public void paintBorder(Component c, Graphics g,
                          int x, int y, int width, int height) {
    Rectangle borderR = new Rectangle(x      +  EDGE_SPACING,
                                      y      +  EDGE_SPACING,
                                      width  - (EDGE_SPACING * 2),
                                      height - (EDGE_SPACING * 2));
    Insets borderInsets;
    if (border != null) {
      borderInsets = border.getBorderInsets(c);
    } else {
      borderInsets = new Insets(0, 0, 0, 0);
    }
    
    Rectangle rect = new Rectangle(x,y,width,height);
    Insets insets = getBorderInsets(c);
    Rectangle compR = getComponentRect(rect, insets);
    int diff;
    switch (titlePosition) {
      case ABOVE_TOP:
        diff = compR.height + TEXT_SPACING;
        borderR.y += diff;
        borderR.height -= diff;
        break;
      case TOP:
      case DEFAULT_POSITION:
        diff = insets.top/2 - borderInsets.top - EDGE_SPACING;
        borderR.y += diff;
        borderR.height -= diff;
        break;
      case BELOW_TOP:
      case ABOVE_BOTTOM:
        break;
      case BOTTOM:
        diff = insets.bottom/2 - borderInsets.bottom - EDGE_SPACING;
        borderR.height -= diff;
        break;
      case BELOW_BOTTOM:
        diff = compR.height + TEXT_SPACING;
        borderR.height -= diff;
        break;
    }
    border.paintBorder(c, g, borderR.x,     borderR.y, 
                             borderR.width, borderR.height);    
    Color col = g.getColor();
    g.setColor(c.getBackground());
    g.fillRect(compR.x, compR.y, compR.width, compR.height);
    g.setColor(col);
    component.repaint();
  }
   
  public Insets getBorderInsets(Component c, Insets insets) {
    Insets borderInsets;
    if (border != null) {
      borderInsets  = border.getBorderInsets(c);
    } else {
      borderInsets  = new Insets(0,0,0,0);
    }
    insets.top    = EDGE_SPACING + TEXT_SPACING + borderInsets.top;
    insets.right  = EDGE_SPACING + TEXT_SPACING + borderInsets.right;
    insets.bottom = EDGE_SPACING + TEXT_SPACING + borderInsets.bottom;
    insets.left   = EDGE_SPACING + TEXT_SPACING + borderInsets.left;
 
    if (c == null || component == null) {
      return insets;
    }
 
    int compHeight = 0;
    if (component != null) {
      compHeight = component.getPreferredSize().height;
    }
 
    switch (titlePosition) {
      case ABOVE_TOP:
        insets.top    += compHeight + TEXT_SPACING;
        break;
      case TOP:
      case DEFAULT_POSITION:
        insets.top    += Math.max(compHeight,borderInsets.top) - borderInsets.top;
        break;
      case BELOW_TOP:
        insets.top    += compHeight + TEXT_SPACING;
        break;
      case ABOVE_BOTTOM:
        insets.bottom += compHeight + TEXT_SPACING;
        break;
      case BOTTOM:
        insets.bottom += Math.max(compHeight,borderInsets.bottom) - borderInsets.bottom;
        break;
      case BELOW_BOTTOM:
        insets.bottom += compHeight + TEXT_SPACING;
        break;
    }
    return insets;
  }
  
  public JComponent getTitleComponent() {
    return component;
  }
  
  public void setTitleComponent(JComponent component) {
    this.component = component;
  }
  
  
  public Rectangle getComponentRect(Rectangle rect,Insets borderInsets) {
    Dimension compD = component.getPreferredSize();
    Rectangle compR = new Rectangle(0,0,compD.width,compD.height);
    switch (titlePosition) {
      case ABOVE_TOP:
        compR.y = EDGE_SPACING;
        break;
      case TOP:
      case DEFAULT_POSITION:
        compR.y = EDGE_SPACING + 
                 (borderInsets.top -EDGE_SPACING -TEXT_SPACING -compD.height)/2;
        break;
      case BELOW_TOP:
        compR.y = borderInsets.top - compD.height - TEXT_SPACING;
        break;
      case ABOVE_BOTTOM:
        compR.y = rect.height - borderInsets.bottom + TEXT_SPACING;
        break;
      case BOTTOM:
        compR.y = rect.height - borderInsets.bottom + TEXT_SPACING +
                 (borderInsets.bottom -EDGE_SPACING -TEXT_SPACING -compD.height)/2;
        break;
      case BELOW_BOTTOM:
        compR.y = rect.height - compD.height - EDGE_SPACING;
        break;
    }
    switch (titleJustification) {
      case LEFT:
      case DEFAULT_JUSTIFICATION:
        compR.x = TEXT_INSET_H + borderInsets.left;
        break;
      case RIGHT:
        compR.x = rect.width - borderInsets.right -TEXT_INSET_H -compR.width;
        break;
      case CENTER:
        compR.x = (rect.width - compR.width) / 2;
        break;
    }
    return compR;
  }
 
}

Perform outline-dragging with JInternalFrame

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

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

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

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

Changing a JButton’s label

Use the method setText.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame {
   JList list; 
 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      // following objects are final because they are used
      // in a inner class
      final JTextField textfield = new JTextField(20); 
      final JButton button = new JButton("initial label");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            if (!textfield.getText().equals(""))
               button.setText(textfield.getText());
         }
      });
 
      getContentPane().add(textfield);
      getContentPane().add(button);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Getting an event when a JComboBox is about to appear/disappear

Since JDK1.4, you can add PopupMenuListeners to your JComboBox. This allows you to get the events popupMenuWillBecomeVisible and popupMenuWillBecomeInvisible. Another event is supposed to be thrown, for a popupMenuCanceled, but is not, due to a bug.

Now that you have the possibility to get an event when the JComboBox popup is about to appear, you can lazily populate it. So only when the user wants to change the value of a JComboBox, you fill it up.

Here’s a short example. Due to a bug related to the order in which getPreferredSize and popupMenuWillBecomeVisible are called, the size of the component is not the desired size. Click twice on the JComboBox to see the desired size.

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
 
      final JComboBox combobox = new JComboBox(new Object[] {"Default Item"});
      getContentPane().add(combobox);
 
      combobox.addPopupMenuListener(new PopupMenuListener() {
         public void popupMenuCanceled(PopupMenuEvent e) {
            System.out.println("popupMenu canceled");
         }
         public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            System.out.println("popupMenu will become invisible");
         }
         public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            if (combobox.getModel().getSize() <= 1) {
               // lazily populate combobox
               for (int i=0; i<100; i++) {
                  combobox.insertItemAt("Item #" + i, 0);
               }
               combobox.validate();
            }
            System.out.println("popupMenu will become visible");
         }
      });  
 
      setSize(300, 300);
   }
 
   public static void main(String[] args) {
      (new Main()).setVisible(true);
   }
}

Creating a background for a JList

Here’s an example:

import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main {
   public static void main(String args[]) {
      JFrame frame = new JFrame("JList Background Demonstration");
      final ImageIcon imageIcon = new ImageIcon("bg1.jpg");
 
      Vector v = new Vector();
      for (int i=0; i<10; i++) {
         v.addElement("Item #" + i);
      }
 
      JList list = new JList(v) {
         Image image = imageIcon.getImage();
         { 
            setOpaque(false);
         }
         public void paintComponent(Graphics g) {
            g.drawImage(image, 0, 0, this);
            super.paintComponent(g);
         }
      };
      list.setCellRenderer(new OpaqueCellRenderer());
      
      frame.getContentPane().add(BorderLayout.CENTER, list); //new JScrollPane(list));
      frame.setDefaultCloseOperation(3);
      frame.pack();
      frame.setVisible(true);
   }
}
 
class OpaqueCellRenderer extends DefaultListCellRenderer implements ListCellRenderer {
   public Component getListCellRendererComponent(
      JList list,
      Object value,            // value to display
      int index,               // cell index
      boolean isSelected,      // is the cell selected
      boolean cellHasFocus)    // the list and the cell have the focus
   {
      Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
 
      if (isSelected) {
         ((JComponent) c).setOpaque(true);
         c.setBackground(list.getSelectionBackground());
         c.setForeground(list.getSelectionForeground());
      }
      else {
         ((JComponent) c).setOpaque(false);
         c.setBackground(list.getBackground());
         c.setForeground(list.getForeground());
      }
 
      return c;
   }
}

bg1.jpg:

Aligning a ‘Help’ JMenu component to the right side of the JMenuBar

JMenuBar has a method called setHelpMenu but you’ll get a runtime error when you try to use it. A workaround is to use Box.createHorizontalGlue to create the necessary empty space between the last left-aligned menu and the help menu. For more information about BoxLayout and its static methods, check out the link below.

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 {
   public Main() {
      JMenu fileMenu = new JMenu("File");
      fileMenu.add(new JMenuItem("Open"));
      fileMenu.add(new JMenuItem("Save"));
 
      JMenu helpMenu = new JMenu("Help");
      helpMenu.add(new JMenuItem("Help Topics"));
      helpMenu.add(new JSeparator());
      helpMenu.add(new JMenuItem("About"));
 
      JMenuBar mb = new JMenuBar();
      mb.add(fileMenu);
      // following line of code gives a runtime exception:
      //        "setHelpMenu() not yet implemented"
      //mb.setHelpMenu(helpMenu);
 
      // workaround:
      mb.add(Box.createHorizontalGlue());
      mb.add(helpMenu);
      
      this.setJMenuBar(mb);
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
} 

Automatically transferring the focus when a JTextField column limit has been reached

You can do so by extending JTextField to catch every insertion and checking whether the limit has been reached. If so, you can use transferFocus to have the focus jumpt to the next component.

Main.java:

import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      getContentPane().add(new AutoFocusTextField("Try typing more", 15, 20));
      getContentPane().add(new AutoFocusTextField(10, 3));
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(300, 300);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}
 
class AutoFocusTextField extends JTextField
{
   private int maxCols = 0;
 
   public AutoFocusTextField(int maxCols) {
      super();
      this.maxCols = maxCols;
   }
 
   public AutoFocusTextField(int cols, int maxCols) {
      super(cols);
      this.maxCols = maxCols;
   }
  
   public AutoFocusTextField(String text, int maxCols) {
      super();
      this.maxCols = maxCols;
      setText(text);
   } 
 
   public AutoFocusTextField(String text, int cols, int maxCols) {
      super(cols);
      this.maxCols = maxCols;
      setText(text);
   }
 
   protected Document createDefaultModel() {
      return new AutoFocusDocument();
   }
  
   protected class AutoFocusDocument extends PlainDocument {
      public void insertString(int offset, String str, AttributeSet as) 
            throws BadLocationException  {
         if (str == null || getLength() + str.length() <= maxCols) {
            super.insertString(offset, str, as);
            if (offset == maxCols-1) {
               transferFocus();
            }
         }
         else {
            int remainder = maxCols - getLength();
            if (remainder > 0) {
               super.insertString(offset, str.substring(0, remainder), as);
            }
            transferFocus();
         }
      }
   }
}

Catching events when the mouse moves over a JLabel

You can add a MouseMotionListener for mouse movements or a MouseListener for other interesting mouse events. This example shows how to invert the color of the JLabel when the mouse is positioned over it.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      final JLabel label = new JLabel("Move your mouse over this JLabel!");
      label.setOpaque(true);
      getContentPane().add(label);  
 
      label.addMouseMotionListener(new MouseMotionAdapter() {
         public void mouseMoved(MouseEvent me) {
            System.out.println("Mouse is being moved over JLabel");
         }
      });
 
      label.addMouseListener(new MouseAdapter() {
         public void mouseEntered(MouseEvent evt) {
            Color c = label.getBackground();
            label.setBackground(label.getForeground());
            label.setForeground(c);
         }
 
         public final void mouseExited(MouseEvent evt) { 
            Color c = label.getBackground();
            label.setBackground(label.getForeground());
            label.setForeground(c);            
         } 
         
         public final void mouseClicked(MouseEvent evt) { 
            System.err.println("Mouse has been clicked on JLabel"); 
         } 
      }); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(300, 200);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Setting the width of a JTable column

you should do something like this:

   TableColumn column=jTable1.getColumnModel().getColumn(1);
   column.setMinWidth(0);
   column.setMaxWidth(300);
   column.setPreferredWidth(15);

Setting

column.setMinWidth(0);
column.setMaxWidth(300);

is not nessesary, but you’ll be sure that desired width fits in this range.

Creating a JTable with row headers

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



import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
 
 
/**
 * @version 1.0 11/09/98
 */
  
class RowHeaderRenderer extends JLabel implements ListCellRenderer {
   
  RowHeaderRenderer(JTable table) {
    JTableHeader header = table.getTableHeader();
    setOpaque(true);
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    setHorizontalAlignment(CENTER);
    setForeground(header.getForeground());
    setBackground(header.getBackground());
    setFont(header.getFont());
  }
  
  public Component getListCellRendererComponent( JList list, 
         Object value, int index, boolean isSelected, boolean cellHasFocus) {
    setText((value == null) ? "" : value.toString());
    return this;
  }
}
 
public class RowHeaderExample extends JFrame {
 
  public RowHeaderExample() {
    super( "Row Header Example" );
    setSize( 300, 150 );
        
    ListModel lm = new AbstractListModel() {
      String headers[] = {"a", "b", "c", "d", "e", "f", "g", "h", "i"};
      public int getSize() { return headers.length; }
      public Object getElementAt(int index) {
        return headers[index];
      }
    };
 
    DefaultTableModel dm = new DefaultTableModel(lm.getSize(),10);
    JTable table = new JTable( dm );
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    
    JList rowHeader = new JList(lm);    
    rowHeader.setFixedCellWidth(50);
    
    rowHeader.setFixedCellHeight(table.getRowHeight()
                               + table.getRowMargin());
//                             + table.getIntercellSpacing().height);
    rowHeader.setCellRenderer(new RowHeaderRenderer(table));
 
    JScrollPane scroll = new JScrollPane( table );
    scroll.setRowHeaderView(rowHeader);
    getContentPane().add(scroll, BorderLayout.CENTER);
  }
 
  public static void main(String[] args) {
    RowHeaderExample frame = new RowHeaderExample();
    frame.addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent e ) {
        System.exit(0);
      }
    });
    frame.setVisible(true);
  }
}