JComboBox renderer

Hello,
i want to make a new renderer for my combobox,
is it possible to get rid of the white background?
at same time i want to have the first item in the combobox to be red
With regards
Sven

Hello Joerg22
thanks for the reply,
did work it out and it works allmost,
but the mainpart (besides the dropdownbutton) stays white, the popup part allready works txs for the tip!
class MessageComboBoxRenderer extends JLabel
                          implements ListCellRenderer {
       public MessageComboBoxRenderer() {
           setOpaque(true);
           setHorizontalAlignment(CENTER);
           setVerticalAlignment(CENTER);
        * This method finds the image and text corresponding
        * to the selected value and returns the label, set up
        * to display the text and image.
       public Component getListCellRendererComponent(
                                          JList list,
                                          Object value,
                                          int index,
                                          boolean isSelected,
                                          boolean cellHasFocus) {
           //Get the selected index. (The index param isn't
           //always valid, so just use the value.)
           if (index == 0) {
               setForeground(Color.red);
           } else {
               setForeground(list.getForeground());
           setBackground(Color.darkGray);
         if (value != null)
           setText(value.toString());
           return this;
    }

Similar Messages

  • Jtable sorting column having Jcombobox renderer

    Hi
    I am trying to sort Jtable column having Jcombobox renderer , please can you give me some idea to do it.
    already tried with JDK1.6 table.setAutoCreateRowSorter(true);

    To get better help sooner, post a [_SSCCE_|http://mindprod.com/jgloss/sscce.html] that clearly demonstrates your problem.
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    db

  • JComboBox rendering issue in JTable

    I use a JComboBox to render certain items in my JTable.
    When I use jdk1.3, the items render perfectly.
    The problem is that when I use jdk1.4, the combobox is rendered with larger insets, clipping the bottom of the text.
    Has anyone else had this problem?

    Okay - I can get the JComboBox and define an empty border for it. This means it renders okay.
    What I don't like is stupid things like this creeping into jdk1.4 which weren't there in jdk1.3.
    Thanks for the reply Rommie.

  • JCombobox Renderer Question

    I am trying to use a custom renderer for a jcombobox in order to show combobox items in different font color. I get a DefaultListCellRenderer and update it according to my needs (setting font color). When I run the application, the combobox is populated properly. When I select one of the items (say "Red") from the combobox, the item gets selected, but the after the selection the font color of the item that is selected defaults to black (instead of red here). What should I do so that after selecting the item, the selected item is shown in the appropriated font color as indicated by custom renderer.
    Here is the code for the custom renderer.
        private class ColorCmbRenderer implements ListCellRenderer {
            protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
            private final Dimension preferredSize = new Dimension(50, 23);
            public Component getListCellRendererComponent(JList list, Object value,
                                                        int index, boolean isSelected,
                                                        boolean cellHasFocus) {
            JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index,
                                                        isSelected, cellHasFocus);
                switch (index) {
                    case 0: renderer.setText("Black");
                            renderer.setForeground(Color.BLACK);
                            break;
                    case 1: renderer.setText("Red");
                            renderer.setForeground(Color.RED);
                            break;
                    case 2: renderer.setText("Blue");
                            renderer.setForeground(Color.BLUE);
                            break;
                    case 3: renderer.setText("Green");
                            renderer.setForeground(Color.GREEN);
                            break;
                    default: break;
                renderer.setPreferredSize(preferredSize);
                return renderer;
        }Another thing that I wanted to know is whether each of the items in the jcombobox can be associated with individual Action objects by using something like setAction(new HTMLEditorKit.BoldAction()).
    regards,
    Nirvan.

    There are 3 foregrounds to be set.import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.*;
    import javax.swing.plaf.basic.BasicComboBoxRenderer;
    public class ComboColors {
       JComboBox comboBox;
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new ComboColors().makeUI();
       public void makeUI() {
          comboBox = new JComboBox(
                new Object[]{"BLACK", "RED", "BLUE", "GREEN"});
          comboBox.setRenderer(new BasicComboBoxRenderer() {
             private final Color[] colors = {
                Color.BLACK, Color.RED, Color.BLUE, Color.GREEN
             @Override
             public Component getListCellRendererComponent(JList list, Object value,
                   int index, boolean isSelected, boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value,
                      index, isSelected, cellHasFocus);
                if (index == -1) {
                   index = comboBox.getSelectedIndex();
                setForeground(colors[index]);
                list.setSelectionForeground(colors[index]);
                comboBox.setForeground(colors[index]);
                return this;
          JFrame frame = new JFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.add(comboBox);
          frame.add(new JButton("Dummy"), BorderLayout.SOUTH);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
    }db

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

  • JComboBox renderer: please give advise

    Hello.
    Sorry, if my question is not completely matching Swing theme of this forum.. But it contains a word "renderer" nevertheless :)
    I have several types of entities, that contain two string fields: code and friendly name (for example, trains stations code-name: NYC - New York City, or trains routes code-name, etc.). They are not saved in database, but are typed in one utility class "by hands". Because of that, I don't use ids for this entities. Only code and name
    I need JComboBox, that shows this entities friendly names, and sends selected entity to server. Now, I show names and send codes. The problem is with finding name by code when i show info from server - renderer should contain some sort of HashMap with code as key to find friendly name by this string code. I think it's not the best solution.
    Should I assign id's to all my entities and use arrays with id as index in my renderers? Also send to server not codes, but this ids.
    Am I right that such kind of string codes are similar to "friendly name" and shouldn't be used as unique indentifiers at all?
    Thanks.

    I think this is what you are looking for:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=613731

  • JComboBox Rendering problem

    Hi all,
    I am displaying some numbers in a JCombobox. To center-align the numbers, I used a custom ListCellRenderer(extending JLabel) where I added the code setHorizontalAlignment(JLabel.CENTER);
    But the number displayed in the combobox is left aligned. Only other numbers inside the combobox are center-aligned. Pls help me out.

    You'll always have to set the alignment of the textfield used by the editor component of the combo box, you can try something like this:
          ComboBoxEditor editor=(ComboBoxEditor)myComboBox.getEditor();
          JTextField TF=(JTextField)editor.getEditorComponent();
          TF.setHorizontalAlignment(JLabel.CENTER);;o)
    V.V.

  • JComboBox table cell renderer problem

    The following program demonstrates a difference in behavior of table cell editor combobox based on whether the combo box is editable or not. If the ComboBox is editable, then the first click into the table cell starts the edit and shows the popup, whereas if the combobox is not editable then it takes 2 clicks into the cell to cause the popup to become visible. I am trying to achieve the 1 click popup behavior while keeping the combobox not editable. Run the following program, and click on various cells, the top table requires 2 clicks for a popup, and the bottom table only 1. The only difference is the editablility of the combobox. (This is windows l&f)
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    public class JTableComboBoxCellEditorTest {
         public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e){e.printStackTrace();}
              DefaultTableModel tableModel = new DefaultTableModel(
                        new Object[][] {{"1","2"},{"2","3"},{"3","1"} },
                        new Object[]{"Column1","Column2"}
              final JComboBox renderer = new JComboBox(new Object[]{"1","2","3"});
              TableCellRenderer cellRenderer = new TableCellRenderer() {
                   public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col){
                        renderer.setSelectedItem(value);
                        return renderer;
              JTable table1 = new JTable(tableModel);
              final JComboBox badEditor = new JComboBox(new Object[]{"1","2","3"});
              badEditor.setEditable(false);
              table1.setDefaultEditor(Object.class, new DefaultCellEditor(badEditor));
              table1.setDefaultRenderer(Object.class, cellRenderer);
              table1.setRowHeight(24);
              JTable table2 = new JTable(tableModel);
              final JComboBox goodEditor = new JComboBox(new Object[]{"1","2","3"});
              goodEditor.setEditable(true);
              table2.setDefaultEditor(Object.class, new DefaultCellEditor(goodEditor));
              table2.setRowHeight(24);
              table2.setDefaultRenderer(Object.class, cellRenderer);
              JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT,new JScrollPane(table1), new JScrollPane(table2));
            JFrame f = new JFrame("Table Test");
            f.getContentPane().add(split,BorderLayout.CENTER);
                f.setBounds(100,100,500,500);
            f.addWindowListener(new WindowAdapter() {
                 public void windowClosing(WindowEvent e) {
                      System.exit(0);
            f.setVisible(true);
    }

    Setting a renderer for first column:
    assetTable.getColumnModel().getColumn(1).setRenderer(tableRenderer);Your custom renderer must honor the selection color and border or otherwise the first column will not look selected. You should subclass DefaultTableCellRenderer:
    public class AssesTableRenderer extends DefaultTableCellRenderer  {
      public Component getTableCellRendererComponent(...) {
        // default renderer uses a label
        JLabel label = (JLabel)super.getTableCellRendererComponent(...);
        // decide icon to use
        Icon icon = ...;
        label.setIcon(icon);
       return label;
    }

  • 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.

  • Minimize size of a JComboBox

    Hi,
    i�ve got a JComboBox rendered into a JTable. This works fine but the ComboBox is much to big. I played around with setMaximumSize in several LayoutManagers. The problem is that at a certain size it cuts the JComboBox. What to do? thanks
    uri

    And I would be interested which LayoutManager you prefer using.I don't use a single Layout Manager. I use a combination of Layout Managers to do the job. Thats why this question doesn't have a specific example. Remember LayoutManagers can be nested. The default layout manager for a frame is a border layout. That great for the general look of your application.
    a) you add a toolbar to the north
    b) you add a status bar to the south
    c) you add your main panel to the center.
    the main panel in turrn may use nested panels depending on your requirements. I don't do a lot of screen design but I typically use BorderLayout, FlowLayout, GridLayout and BoxLayout. GridBagLayout and SpringLayout have too many constraints to learn and master. They may be good for a GUI tool that only uses a single layout manager for the entire GUI, but I believe a better design is to break down the form into smaller more manageable areas and group components and use the appropriate layout manager for the group. That may or may not be a GridBagLayout for the small group, but I don't think you should force the entire form to use a GridbagLayout.

  • 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.

  • Dynamically changing the functions in a menu based on the user (in SSHR)

    Dear All,
    I have a requirement to change the functions in a menu dynamically.
    For Ex: An employee is allowed to apply Advance only in the first one month of his/her joining. I created it as an EIT and attached the function, to the menu. Now, i want to remove it automatically from the menu if his/her term in the company crossed one month.
    Can any one tell me how to automatically disable it after one month.
    Thanks and Regards
    Raj
    Edited by: SuperStar_Krishna on Jul 5, 2010 12:22 AM

    The following code should do it. In this example, MyCellRenderer is the renderer class implementing TableCellRenderer, used for displaying combo box.
    TableCellRenderer renderer= new MyCellRenderer();
    (JComboBox)renderer.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            //Your event handling goes here
    });

  • Dynamically changing dropdown options in JCombox cell editor

    Hi all,
    I have a JTable with one column with JComboBox renderer and i am using the cell editor for that column as new DefaultCellEditor(JComBoBox renderer class).
    My requirement is i want to change the dropdown options basing on another column value.
    So what i did is in the setValueAt(...) function i got the table column renderer and as send the new values in a object to the renderer and in the getTableCellRendererComponent method i am checking the row number and setting the dropdown options to the JComboxBox. This works fine and the JComboBox is showing the new dropdown options correctly but when i click on the JcomboxBox cell it is showing the old dropdown options.
    So my question is how can i change the values in the editor.
    I tried like this in my setValueAt(..) functioin in my JTable model
    ( (my custom class) ((DefaultCellEditor) table.getColumnModel.getColumn(int)).getComponent).add(NewObject)
    in the new object i am sending new dropdown values and row and column but it some how it is updating renderer but not editor. Please give me the solution
    Thanks in advance
    Sunil

    You can extend DefaultCellEditor the same way as you extend cell renderer.
    After that you can set it back to your table using table.setCellEditor() method.
    best regards
    Stas

  • Set Background/Foreground color for Cell Renderer in JComboBox

    Hello,
    I was wondering if there is a way to change default settings for when I browse items under a JComboBox's cell renderer? I want the item's color to change (to what I set it to), when mouse enters the item. As of now, the cell's background color changes to Blue when I enter it. Is this default for JComboBox or might it have been set somewhere, that I need to look into?
    Please let me know if there are ways to do this.
    Thanks!
    Message was edited by:
    programmer_girl

    Here's my SSCCE:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JComboBox;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.text.DefaultHighlighter;
    public class MyComboBoxTest extends JPanel {
          * @param args
         String[] patterns = {"pattern1","pattern2","pattern3"};
         public MyComboBoxTest()
              JPanel patternsPanel = new JPanel();
            setMinimumSize(new Dimension(100, 100));
            JComboBox patternList = new JComboBox(patterns);
            final JTextField editor = (JTextField) patternList.getEditor().getEditorComponent();
            patternList.setEditable(true);
            this.add(patternsPanel);
            patternsPanel.add(patternList);
            patternList.addActionListener(new ActionListener()
                 public void actionPerformed(ActionEvent e)
                      editor.setSelectedTextColor(Color.WHITE);
                      editor.setForeground(Color.WHITE);
                      try{
                           editor.getHighlighter().addHighlight(0, editor.getText().length(),new DefaultHighlighter.DefaultHighlightPainter(Color.BLUE));
                           } catch (Exception ex){
                                ex.getMessage();
            editor.addMouseListener(new MouseAdapter()
                 public void mouseClicked(MouseEvent e)
                      editor.getHighlighter().removeAllHighlights();
                      editor.setForeground(Color.BLACK);
                      editor.setSelectedTextColor(Color.BLACK);
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              JFrame frame = new JFrame("My ComboBox Demo");
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setSize(100, 100);
            frame.getContentPane().add(new MyComboBoxTest());
            frame.setLocation(50, 50);
            frame.pack();
            frame.setVisible(true);
    }

  • JComboBox with Custon Renderer Problem

    Hi, I am using a JComboBox with a custom ListCellRenderer that changes the colors of the strings on the list depending on some circunstances. The problem is that the changes only work on the list, but when one item is finally selected, and the list is no longer visible, the selected item has the default format (no colors)
    Thanks in advance

    I am not exactly sure what you mean, but here is something I wrote that sounds similar. It allows items in the dropdown list to be highlighted (text in red). The highlighted state is maintained when the dropdown list disappears, though in this implementation a selected item has highlighting turned off (the idea was that the items are things the user needed to see, once the user had selected a item, it no longer needed to be highlighted).
    For this to work all the items in your list must implement HighlightingComboBox.Highlightable.
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    * An extension to JComboBox that allows items to be "highlighted"
    * (if they implement the HighlightingComboBox.Highlightable interface).
    * Highlighted items are shown in red. Highlighting is turned off when
    * the item is first selected. Items not impleneting that interface are
    * displayed normally. The drop-down list is rendered the same
    * regardless of the font property of the components, it is therefore
    * possible to set that property to, say, a huge, fancy font without the
    * drop-down panel being affected.
    public class HighlightingComboBox extends JComboBox
                                      implements ActionListener {
        public HighlightingComboBox() {
            super();
            addActionListener(this);
            setRenderer(new FancyRenderer());
        public HighlightingComboBox(Object[] os) {
            super(os);
            this.addActionListener(this);
            setRenderer(new FancyRenderer());
        public void actionPerformed(java.awt.event.ActionEvent ae) {
            if (getSelectedItem() instanceof Highlightable)
                ((Highlightable)getSelectedItem()).setHighlighted(false);
        private static class FancyRenderer extends JLabel
                                           implements ListCellRenderer {
            public java.awt.Component getListCellRendererComponent(
                    javax.swing.JList list,
                    Object value,
                    int index,
                    boolean isSelected,
                    boolean cellHasFocus) {
                setText(value.toString());
                if ((value instanceof Highlightable)
                           && (((Highlightable)value).isHighlighted())) {
                    setForeground(Color.red);
                } else {
                    setForeground(Color.black);
                setBackground(isSelected ? Color.yellow : Color.white);
                setForeground(Color.black);
                return this;
         * Objects that implement this interface can be
         * highlighted on a HighlightingComboBox.
        public interface Highlightable {
            public boolean isHighlighted();
            public void setHighlighted(boolean flag);
    }

Maybe you are looking for