我正在尝试实现一个自定义JCombobox,我试图在下拉列表中有一个复选框(JCheckBox),底部有一个简单的“隐藏”按钮,它应该隐藏下拉菜单。现在我的JCombobox有复选框,但我不知道如何继续并添加隐藏菜单的隐藏按钮。我还想在单击一个项目(复选框)时阻止JCombobox消失。
我想隐藏按钮的原因是选择/取消选择复选框会在我的GUI中进行一些更改,例如在GUI中添加/删除列表中的电影。我希望它更实时,以便更改更明显。
以下是我的代码。我该怎么办?
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);
}
}
}
渲染器类
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;
}
}
菜单项类
class MenuItem
{
String id;
Boolean state;
public MenuItem(String id, Boolean state)
{
this.id = id;
this.state = state;
}
}