1
votes

I have a JComboBox that contains items that all have a tooltip. To add the tooltips I used the stackoverflow solution here Java Swing: Mouseover text on JComboBox items?. Now I want to take this one step further and add new items to the combobox and add a new tooltip for each new item.

To test this I created a simple test project with a combobox and a button. When you click the button, a new item is created and added to the combobox. My problem is that I can't figure out how I can add the proper tooltip at the same time. In this case it seems that I'm not allowed to manually add the tooltip String to the list.

import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;

public class ComboBoxWithToolTips extends JPanel
{
    JComboBox<String> combo;
    ComboboxToolTipRenderer renderer;

    JButton button;

    String[] items;
    List<String> tooltips;

    public ComboBoxWithToolTips()
    {
        items = new String[] {"red", "blue", "black"};
        tooltips = Arrays.asList(new String[] {"a", "b", "c"});
        combo = new JComboBox<>(items);
        renderer = new ComboboxToolTipRenderer();
        renderer.setTooltips(tooltips);
        combo.setRenderer(renderer);
        add(combo);

        button = new JButton("Add");
        button.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                Random random = new Random();
                String name = "new" + random.nextInt(100);
                String tooltip = name + " tooltip";

                combo.addItem(name); // Add the new item
                renderer.tooltips.add(tooltip); // Add the new tooltip to the list
            }
        });
        add(button);
    }

    public class ComboboxToolTipRenderer extends DefaultListCellRenderer
    {
        List<String> tooltips;

        @Override
        public Component getListCellRendererComponent(JList list, Object value,
                int index, boolean isSelected, boolean cellHasFocus)
        {

            JComponent comp = (JComponent) super.getListCellRendererComponent(
                    list, value, index, isSelected, cellHasFocus);

            if (-1 < index && null != value && null != tooltips)
            {
                list.setToolTipText(tooltips.get(index));
            }
            return comp;
        }

        public void setTooltips(List<String> tooltips)
        {
            this.tooltips = tooltips;
        }
    }

    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Tooltip Test");

        ComboBoxWithToolTips comboBoxWithToolTips = new ComboBoxWithToolTips();
        comboBoxWithToolTips.setPreferredSize(new Dimension(500, 500));
        frame.getContentPane()
            .add(comboBoxWithToolTips);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
    }
}

The frame opens and every combobox item has its tooltip. But when I press the "Add" Button I get the following exception:

Exception in thread "AWT-EventQueue-0" java.lang.UnsupportedOperationException at java.util.AbstractList.add(Unknown Source) at java.util.AbstractList.add(Unknown Source) at ComboBoxWithToolTips$1.actionPerformed(ComboBoxWithToolTips.java:48) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.setPressed(Unknown Source) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$500(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source)

The solution from the prior mentioned stackoverflow topic works only for initialization but not for dynamically adding new items.

Does anybody see the mistake or is there a special type of JComboBox for what I m trying to do?

Thanks in advance!

1

1 Answers

2
votes

It's because of this line:

tooltips = Arrays.asList(new String[] {"a", "b", "c"});

Arrays.asList returns an immutable list, and you can't add elements to it.

You can create a mutable list like this:

tooltips = new ArrayList<>(Arrays.asList(new String[] {"a", "b", "c"}));