仅显示 JComboBox 所选项目文本而不显示图标?
我有一个 JComboBox
,它的渲染器是一个 JLabel
,其中组合列表中的每个项目都有一个 Icon
:
class ComboBoxRenderer extends JLabel implements ListCellRenderer {
public Component getListCellRendererComponent(
JList list,
Object comboItemObject,
int comboItemIndex,
boolean isSelected,
boolean cellHasFocus) {
String comboItemTitle = (String)comboItemObject;
setText( comboItemTitle );
setIcon( new ImageIcon( getClass().getResource( "/images/myIcon.png" ) ) );
return this;
}
}
当我从组合框中选择一个项目时我只想在组合框中显示所选项目的文本,而不是项目图标。 我有办法做到这一点吗?
I have a JComboBox
that its renderer is a JLabel
with an Icon
for each item in the combo list :
class ComboBoxRenderer extends JLabel implements ListCellRenderer {
public Component getListCellRendererComponent(
JList list,
Object comboItemObject,
int comboItemIndex,
boolean isSelected,
boolean cellHasFocus) {
String comboItemTitle = (String)comboItemObject;
setText( comboItemTitle );
setIcon( new ImageIcon( getClass().getResource( "/images/myIcon.png" ) ) );
return this;
}
}
When i select an item from the comboBox i just want to show the selected item text in the comboBox, and not the item icon also. Is there a way i can do that ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在渲染代码中您可以检查索引。类似于:
此外,您不应该在渲染代码中读取图像,因为代码被频繁调用。
In the rendering code you can check the index. Something like:
Also, you should not be reading the image in the rendering code since code is called frequently.
那么你必须覆盖
isSelected
,并且extends JLabel
是无用的,因为渲染器默认返回JLabel
作为组件then you have to override
isSelected
, andextends JLabel
is useless, because renderer by defalult returnsJLabel
as Component要获取组合框中的文本;您只需要一个单行代码即可。
创建一个变量,如我所称的
Combotext
,然后从
JComboBox
获取SelectedItem
。To get the text in the
combobox;
a one liner code is all you need.Create a variable, as I have called mine
Combotext
then get the
SelectedItem
from theJComboBox
.