我希望在我的Swing应用程序中有一个JCombobox,它在没有选择任何内容时显示标题。像这样:
国家▼
西班牙
德国
爱尔兰
我希望“COUNTRY”在所选索引为-1时显示,因此用户将无法选择它。我试图把它放在第一个插槽然后覆盖ListCellRenderer,所以第一个元素显示为灰色,并处理事件所以当试图选择“标题”时,它选择第一个实际元素,但我认为这是一个脏方法
你可以帮我一把吗?
答案 0 :(得分:8)
覆盖ListCellRenderer
是一种很好的方法,但是你尝试过一些过于复杂的东西。如果要渲染单元格-1并且没有选择(值为null),则只显示某个字符串。您不仅限于列表中的显示元素。
以下是演示它的示例程序:
完整代码:
import java.awt.BorderLayout;
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.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;
public class ComboBoxTitleTest
{
public static final void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
new ComboBoxTitleTest().createAndShowGUI();
}
});
}
public void createAndShowGUI()
{
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JPanel buttonsPanel = new JPanel();
frame.add(mainPanel);
frame.add(buttonsPanel, BorderLayout.SOUTH);
String[] options = { "Spain", "Germany", "Ireland", "The kingdom of far far away" };
final JComboBox comboBox = new JComboBox(options);
comboBox.setRenderer(new MyComboBoxRenderer("COUNTRY"));
comboBox.setSelectedIndex(-1); //By default it selects first item, we don't want any selection
mainPanel.add(comboBox);
JButton clearSelectionButton = new JButton("Clear selection");
clearSelectionButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
comboBox.setSelectedIndex(-1);
}
});
buttonsPanel.add(clearSelectionButton);
frame.pack();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class MyComboBoxRenderer extends JLabel implements ListCellRenderer
{
private String _title;
public MyComboBoxRenderer(String title)
{
_title = title;
}
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean hasFocus)
{
if (index == -1 && value == null) setText(_title);
else setText(value.toString());
return this;
}
}
}
渲染器中的index == -1是头部组件,默认情况下,显示所选项目以及我们想要在没有选择时放置标题的位置。
渲染器知道没有选择,因为传递给它的值为null,这通常就是这种情况。但是,如果由于某些奇怪的原因,您在列表中有可选的空值,您可以让渲染器通过向comboBox传递一个引用来查询哪个是显式当前选择的索引,但这是完全不现实的。