Custom JComboBox -- MouseListener

Hi. I'm in the process of making a custom JComboBox (called TitledComboBox).
It's going to use a ComboBox as the component that is always visible, but when you click it instead of the standard dropdown, I'm creating a JPopupMenu to replace that. That way I want to avoid the first element (or the selected one) being repeated inside the list.
So I've created my class extending JComboBox, and implemented MouseListener, but I'm unable to make the listener work for the JComboBox layout manager. It works perfectly for the spots on the JComboBox where the LayoutManager doesnt paint (or whatever it does), so the "arrow" doesn't effect the MouseListener....
How can I extend the default JComboBox LayoutManager to have the same MouseListener??

package gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
@SuppressWarnings("serial")
public class TitledComboBox extends JComboBox implements MouseListener
    @SuppressWarnings("serial")
    private class PopItem extends JMenuItem
         public PopItem(String text)
            setLayout(null);
            setText(text);
            setOpaque(false);
            setBackground(Color.BLACK);
        public void paint(Graphics g)
            super.paint(g);
    @SuppressWarnings("serial")
    private class PopMenu extends JPopupMenu
          public PopMenu()
               this.setLayout(null);
               this.setPopupSize(120, 23*this.getComponentCount());
               this.setOpaque(false);
          public PopMenu(String[] items)
               this();
               for(int i = 0; i < items.length; i++)
                    this.add(new PopItem(items));
               updateSize();
          private void updateSize()
               this.setPopupSize(120, 23*this.getComponentCount());
          public void show(Component arg0, int arg1, int arg2)
               super.show(arg0, arg1, arg2);
               this.setVisible(true);
          public void paint(Graphics g)
               super.paint(g);
     public PopMenu dropdown;
     private TitledComboBox()
          super();
          this.addMouseListener(this);
          this.setVisible(true);
this.setEnabled(false);
     public TitledComboBox(String title)
          this();
          this.addItem(title);
          dropdown = new PopMenu();
     public TitledComboBox(String title, String[] items)
          this();
          this.addItem(title);
          dropdown = new PopMenu(items);
     public void addPopItem(String item)
          dropdown.add(new PopItem(item));
          dropdown.updateSize();
     public void removePopItem(int itemIndex)
          dropdown.remove(itemIndex);
          dropdown.updateSize();
     public void paint(Graphics g)
          this.setEnabled(true);
          super.paint(g);
          this.setEnabled(false);
     public void mouseClicked(MouseEvent m)
dropdown.show(this, 0, 20);
     public void mouseEntered(MouseEvent arg0)
     public void mouseExited(MouseEvent arg0)
     public void mousePressed(MouseEvent arg0)
     public void mouseReleased(MouseEvent arg0)
