I am trying to implement a custom JCombobox where I am trying to have checkboxes (JCheckBox) inside the dropdown and a simple "Hide" button at the bottom which should hide the drop-down menu. Right now my JCombobox has the checkboxes but i dont know how to proceed and add a hide button which would hide the menu. I would also want to stop the JCombobox from disappearing when an item (checkbox) is clicked upon.
The reason i want to a hide button is that selecting/de-selecting checkboxes makes some changes in my GUI like add/remove movies from a list in GUI. I want it to be more realtime so that changes made are more visible.
Below is my code. How do i do proceed ?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PopupMenuExample implements ActionListener
{
public JComboBox search_genre;
public static void main(String[] args)
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new PopupMenuExample().getContent());
f.setSize(300,160);
f.setLocation(200,200);
f.setVisible(true);
}
private JPanel getContent()
{
String[] item_names = { "All Genre", "Horror", "Drama", "Comedy" };
Boolean[] values ={ Boolean.TRUE, Boolean.TRUE, Boolean.TRUE, Boolean.TRUE };
// instantiate items
MenuItem[] items = new MenuItem[item_names.length];
for(int j = 0; j < item_names.length; j++) items[j] = new MenuItem(item_names[j], values[j]);
search_genre = new JComboBox(items);
search_genre.setRenderer(new Renderer());
search_genre.addActionListener(this);
JPanel panel = new JPanel();
panel.add(search_genre);
return panel;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==search_genre)
{
JComboBox cb = (JComboBox)e.getSource();
MenuItem menu_item = (MenuItem)cb.getSelectedItem();
System.out.println(menu_item.id);
Renderer ccr = (Renderer)cb.getRenderer();
ccr.checkBox.setSelected((menu_item.state = !menu_item.state));
search_genre.setSelectedIndex(0);
}
}
}
Renderer class
class Renderer implements ListCellRenderer
{
JCheckBox checkBox;
public Renderer()
{
checkBox = new JCheckBox();
}
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
MenuItem store = (MenuItem)value;
checkBox.setText(store.id);
checkBox.setSelected(((Boolean)store.state).booleanValue());
checkBox.setBackground(isSelected ? Color.blue : Color.white);
checkBox.setForeground(isSelected ? Color.white : Color.black);
return checkBox;
}
}
Menu item class
class MenuItem
{
String id;
Boolean state;
public MenuItem(String id, Boolean state)
{
this.id = id;
this.state = state;
}
}