import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.plaf.basic.BasicComboBoxEditor;
public class ComboBoxRendererDemo extends JPanel
{
/**
*
*/
private static final long serialVersionUID = 1L;
static class ButtonComboBoxRenderer implements ListCellRenderer
{
public Component
getListCellRendererComponent (JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{
final JButton button = new JButton (value.toString());
final Object valueCopy = value;
button.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent ae)
{
JOptionPane.showMessageDialog((Component) ae.getSource(), "You chose \"" + valueCopy + "\"!");
}
});
return button;
}
}
static class ButtonComboBoxEditor extends BasicComboBoxEditor implements ActionListener
{
JButton selectedButton = new JButton();
ActionListener currentActionListener;
public Object getItem()
{
return selectedButton;
}
public void setItem (Object o)
{
final String text = o.toString();
selectedButton.setText (text);
if (currentActionListener != null)
selectedButton.removeActionListener (currentActionListener);
currentActionListener = new ActionListener()
{
public void actionPerformed (ActionEvent ae)
{
JOptionPane.showMessageDialog((Component) ae.getSource(), "You chose \"" + text + "\"!");
}
};
selectedButton.addActionListener (currentActionListener);
}
public Component getEditorComponent()
{
return selectedButton;
}
public void actionPerformed (ActionEvent ae)
{
currentActionListener.actionPerformed (ae);
}
}
public static void main (String arg[])
{
JFrame mainFrame = new JFrame ("Combo Box With Buttons");
JComboBox comboBox = new JComboBox (arg);
ButtonComboBoxEditor editor = new ButtonComboBoxEditor();
comboBox.setRenderer (new ButtonComboBoxRenderer());
comboBox.setEditor (editor);
comboBox.setEditable (true);
comboBox.addActionListener (editor);
mainFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
mainFrame.getContentPane().add (comboBox);
mainFrame.show();
}
}