Using this now gives something very similar to a JComboBox, just without the top element showing. However, I STILL don't know how to get the LayoutManager to be a part of the MouseListener... Please help!
Edited by: Ondkloss on Nov 21, 2007 7:12 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • Customized JComboBox Editor for JTable

    Hi,
    I am new to swing development and have gotten my self stuck on an issue. Basically I have a JTable that is dynamically populated from the database, in which one of the columns has a customized JComboBox Renderer and Editor. The default values load up fine when the page loads up but when I selected a new value in the combo box and select a new row in the JTable, the combo box defaults back to the original value. How can I make sure that the new selection is maintain.
    Thanks, Anthony
    Here are my Driver, Renderer and Editor:
    excerpts from the Driver
    contract.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    keys = contractSelectedEvent.getKeys();
    String sql = contractSelectedEvent.getSchdSql(keys);
    table = contractSelectedEvent.getStatusTable(sql);
    table.setDefaultRenderer(CashFlow.class, new CashFlowRenderer());
    table.setDefaultEditor(CashFlow.class, new CashFlowEditor());
    public class CashFlowRenderer extends JComboBox implements TableCellRenderer {
    protected QueryComboBoxModel comboModel;
    /** Creates a new instance of CashFlowRenderer */
    public CashFlowRenderer() {
    super();
    comboModel = new QueryComboBoxModel("Select Ref_ID, Ref_Desc From Ref Where
    Ref_Typ_ID = 910 order by Ref_ID ");
    super.setModel(comboModel);
    public java.awt.Component getTableCellRendererComponent(javax.swing.JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus,
    int row,
    int column) {
    if(value == null) {
    return this;
    if(value instanceof CashFlow) {
    //set the cashflow equal to the value
    CashFlow cashFlow = new CashFlow(((CashFlow) value).getCashFlow());
    setSelectedItem(cashFlow);
    else {
    //default the cashflow
    CashFlow cashFlow = new CashFlow();
    setSelectedItem(cashFlow.getCashFlow());
    return this;
    public boolean isCellEditable() {
    return true;
    public class CashFlowEditor extends JComboBox implements TableCellEditor {
    protected transient Vector listeners;
    protected transient String originalValue;
    protected QueryComboBoxModel comboModel;
    /** Creates new CashFlowEditor */
    public CashFlowEditor() {
    super();
    comboModel = new QueryComboBoxModel("Select Ref_ID, Ref_Desc From Ref Where Ref_Typ_ID = 910 order by Ref_ID ");
    super.setModel(comboModel);
    listeners = new Vector();
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    if(value == null) {
    return this;
    if (value instanceof CashFlow) {
    setSelectedItem(((CashFlow)value).getCashFlow());
    else {
    CashFlow cashFlow = new CashFlow();
    setSelectedItem(cashFlow.getCashFlow());
    table.setRowSelectionInterval(row, row);
    table.setColumnSelectionInterval(column, column);
    originalValue = (String) getSelectedItem();
    return this;
    public void cancelCellEditing() {
    fireEditingCanceled();
    public Object getCellEditorValue() {
    return (String)getSelectedItem();
    public boolean isCellEditable(EventObject eo) {
    return true;
    public boolean shouldSelectCell(EventObject eo) {
    return true;
    public boolean stopCellEditing() {
    CashFlow cashflow = new CashFlow((String)getSelectedItem());
    setSelectedItem(cashflow.getCashFlow());
    fireEditingStopped();
    return true;
    public void addCellEditorListener(CellEditorListener cel) {
    listeners.addElement(cel);
    public void removeCellEditorListener(CellEditorListener cel) {
    listeners.removeElement(cel);
    protected void fireEditingCanceled() {
    setSelectedItem(originalValue);
    ChangeEvent ce = new ChangeEvent(this);
    for(int i = listeners.size(); i >= 0; i--) {
    ((CellEditorListener)listeners.elementAt(i)).editingCanceled(ce);
    protected void fireEditingStopped() {
    ChangeEvent ce = new ChangeEvent(this);
    for(int i = listeners.size() - 1; i >= 0; i--) {
    ((CellEditorListener)listeners.elementAt(i)).editingStopped(ce);

    First off, I wouldn't subclass JComboBox to create a custom renderer/editor. I would have a renderer/editor component that makes use of a JComboBox. But that is just me.
    In order for setSelectedItem to work, the items in your combo box have to compare against each other correctly with equals(). Since you are creating new instances, your objects (even though they contain the same data) are going to be different instances and aren't going to be considered equal. Write your own equals() method in your CashFlow object that tests for equality based on the actual values in the objects and you should be fine.

  • Custom JComboBox

    Hello,
    I am attempting to customize some aspects of the JComboBox, but I am having problem changing the way it looks. I can't seem to change the way the arrow button acts. For example I have a custom button that uses a raised bevel border when no pressed and a lowered bevel border when pressed. When I place a button such as this one in place of the combo box's original button, the border does not change when clicked. Its almost like the BasicComboBoxUI is removing all of my button's listeners. Does anyone know what the problem might be?
    Thanks for any help.
    package KComponent;
    import javax.swing.JButton;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    public class KMouseOverComboBoxButton extends KButton implements MouseListener {
      private Color color;
      private Border border;
      private Border highlight;
      private Border noHighlight;
      protected boolean drawBorder = false;
      public KMouseOverComboBoxButton(Color color, Color bg, Border highlight, Border noHighlight) {
        //super(new KComboIcon(color));
        super("v", color, color, color);
        this.color = color;
        setBackground(bg);
        addMouseListener(this);
        // it seems to ignore all of my calls to setBorder because the border does not change
        setBorder(null);
        border = getBorder();
      public void setBorder(Border b) {
        super.setBorder(BorderFactory.createCompoundBorder(border, noHighlight));
        border = b;
      public void mouseClicked(MouseEvent e) {}
      public void mousePressed(MouseEvent e) {}
      public void mouseDragged(MouseEvent e) {}
      public void mouseReleased(MouseEvent e) {}
      public void mouseEntered(MouseEvent e) {
        super.setBorder(null);
        super.setBorder(BorderFactory.createCompoundBorder(border, highlight));
      public void mouseExited(MouseEvent e) {
        super.setBorder(null);
        super.setBorder(BorderFactory.createCompoundBorder(border, noHighlight));
    class KComboIcon implements Icon {
      private static final int HEIGHT = 5;
      private static final int WIDTH = 10;
      private static final int MARGIN = 2;
      private Color color;
      public KComboIcon(Color color) {
        this.color = color;
      public void paintIcon(Component c, Graphics g, int x, int y) {
        g.setColor(color);
        Polygon poly = new Polygon();
        poly.addPoint(MARGIN, HEIGHT/2);
        poly.addPoint(WIDTH/2, HEIGHT-MARGIN);
        poly.addPoint(WIDTH-MARGIN, HEIGHT/2);
        poly.addPoint(WIDTH-MARGIN, HEIGHT/2-3);
        poly.addPoint(WIDTH/2, HEIGHT-MARGIN-3);
        poly.addPoint(MARGIN, HEIGHT/2-3);
        g.fillPolygon(poly);
      public int getIconHeight() {
        return HEIGHT;
      public int getIconWidth() {
        return WIDTH;

    I am trying to set my combo box's border to an empty border and it is not working. Help!
    comboBox.setBorder(BorderFactory.createEmptyBorder());
    Also,
    UIManager.put(ComboBox.border, BorderFactory.createEmptyBorder());
    doesn't work either.
    Thanks.
    - Berni.

  • JComboBox MouseListener Problem

    Hi!
    I have problem in getting mouseEntered event from a JComboBox. I have registered a MouseListener with it but it doesn't fire any mouseEvent. Anyone has any idea how to get the mouseEntered Event fired from a JComboBox??
    Thanks!!

    Even I, have a similar problem. My obejective is to display the tooltip, When I move the mouse over every individual item in the combo box. The combo basically has a JList. So, I overrided the getListCellRenderer(...) method. It is not displaying the toolTip when the combo initially has no selectedItem. If there is a selected item, the first time itslef, it displays the toolTip. If theres no selectedItem, it displays the toolTip when I move the mouse out of the combo(when the combo is expanded). Tried all possible combinations... but doesnt work. Have set the toolTip with setToolTipText() method... and when I print the toolTip with getToolTipText() method. It prints correctly, but isnt getting displayed.. :-(

  • JComboBox MouseListener

    Hi guys,
    I am facing a weird problem while using an JComboBox.
    I've got an JPanel to which I am adding a JComboBox, and when I try to set its border on the MouseListener event class:
    public void mouseEntered(MouseEvent e)
            ((JComponent)e.getSource()).setBorder(Color.Blue, 1);
    }The comboBox changes its location, I mean the Jpanel where it was added moves its location to the top/east location in th JFrame.
    But If I do this:
    myObjCbo.getComponent(0).addMouseListener(myMouseListerner);
    myObjCbo.getComponent(1).addMouseListener(myMouseListerner);
    myObjCbo.getComponent(2).addMouseListener(myMouseListerner);
    BorderlessTextField
    CellRenderedPane
    BasicArrowPaneIt sort of works... and its position is not changed anymore.
    Is this behaviour normal??
    Thanks,
    MeTitus

    I just found what the problem is.
    Back in the work I am using Xp and I enable L&F, now I am trying the program at home in my linux box and I'm getting this stack trace:
    (<unknown>:9292): Gtk-WARNING **: Attempting to add a widget with type GtkButton to a GtkComboBoxEntry (need an instance of GtkEntry or of a subclass)
    (<unknown>:9292): Gtk-CRITICAL **: gtk_widget_realize: assertion `GTK_WIDGET_ANCHORED (widget) || GTK_IS_INVISIBLE (widget)' failed
    (<unknown>:9292): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:9292): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:9292): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:9292): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failedAnd simple things like changing the background of a component fail to work. I disabled L&F and the problem I was getting with the component changing its location when using setBorder now works properly.
    So enabling L&F both in windows and linux have problems. Do you guys experience any problems when using L&F at all??
    Thanks,
    MeTitus

  • Custom JComboBox Renderer

    Hi!
    I want to use a JMenu as a renderer for a JComboBox. When the combo is pressed, the popup that is open should contain 3 JMenu. Then if the mouse id moved over any of the 3 JMenu, 2 check menu items should be opened in an additional popup, near the popup that contains the 3 JMenu.
    A picture that illustrate the behaviour could be found here: [http://www.trilulilu.ro/mogadiscio/ee847e6a14b2d5]
    I'm able to obtain the 3 JMenus in the combo's popup but the 3 JMenus does not repond to mouse events so the additional submenu is not open.
    Any suggestions are welcome.
    Orly

    package supercombo;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.util.ArrayList;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.DefaultListCellRenderer;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JMenu;
    import javax.swing.JToolBar;
    import javax.swing.SwingConstants;
    public class SuperCombo6 extends JComboBox {
        public static void main(String[] args) {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(500, 300);
            frame.setTitle("Super Combo 6");
            JToolBar tb = new JToolBar();
            tb.setLayout(new FlowLayout(FlowLayout.LEFT));
            tb.add(new SuperCombo6(new String[][] {
                    {"M1", "M1.1", "M1.2"},
                    {"M2", "M2.1", "M2.2"},
                    {"M3", "M3.1", "M3.2"}
            frame.getContentPane().setLayout(new BorderLayout());
            frame.getContentPane().add(tb, BorderLayout.NORTH);
            frame.setVisible(true);
        public SuperCombo6(String[][] items) {
            super(new SuperComboModel6(items.length));
            setPreferredSize(new Dimension(120, 20));
            setRenderer(new SuperComboRenderer6(items, this));
    class SuperComboModel6 extends DefaultComboBoxModel {
        private int _size;
        public SuperComboModel6(int size) {
            this._size = size;
        public int getSize() {
            return _size;
    class SuperComboRenderer6 extends DefaultListCellRenderer {
        private JLabel title;
        private ArrayList menus;
        public SuperComboRenderer6(String[][] items, final JComboBox combo) {
            title = new JLabel("SuperCombo6");
            title.setHorizontalAlignment(SwingConstants.LEFT);
            menus = new ArrayList();
            for (int i = 0; i < items.length; i++) {
                final JMenu menu = new JMenu(items[0]);
    for (int j = 1; j < items[i].length; j++) {
    JCheckBoxMenuItem item = new JCheckBoxMenuItem(items[i][j]);
    menu.add(item);
    menus.add(menu);
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
    if (index == -1) {
    return title;
    JMenu menu = (JMenu) menus.get(index);
    if (isSelected) {
    menu.setSelected(true);
    } else {
    menu.setSelected(false);
    return menu;

  • Customizing JComboBox

    I am trying to develop my own look and feel for my application.
    How do I go about customizing the drop down button on a comboBox?
    Thanks
    Adam

    you start off setting your own UI with an extended BasicComboBoxUI, and overriding
    createArrowButton()
    which returns a
    new BasicArrowButton()
    you can do some things with the instance of BasicArrowButton, or you can return
    your own extended BasicArrowButton, where you can do other things

  • JComboBox custom editor and model

    I'd like to implement a custom JComboBox that uses application's arbitrary text field as its editor. Below is a first trial but it is dead on birth. Specifically, two action listeners for the text field do not work let alone do accumulating edited items on the combo box. What could be my foolish errors?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import javax.swing.plaf.metal.MetalComboBoxEditor;
    public class EditableComboBox extends JComboBox{
      Vector<String> items;
      CustomComboBoxModel model;
      JTextField tfield;
      CustomComboBoxEditor editor;
      public EditableComboBox(Vector<String> vec, JTextField tf){
        items = vec;
        model = new CustomComboBoxModel(items);
        setModel(model);
        tfield = tf;
        editor = new CustomComboBoxEditor(tfield);
        setEditor(editor);
        setEditable(true);
        tfield.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e){
            handleEditedItem();
      void handleEditedItem(){
        String s = tfield.getText();
        if (s.length() > 0 && ! model.hasElement(s)){
          model.addElement(s); // add new element
      class CustomComboBoxModel extends DefaultComboBoxModel{
        public CustomComboBoxModel(Vector<String> vec){
          super(vec);
        // like to add it to head, not to tail
        public void addElement(Object o){
          insertElementAt(o, 0);
        public boolean hasElement(Object o){
          int size = getSize();
          int idx = getIndexOf(o);
          return (idx > -1 && idx < size);
      class CustomComboBoxEditor extends MetalComboBoxEditor{
        JTextField tfield;
        public CustomComboBoxEditor(JTextField t){
          tfield = t;
        public JTextField createEditorComponent(){
          return tfield;
      public static void main(String[] args){
        final JTextField jtf = new JTextField(80);
        Vector<String> vs = new Vector<String>();
        EditableComboBox ecb = new EditableComboBox(vs, jtf);
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(ecb, BorderLayout.NORTH);
        jtf.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e){
            System.out.println(jtf.getText());
        frame.pack();
        frame.setVisible(true);
    }Edited by: hiwa on Sep 28, 2007 3:08 PM

    This is the final or provisional production version based on Michael's first solution. I find the class is much more useful when the handleEditedItem() method can be called from the application because the application can control the behavior.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class JTextFieldWithMemory extends JComboBox{
      Vector<String> items;
      CustomComboBoxModel model;
      JTextField tfield;
      int columns;
      /* constructor for a special usage, this obj calls handleEditedElement() */
      public JTextFieldWithMemory(Vector<String> vec, int cs, boolean handleEdit){
        items = vec;
        columns = cs;
        model = new CustomComboBoxModel(items);
        setModel(model);
        setEditable(true);
        tfield = (JTextField)getEditor().getEditorComponent();
        if (cs > 0){
          tfield.setColumns(columns);
        if (handleEdit){ // automatic self accumulation
          tfield.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
              handleEditedItem();
      /* ordinary usage constructor, application calls handleEditedElement() */
      public JTextFieldWithMemory(Vector<String> vec, int cs){
        this(vec, cs, false);
      public JTextFieldWithMemory(Vector<String> vec){
        this(vec, 0);
      public JTextFieldWithMemory(){
        this(new Vector<String>(), 0);
      public JTextField getTextField(){
        return tfield;
      public String getText(){
        return tfield.getText();
      public void setText(String t){
        tfield.setText(t);
        handleEditedItem();
      public Vector<String> getItems(){
        return items;
      public void addActionListenerTf(ActionListener al){
        tfield.addActionListener(al);
      public void handleEditedItem(){
        String s = tfield.getText();
        if (s.length() > 0 && ! model.hasElement(s)){
          model.addElement(s); // add new element
        tfield.setText(s); // prevent blanking out
      class CustomComboBoxModel extends DefaultComboBoxModel{
        public CustomComboBoxModel(Vector<String> vec){
          super(vec);
        // like to add it to head, not to tail
        public void addElement(Object o){
          insertElementAt(o, 0);
        public boolean hasElement(Object o){
          int size = getSize();
          int idx = getIndexOf(o);
          return (idx > -1 && idx < size);
      /* main() for test */
      static JTextField jtf;
      static JTextFieldWithMemory tm;
      public static void main(String[] args){
        Vector<String> vs = new Vector<String>();
        tm = new JTextFieldWithMemory(vs, 30);
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(tm, BorderLayout.NORTH);
        jtf = (JTextField)tm.getEditor().getEditorComponent();
        jtf.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e){
            tm.handleEditedItem(); // called from app
            System.out.println(jtf.getText());
        frame.pack();
        frame.setVisible(true);
    }

  • JComboBox takes ages to load/refresh when tried to add more items.

    Swing gurus ...
    Here is the test app generated from VA3.5 concept is the
    same - JComboBox takes long time to add data items to itself when added more items.
    In this senario, I tried to load about 500 items into the combo box, takes about 2+ minutes to load. I have an app which needs to show about 1K items in the pick list ( ComboBox ) - which takes any where from 4 - 10 min - this is not acceptable - are there any ways we can load more items into combo box ? Help is really appreciated.
    Example:
    * Insert the type's description here.
    * Creation date: (6/28/2001 11:23:26 AM)
    * @author: Administrator
    public class ComboTest extends javax.swing.JFrame {
         private javax.swing.JPanel ivjJFrameContentPane = null;
         private javax.swing.JButton ivjLoadBtn = null;
         private javax.swing.JComboBox ivjTestCombo = null;
    * ComboTest constructor comment.
    public ComboTest() {
         super();
         initialize();
    * ComboTest constructor comment.
    * @param title java.lang.String
    public ComboTest(String title) {
         super(title);
    * connEtoC1: (LoadBtn.action.actionPerformed(java.awt.event.ActionEvent) --> ComboTest.loadBtn_ActionPerformed(Ljava.awt.event.ActionEvent;)V)
    * @param arg1 java.awt.event.ActionEvent
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void connEtoC1(java.awt.event.ActionEvent arg1) {
         try {
              // user code begin {1}
              // user code end
              this.loadBtn_ActionPerformed(arg1);
              // user code begin {2}
              // user code end
         } catch (java.lang.Throwable ivjExc) {
              // user code begin {3}
              // user code end
              handleException(ivjExc);
    * Return the JFrameContentPane property value.
    * @return javax.swing.JPanel
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private javax.swing.JPanel getJFrameContentPane() {
         if (ivjJFrameContentPane == null) {
              try {
                   ivjJFrameContentPane = new javax.swing.JPanel();
                   ivjJFrameContentPane.setName("JFrameContentPane");
                   ivjJFrameContentPane.setLayout(null);
                   getJFrameContentPane().add(getTestCombo(), getTestCombo().getName());
                   getJFrameContentPane().add(getLoadBtn(), getLoadBtn().getName());
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjJFrameContentPane;
    * Return the LoadBtn property value.
    * @return javax.swing.JButton
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private javax.swing.JButton getLoadBtn() {
         if (ivjLoadBtn == null) {
              try {
                   ivjLoadBtn = new javax.swing.JButton();
                   ivjLoadBtn.setName("LoadBtn");
                   ivjLoadBtn.setText("Load");
                   ivjLoadBtn.setBounds(248, 41, 85, 25);
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjLoadBtn;
    * Return the TestCombo property value.
    * @return javax.swing.JComboBox
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private javax.swing.JComboBox getTestCombo() {
         if (ivjTestCombo == null) {
              try {
                   ivjTestCombo = new javax.swing.JComboBox();
                   ivjTestCombo.setName("TestCombo");
                   ivjTestCombo.setDoubleBuffered(true);
                   ivjTestCombo.setBounds(78, 41, 164, 23);
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjTestCombo;
    * Called whenever the part throws an exception.
    * @param exception java.lang.Throwable
    private void handleException(java.lang.Throwable exception) {
         /* Uncomment the following lines to print uncaught exceptions to stdout */
         // System.out.println("--------- UNCAUGHT EXCEPTION ---------");
         // exception.printStackTrace(System.out);
    * Initializes connections
    * @exception java.lang.Exception The exception description.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initConnections() throws java.lang.Exception {
         // user code begin {1}
         // user code end
         getLoadBtn().addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent e) {
                   connEtoC1(e);
    * Initialize the class.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initialize() {
         try {
              // user code begin {1}
              // user code end
              setName("ComboTest");
              setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
              setSize(426, 131);
              setTitle("Test App");
              setContentPane(getJFrameContentPane());
              initConnections();
         } catch (java.lang.Throwable ivjExc) {
              handleException(ivjExc);
         // user code begin {2}
         // user code end
    * Comment
    public void loadBtn_ActionPerformed(java.awt.event.ActionEvent actionEvent)
         String val = "String Item: ";
         for ( int i=0; i<500; i++ )
              getTestCombo().addItem( val + i);
         return;
    * main entrypoint - starts the part when it is run as an application
    * @param args java.lang.String[]
    public static void main(java.lang.String[] args) {
         try {
              ComboTest aComboTest;
              aComboTest = new ComboTest();
              aComboTest.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
              aComboTest.show();
              java.awt.Insets insets = aComboTest.getInsets();
              aComboTest.setSize(aComboTest.getWidth() + insets.left + insets.right, aComboTest.getHeight() + insets.top + insets.bottom);
              aComboTest.setVisible(true);
         } catch (Throwable exception) {
              System.err.println("Exception occurred in main() of javax.swing.JFrame");
              exception.printStackTrace(System.out);

    The "Really fast combo boxes" thread referred to by lk555 can be summarized as follows:
    1. RegFish wrote a custom JComboBox that handles large numbers of elements better than a standard JComboBox does.
    2. You can download his code at http://www.reddfish.co.nz/freesoftware/PoliteComboBox.jar
    3. You may want to reconsider your design, since a JComboBox with more than a few dozen elements is usually too hard for the user to use (see various postings in the long thread).

  • Custom renderer (almost works)

    I'm creating a custom JComboBox renderer. What I want it to do is display text next to a colored box. Everything works except for the default value were its not showing the text. Anyone see the problem? Or is there a better way of doing this? I’ve included the code below:
    (Renderer Code: ComboBoxRenderer.java)
    import java.awt.*;
    import java.util.ArrayList;
    import javax.swing.*;
    class ComboBoxRenderer extends JLabel implements ListCellRenderer
        String[] _textLabels = {"Red", "Green", "Blue", "Orange", "Yellow", "Cyan"};
        private ArrayList _colors = null;
        private JPanel _coloredBox = null;
        private JPanel _container = null;
        private JLabel _label = null;
        public ComboBoxRenderer()
            setOpaque(true);
            setHorizontalAlignment(CENTER);
            setVerticalAlignment(CENTER);
            // Text container (can't get text to show without it being contained inside another jpanel. Why is this?)
            _container = new JPanel();
            Dimension holderSize = new Dimension(80, 20);
            _container.setLocation(22, 0);
            _container.setSize(holderSize);
            _container.setOpaque(false);
            _container.setLayout(new BorderLayout());
            this.add(_container, BorderLayout.WEST);
            // Text
            _label = new JLabel("Disabled");
            Dimension textSize = new Dimension(80, 20);
            _label.setForeground(Color.black);
            _label.setPreferredSize(textSize);
            _label.setHorizontalAlignment(JTextField.LEFT);
            _container.add(_label, BorderLayout.WEST);
            // Colored box
            _coloredBox = new JPanel();
            Dimension preferredSize = new Dimension(16, 16);
            _coloredBox.setLocation(2, 2);
            _coloredBox.setSize(preferredSize);
            _coloredBox.setOpaque(true);
            this.add(_coloredBox, BorderLayout.WEST);
            // Initialize color list
            _colors = new ArrayList();
            _colors.add(new Color(255, 0, 0));
            _colors.add(new Color(0, 255, 0));
            _colors.add(new Color(0, 0, 255));
            _colors.add(new Color(255, 215, 0));
            _colors.add(new Color(255, 255, 0));
            _colors.add(new Color(0, 255, 255));
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
            // Get the selected index.
            int selectedIndex = ((Integer)value).intValue();
            // Set the background color for each element
            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            // Set text
            String text = _textLabels[selectedIndex];
            _label.setText(text);
            _label.setFont(list.getFont());
            // Set box
            Color current = (Color) _colors.get(selectedIndex);
            _coloredBox.setBackground(current);
            return this;
    }(Main: CustomComboBoxDemo.java)
    import java.awt.*;
    import javax.swing.*;
    public class CustomComboBoxDemo extends JPanel
        public CustomComboBoxDemo()
            super(new BorderLayout());
            // Combo list
            Integer[] intArray = new Integer[6];
            for (int i = 0; i < 6; i++) intArray[i] = new Integer(i);
            // Create the combo box.
            JComboBox colorList = new JComboBox(intArray);
            ComboBoxRenderer renderer= new ComboBoxRenderer();
            renderer.setPreferredSize(new Dimension(120, 20));
            colorList.setRenderer(renderer);
            colorList.setMaximumRowCount(5);
            colorList.setSelectedIndex(2);
            // Lay out the demo.
            add(colorList, BorderLayout.PAGE_START);
            setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
        private static void CreateAndShowGUI()
            // Create and set up the window.
            JFrame frame = new JFrame("CustomComboBoxDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            // Create and set up the content pane
            JComponent newContentPane = new CustomComboBoxDemo();
            newContentPane.setOpaque(true);
            frame.setContentPane(newContentPane);
            // Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args)
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    CreateAndShowGUI();
    }Edited by: geforce2000 on Dec 13, 2009 3:37 AM
    Edited by: geforce2000 on Dec 13, 2009 3:38 AM

    BeForthrightWhenCrossPostingToOtherSites
    Here's one: [custom-renderer-almost-works|http://www.java-forums.org/awt-swing/23831-custom-renderer-almost-works.html]
    Any others?
    Next issue: TellTheDetails
    You may understand fully just what is not working here, but we don't since you tell us that it doesn't work, but never really tell us how.

  • How to use JComboBox as VB DataCombo?

    I wan't to know if it is possible to use a JComboBox as VB6 DataCombo.
    There are 3 main properties of the VB6 DataCombo component: BoundColumn, ListField and RowSource.
    For example I can set the rowsource of this component to be a recordset containing for the first field a country code and the second field the corresponding country name. Therefore the BoundColumn will be the country code and the list field the country name. This component will display the country name and I am able to retrieve the corresponding country name. Also when I set to country code to this component, the corresponding country name is displayed.
    Is it possible to have the same behaviour with a JComboBox or do I have to use another component?
    Thanks for your help.

    Hi, you are probably long gone ...but I would like to set the record straight.
    After coming back and reading this post again I realized I my memory was a bit foggy about what a VB bound column property was doing. In fact, you DON'T need a CellRenderer to do this, because a CellRenderer is used to manipulate the visible aspect of the cell, and that has nothing to do with the VB bound column concept. I went into Access and reminded myself what VB is using the bound value for ...which is to store an additional value for each cell in the combo, apart from the value that will be displayed in each cell. This value is used to 'bind' the combo to a database query where the invisible 'bound column' value is a primary key value that is used to lookup the rest of the row for that selection. Of course in VB this all happens behind the scenes when you choose to fill the combo from a database query.
    In Java, unless you want to build an entire wizard to match the one in VB, you don't really approach the problem that way. You are going to have to do your own JDBC routine to fill the combo ...then listen for selections on that combo ...and query new values from the database each time the selection changes. However, you could give yourself a bit of leverage by considering the following two approaches.
    First off, you could ...as you read in the combo values from the db ...just add your own special data object into the combo that holds TWO values instead of just putting in the single visual object into the combo.
    //Loop through db results getting both the primaryKey
    //column values and the visible column values...
    mycombo.addItem( (Object) new MySpecialDataObject(primaryKey,visibleValue) );Your class for MySpecialDataObject could be something like this:
    public class MySpecialDataObject {
      private String primaryKey;
      private String visibleValue;
      public MySpecialDataObject(String primKey, String visVal) {
        primaryKey = primKey;
        visibleValue = visVal;
      public String getPrimaryKey() { return primaryKey; }
      public String getVisibleValue() { return visibleValue; }
    }And then when you get the selected object just cast it back into your special type, and then you can access both the primaryKey and the visibleValue for the selection. You can then requery the db using the primaryKey instead of having to use only the visible combo cell value.
    //Inside your action event for the combobox...
    MySpecialDataObject dao = (MySpecialDataObject) mycombo.getSelectedItem();
    String sql = "SELECT * FROM a_table WHERE primKey = " + dao.getPrimaryKey();However, this kind of forces the work onto the application developer to make this one (or possibly many of these) little data capsules each time they are using the combo. Another alternative could be to go to the data model for the combo, and create your own custom subclass that adds the characteristics you are looking for to the combobox itself, relieving the app developer of this minor nuisance. It might be a bit more work up front ...but it will streamline your development in the future by providing a customized combo class for your dev's to use.
    Here is an example of doing just that. The comments cover most of what I have done and why ...I did this over the weekend as my penance for giving you bad advice regarding the Cell renderer. As a bonus, I threw in an example of defining a custom cell renderer as well. Cheers ...silly old GumB.
    P.S. I am sure there are other approaches as well, good luck.
    * BoundJComboBoxModel.java
    * Created on May 23, 2003, 10:51 PM
    package com.gumbtech.ui;
    import java.util.ArrayList;
    * @author  gum
    public class BoundJComboBoxModel extends javax.swing.DefaultComboBoxModel {
      private ArrayList boundObjects = new ArrayList();
       * Above, is an ArrayList for storing the bound values for each element.
       * Below, I have overriden all three constructors from DefaultComboBoxModel.
       * Notice how the second two just create default 'bound values' equal to a
       * string representation of the elements array index integer.  This may
       * work as a default if your primary keys in the database agreed (which
       * they quite possibly could).  However, the model is not really intended
       * to be filled this way.  Instead, use the overloaded addElement method
       * (below) and provide each item and corresponding bound value as a pair.
      public BoundJComboBoxModel() {
        super();
      public BoundJComboBoxModel(Object[] items) {
        super(items);
        for(int i=0; i<items.length; i++) {
          boundObjects.add(String.valueOf(i));
      public BoundJComboBoxModel(java.util.Vector v) {
        super(v);
        for(int i=0; i<v.size(); i++) {
          boundObjects.add(String.valueOf(i));
       * This method overloads its counterpart from DefaultComboBoxModel.
       * This provides a way to add a complete element, by providing values
       * for both the display value and the bound value all at once.
      public void addElement(Object item, Object boundValue) {
        boundObjects.add(boundValue);
        super.addElement(item);
       * Here are the new methods that 'decorate' the original DefaultComboBoxModel.
       * They provide ways to set and get the bound value for a specific element.
       * The method setBoundValueAt is called from the gui when we fill the combo.
       * The method getBoundValueAt is called from the BoundJComboBox class that
       * we are going to build next. It could be called directly on the model, but
       * making a special JComboBox class that used this model seemed a little nicer.
       * You will see the JComboBox class that uses this model next in the example.
      public void setBoundValueAt(int index, Object boundValue) {
        boundObjects.set(index, boundValue);
      public Object getBoundValueAt(int index) {
        return boundObjects.get(index);
      public Object getBoundValueForItem(Object item) {
        int index = getIndexOf(item);
        return boundObjects.get(index);
       * These methods override thier counterparts from DefaultComboBoxModel.
       * They are overriden so we can keep the bound value list in sync.
       * For example, consider the original addElement method from the superclass.
       * Used when no bound value is provided, the method will add a bound value
       * equal to a string representation of the elements array index integer.
       * The other two overriden methods are self explanatory.
      public void addElement(Object item) {
        int idNum = boundObjects.size();
        boundObjects.add(String.valueOf(idNum));
        super.addElement(item);
      public void removeElement(Object item) {
        int index = super.getIndexOf(item);
        boundObjects.remove(index);
        super.removeElement(item);
      public void removeAll() {
        boundObjects = new ArrayList();
        super.removeAllElements();
    * BoundJComboBox.java
    * Created on May 23, 2003, 10:00 PM
    package com.gumbtech.ui;
    import java.util.ArrayList;
    import com.gumbtech.ui.BoundJComboBoxModel;
    * @author  gum
    public class BoundJComboBox extends javax.swing.JComboBox {
       * Here, I have overriden all three constructors from JComboBox.
       * We will 'force' our custom JComboBox to use the BoundJComboBoxModel.
      public BoundJComboBox() {
        super(new BoundJComboBoxModel());
      public BoundJComboBox(Object[] items) {
        super(new BoundJComboBoxModel(items));
      public BoundJComboBox(java.util.Vector v) {
        super(new BoundJComboBoxModel(v));
       * These are the new methods that 'decorate' the original JComboBox
       * class.  We have added methods that match the two methods JComboBox
       * provides for finding elements in the models list, except that our
       * new methods access the bound value list instead of the item list.
       * I only use the getSelectedBoundValue method in this example.  I
       * provided the other because together the two make a complete match
       * to the way the original class lets you query the original model.
      public Object getSelectedBoundValue() {
        return ((BoundJComboBoxModel)this.dataModel)
                .getBoundValueAt(getSelectedIndex());
      public Object getBoundValueAt(int index) {
        return ((BoundJComboBoxModel)this.dataModel)
                .getBoundValueAt(index);
    * BoundComboTest.java
    * Created on May 24, 2003, 12:18 PM
    package com;
    import java.awt.Color;
    import com.gumbtech.ui.BoundJComboBox;
    import com.gumbtech.ui.BoundJComboBoxModel;
    import com.gumbtech.ui.MyCustomCellRenderer;
    * This is a test gui that lets us demonstrate the custom
    * BoundJComboBox that we have created.  We are going to
    * emulate the 'bound column' characteristic of a VB bound
    * combo box object.
    * @author  gum
    public class BoundComboTest extends javax.swing.JFrame {
      public final static String T = "    ";
      private BoundJComboBox boundJComboBox;
      private javax.swing.JLabel msgLbl;
       * The constructor just calls methods that
       * build the gui and then fill the combo box.
      public BoundComboTest() {
        initComponents();
        fillCityComboByProvince("Alberta");
       * This method just sets up the gui components for our example.
      private void initComponents() {
      //Create an instance of BoundJComboBox (our customized JComboBox).
        boundJComboBox = new BoundJComboBox();
      //Plug in a custom renderer for the element cells visual appearance.
      //I put this here so you can see what a CellRenderer does, but this
      //actually plays no part in creating our VB like bound column combobox.
      //Out of interest, you can look at the MyCustomCellRenderer class later on.
        boundJComboBox.setRenderer(new MyCustomCellRenderer(new Color(40,100,60)));
      //Listen for change events on the combo box with an action listener.
      //Inside this action (see the comboActionPerformed method below) lies
      //the real reason for needing the bound column value.  The action needs
      //to translate the combo selection into a database query that retrieves
      //the values to be used on the form that this combo box is controlling.
        boundJComboBox.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
            comboActionPerformed(evt);
      //Create other stuff to host our combo box in (irrelevent to our example).
        msgLbl = new javax.swing.JLabel();
        setTitle("Bound Combo Example");
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
          public void windowClosing(java.awt.event.WindowEvent evt) {
            System.exit(0);
        getContentPane().add(boundJComboBox, java.awt.BorderLayout.NORTH);
        getContentPane().add(msgLbl, java.awt.BorderLayout.CENTER);
        pack();
        java.awt.Dimension screenSize =
           java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setSize(new java.awt.Dimension(400, 200));
        setLocation((screenSize.width-400)/2,(screenSize.height-200)/2);
       * So, your 'bound' combo box needs a visual label that will be
       * displayed in the combo box, here we use city names from a db.
       * Your VB like 'bound column' is going to be the city_ID number, which is
       * the primary key we need to use to look up this cities values in other
       * tables.  Being different from the visible text label ...this value needs
       * to be stored in the special 'bound column' area of our combo box model.
      private void fillCityComboByProvince(String province) {
      //We can get the model out of our JComboBox, notice that the model is of
      //type BoundJComboBoxModel ...which is our own customized ComboBoxModel.
        BoundJComboBoxModel model = (BoundJComboBoxModel) boundJComboBox.getModel();
      //Clear out the combo so we can load it fresh  See how the methods we are
      //used to using in a regular ComboBoxModel now seamlessly handle our
      //parallel list of 'bound column' values.  That's because we over-rode
      //them appropriately in our customized BoundJComboBoxModel.
        model.removeAll();
      //Pretend this is the query we would use to get the values...
      //If we were selecting all the rows in the table, we might not need a bound
      //column bacause they may have a linear set of incrementing primary keys.
      //However, we are selecting a filtered set of cities ...only those from Alberta
      //...so the primary keys will not follow any regular pattern.  This is why the
      //'bound column' concept is used ...to hold a non-visible list of primary keys
      //that match each label in the combo box.  Even though we choose the value
      //'Calgary' in the combo ...we need to use '54' to look it up in the database.
        String sql = "SELECT name, city_ID FROM cities WHERE province = "+ province;
      //Pretend this is the results from our query to the db.
        final Object[] cityNames = {"Calgary", "Edmonton", "Lethbridge", "Red Deer"};
        final Object[] primaryKeys = {"54", "89", "101", "193"};
      //Use the overloaded addElement method we created in BoundJComboBoxModel to
      //fill the combo with both the visual text value, and the 'bound' value.
        for(int i=0; i<cityNames.length && i<primaryKeys.length; i++) {
            model.addElement(cityNames, primaryKeys[i]);
    //See, the combo box now has a 'bound column' for each visual element in
    //its list, which we will use to query the db each time the selection changes.
    //This is all your 'bound column' is doing in your VB wizard ...except you
    //never see the code for it. In Java, you just write the code to give your
    //JComboBox this behaviour ...and more if you so choose (which is really
    //the whole the point here!)
    * The next method handles the selection change event for our combo box.
    * This is where you use the 'bound value'. You use it to requery
    * the db so you can fill in your form with new values each time
    * the combobox selection is changed by the user.
    * This method is your action event for the combo ...and it is doing
    * the same thing that your VB program will do with your 'bound column'
    * in your VB combo box. In VB you just can't see the code, that's all.
    private void comboActionPerformed(java.awt.event.ActionEvent evt) {
    //Get the combobox that performed the action event...
    boundJComboBox = (BoundJComboBox) evt.getSource();
    //If we had a database here for real, we would query for our new form
    // values using the 'bound column' value as the primary key in the query.
    //This is what it means to use the 'bound column' of a VB combobox or list.
    //Its just a value for each element in the combo box that is different from
    //the value that will be displayed in the combo list. That's all it means.
    //VB just uses the bound value to query the database, so we can do that too.
    String sql =
    "SELECT * FROM cities WHERE city_ID = " +
    boundJComboBox.getSelectedBoundValue();
    //Since we don't really have a db, I'll just show the values for the element.
    String msg = "<html><font color=#006666>"+
    T +"Index Selected : "+ boundJComboBox.getSelectedIndex() +"<br>"+
    T +"Value Selected : "+ boundJComboBox.getSelectedItem() +"<br>"+
    T +"Bound Column Value: "+ boundJComboBox.getSelectedBoundValue() +"<br>"+
    T +"</font><font color=#dd3366>"+ sql +"</font></html>";
    msgLbl.setText(msg);
    public static void main(String args[]) {
    new BoundComboTest().show();
    * MyCustomCellRenderer.java
    * Created on May 23, 2003, 9:21 PM
    package com.gumbtech.ui;
    import java.awt.Color;
    import javax.swing.JList;
    import javax.swing.DefaultListCellRenderer;
    * usage:
    * String[] data = {"one", "two", "free", "four"};
    * JList dataList = new JList(data);
    * dataList.setCellRenderer(new MyCustomCellRenderer());
    * @author  I think this structure and the comments are a variation of
    *          David Flanagans example from Java Examples 2. (O'Reilly)
    public class MyCustomCellRenderer extends DefaultListCellRenderer {
      private static Color selectedColor = new Color(240,99,99);
      private static Color selectedBG = new Color(163,186,168);
      public MyCustomCellRenderer() {
      public MyCustomCellRenderer(Color selectedColor) {
        this.selectedColor = selectedColor;
       * This is the only method defined by ListCellRenderer.
       * We just reconfigure the Jlabel each time we're called.
      public java.awt.Component getListCellRendererComponent(
             JList list,
             Object value,   // value to display
             int index,      // cell index
             boolean iss,    // is the cell selected
             boolean chf)    // the list and the cell have the focus
         * The DefaultListCellRenderer class will take care of
         * the JLabels text property, it's foreground and background
         * colors, and so on.
        super.getListCellRendererComponent(list, value, index, iss, chf);
         * We additionally set the JLabels color properties here,
         * but only for the cell that is currently selected (highlighted).
        if(iss) {
          setForeground(selectedColor);
          this.setBackground(selectedBG);
        return this;

  • Mousepressed and JComboBox

    I have a JComboBox and need to add some items to it when user press on it.
    I have added mouselistener but it doesn't work

    I'm trying something like this:
    JComboBox combo = new JComboBox();
         MouseListener ml = new MouseListener()
         public void mouseClicked(MouseEvent me){}
         public void mouseEntered(MouseEvent me){}
         public void mouseExited(MouseEvent me){}
         public void mousePressed(MouseEvent me)
              combo.addItem("1");
              combo.addItem("2");
              combo.addItem("3");
              combo.addItem("4");
              combo.addItem("5");
              combo.addItem("6");
         public void mouseReleased(MouseEvent e){}
         combo.addMouseListener(ml);
    Why does'n work

  • Customize popup button image of a JComboBox

    Hi,
    I have made a new child of JComboBox.
    However, I'd like to change the image used by popup button, for users know when the component used is a pure JComboBox or my customized JComboBox.

    Hi,
    I made my own ComboBoxUI, then the button was changed. However, when I use TAB to change from one component to other, the button request the focus. I look at Java source code for BasicComboBoxUI (JDK5), and at line 764 there is the code:
    arrowButton.setRequestFocusEnabled(false);When debugging my component into NetBeans 5.0, the line 764 above runs. But the button continues to receive the focus on TAB.
    My class is here:
    class MyComboBoxUI extends BasicComboBoxUI {
      ClassLoader cl;
      String imageName;
      public MyComboBoxUI(ClassLoader cl, String imageName) {
        super();
        this.cl = cl;
        this.imageName = imageName;
      protected JButton createArrowButton() {
        JButton button = new JButton();
        URL imgLocation = null;
        if (!Geral.StrEmpty(imageName))
          imgLocation = cl.getResource(imageName);
        if (imgLocation != null) {
          button.setIcon(new ImageIcon(imgLocation));
          button.setOpaque(false);
          return button;
        else
          return super.createArrowButton();
    }and I call it in the construtor of my personized JComboBox:
      public JTextLookupCombo(
        ClassLoader cl, String DirImagens,
        Component framepai,
        Connection connLocal,
        boolean required,
        String lookupsql, String lookupfield, String lookupdisplay,
        String lookupfilter, String lookupempty) {
        super();
        // ... many codes
        MyComboBoxUI ui = new MyComboBoxUI(cl, DirImagens + JFrameTab.PESQUISAR + "micro.gif");
        setUI(ui);
        setBorder(BorderFactory.createLineBorder(Color.BLACK));
      }Message was edited by:
    Edilmar_Alves

  • JTable with JPopCell

    I have custom JComboBox that have custom Panel as popup when choosing Items. this Panel have JCalendar Panel to choose date from.
    If I use this ComboBox alone it works fine, but if I use it in JTable cell, and when I open the cell for editing, the Popup JCalendar appears but if I try to click on it
    (any where in the Popop JCalendar) it disappear with no click action.
    Another thing I used the same JComboBox but with anther custom Popup that contains Button,Text,Label and anther JTable, and it works correctly, I can click any
    where on this panel it doesn't disappear All component inside the panel 'doesn't receive any action (like mouse MouseListener, but MouseMotionListener works fine ). .Any Idea why it do this?!!!
    Edited by: Ayman_java on Aug 10, 2008 7:06 PM
    Edited by: Ayman_java on Aug 10, 2008 7:15 PM

    Hi
    This sounds like a failure at the TableCellEditor component code...
    To receive mouse events on this nested elements at the table you need
    to dispatch the mouse events received by the table only down to the
    elements you store in the table.
    here is a little code snipped
    // me ist the MouseEvent object, p is a Point object
    yourComponentAtTheTable.dispatchEvent(new MouseEvent(yourTable, me.getID(), me.getWhen(),
                                                 me.getModifiers(), p.x,
                                                 p.y,
                                                 me.getClickCount(),
                                                 me.isPopupTrigger()));look at the API to better understand the behavior.
    Olek

  • Using SwingConstants in NetBeans designer mode

    In NetBeans, when adding property get/set methods for a bean they'll be added automatically to the properties panel in the designer.
    I've written a setHorizontalAlignment method for a custom JComboBox I use and I want to use SwingConstants as the method parameter.
    How do I get the IDE to display my custom method like the standard setHorizontalAlignment method of JLabel / JTextField, that is as choice selection from a list of SwingConstants values.

    Problem was fixed by a upgrad of the JDK.

Maybe you are looking for