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

Iconifying or deiconinfying a JFrame

Use setState(Frame.ICONIFIED) and setState(Frame.NORMAL).

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame implements ActionListener
{
   public Main()
   {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      JButton iconButton = new JButton("Iconify this Frame");
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
      getContentPane().add(iconButton);
      iconButton.addActionListener(this);
   }
 
   public void actionPerformed(ActionEvent ae) {     
      this.setState(Frame.ICONIFIED);  
   }
 
   public static void main(String args[])
   {
      Main main = new Main();
      main.setSize(300, 150);
      main.setVisible(true);
   }
}

Force the JScrollPane to scroll to the next JTextField when I press the TAB-Key

There are three steps to this:

1. Listen for focus events coming from the components that you want to scroll to. (This works for most component classes, not just JTextField.)

2. In the event listener, find the location of the component that now has focus with getBounds().

3. Ask the scrolled component to make that location visible with scrollRectToVisible(). NOTE! The obvious thing to call scrollRectToVisible on is the JScrollPane, which will compile fine but won’t do what you want. You must call scrollRectToVisible on the object contained in viewport of the scrollpane.

This Forte-generated example shows how this works for a simple panel containing a number of JTextFields. Notice that scrollRectToVisible is called on the JPanel containing the text fields.

TestFocus.java:

public class TestFocus extends javax.swing.JFrame {
 
    /** Creates new form TestFocus */
    public TestFocus() {
        initComponents();
    }
 
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {
        scrollPane = new javax.swing.JScrollPane();
        panel = new javax.swing.JPanel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jTextField4 = new javax.swing.JTextField();
         
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });
        
        scrollPane.setPreferredSize(new java.awt.Dimension(120, 80));
        panel.setLayout(new java.awt.GridLayout(0, 1, 0, 15));
        
        jTextField1.setFont(new java.awt.Font("Dialog", 0, 18));
        jTextField1.setText("jTextField1");
        jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextFieldFocusGained(evt);
            }
        });
         
        panel.add(jTextField1);
        
        jTextField2.setFont(new java.awt.Font("Dialog", 0, 18));
        jTextField2.setText("jTextField2");
        jTextField2.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextFieldFocusGained(evt);
            }
        });
        
        panel.add(jTextField2);
        
        jTextField3.setFont(new java.awt.Font("Dialog", 0, 18));
        jTextField3.setText("jTextField3");
        jTextField3.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextFieldFocusGained(evt);
            }
        });
        
        panel.add(jTextField3);
        
        jTextField4.setFont(new java.awt.Font("Dialog", 0, 18));
        jTextField4.setText("jTextField4");
        jTextField4.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextFieldFocusGained(evt);
            }
        });
        
        panel.add(jTextField4);
        
        scrollPane.setViewportView(panel);
        
        getContentPane().add(scrollPane, java.awt.BorderLayout.CENTER);
        
        pack();
    }
 
    private void jTextFieldFocusGained(java.awt.event.FocusEvent evt) {
        java.awt.Component focusedComponent = evt.getComponent();
        panel.scrollRectToVisible(focusedComponent.getBounds(null));
        repaint();
    }
 
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
        System.exit(0);
    }
 
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        new TestFocus().show();
    }
 
    // Variables declaration - do not modify
    private javax.swing.JScrollPane scrollPane;
    private javax.swing.JPanel panel;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    // End of variables declaration

}

If your panel of components contains a JTextArea, or another JTextComponent subclass, then be aware that those components will absorb TABs into themselves instead of allowing the TAB to change focus. You can disable this behavior by creating a subclass that overrides isManagingFocus() to always return false.

Adding a background image to a JToolBar

Override the JToolBar’s method paintComponent, draw the image using g.drawImage and call the superclass’ paintComponent. This is similar to the JPanel implementation.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
 
   public static void main(String []args) {
      Main main = new Main();
      main.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent ev) {
            System.exit(0);
         }
      });
 
      main.pack();
      main.show(); 
   }
 
   private ImageIcon ii = new ImageIcon("mong.jpg");
 
   public Main() {
      super("ToolBar Background Image");
 
      getContentPane().setLayout(new BorderLayout());
 
      //
      // could also use an anonymous class...e.g.,
      // JToolBar toolbar = new JToolBar() {
      //     public void paintComponent(Graphics g) {
      //         ... see Class below...
      //     }
      // };
      //
      JToolBar toolbar = new ToolBarWithBgImage("My Toolbar", JToolBar.HORIZONTAL, ii);
      getContentPane().add(toolbar, BorderLayout.NORTH);
 
      toolbar.add(new JButton("Item 1"));
      toolbar.add(new JButton("Item 2"));
      toolbar.addSeparator();
      toolbar.add(new JButton("Item 3"));  
   }
 
   /**
    * This implementation stretches the image to fit the panel.
    * Could modify this to "tile" the image, center the image, etc.
    */
   class ToolBarWithBgImage extends JToolBar {
 
      private ImageIcon bgImage;
 
      ToolBarWithBgImage(String name, int orientation, ImageIcon ii) {
         super(name, orientation);
         this.bgImage = ii;
         setOpaque(true);
      }
 
      public void paintComponent(Graphics g) {
         super.paintComponent(g);
         if (bgImage != null) {
            Dimension size = this.getSize();
            g.drawImage(bgImage.getImage(), 0,0, size.width, size.height, this);
         }
      }
   }
}

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

Implementing a mouseover effect with a JButton

Add a MouseListener to your JButton and code the desired behaviour in mouseEntered and mouseExited.
This example makes the JButton’s label red when mouse-moving over it.

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 JButton button = new JButton(&quot;OK!&quot;);
      button.addMouseListener(new MouseAdapter() {
         Color oldcolor = button.getForeground();
         public void mouseEntered(MouseEvent me) {
            oldcolor = button.getForeground();
            button.setForeground(Color.red); 
         }
         public void mouseExited(MouseEvent me) {
            button.setForeground(oldcolor);
         }
      });
 
      getContentPane().add(button);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

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

Displaying animated GIFs in a JList

Try this example with the following two images:

import javax.swing.border.*;
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 Background Demonstration");
 
      JList list = new JList();
 
      String [] imageIcon = new String[] {
         "female.gif", "male.gif"
      };
 
      // create model
      Vector v = new Vector();
      for (int i=0; i<10; i++) {
         ImageIcon ii = new ImageIcon(imageIcon[i % 2]);
         ii.setImageObserver(new AnimatedObserver(list, i));
         v.addElement(ii);
      }
 
      list.setListData(v);
  
      frame.getContentPane().add(BorderLayout.CENTER, list); //new JScrollPane(list));
      frame.setDefaultCloseOperation(3);
      frame.pack();
      frame.setVisible(true);
   }
}
 
class AnimatedObserver implements ImageObserver 
{ 
   JList list; 
   int index; 
 
   public AnimatedObserver(JList list, int index) { 
      this.list = list; 
      this.index = index; 
   }  
 
   public boolean imageUpdate (Image img, int infoflags, int x, int y, int width, int height) {
      if ((infoflags & (FRAMEBITS|ALLBITS)) != 0) { 
         Rectangle rect = list.getCellBounds(index, index); 
         list.repaint(rect); 
      } 
 
      return (infoflags & (ALLBITS|ABORT)) == 0; 
   }
} 

Dynamically removing a separator from a JMenu

Look in the JMenu API for the remove methods!

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();
      // used in inner class, so final
      final JMenu menu = new JMenu("Sex");
      JMenuItem menuItem0 = new JMenuItem("female");
      JMenuItem menuItem1 = new JMenuItem("male");
      JMenuItem menuItem2 = new JMenuItem("androgyn");
 
      // add the MenuItems to the Menu 
      menu.add(menuItem0);
      menu.add(menuItem1);
 
      // used in inner class, so final
      final JSeparator jsep = new JSeparator();
      menu.add(jsep);
      menu.add(menuItem2);
   
      menuBar.add(menu);
 
      this.setJMenuBar(menuBar); 
      final JButton button = new JButton("remove menu separator");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            menu.remove(jsep);
            button.setEnabled(false);
         }
      });
      getContentPane().add(button);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}