【发布时间】:2021-03-06 07:43:04
【问题描述】:
我有这段代码,但 MyComboBoxRenderer() 似乎无法使用它。它在下面写的注释行中有错误。
此代码用于自动建议。因此,当用户在文本字段上键入内容时,它会在组合框中显示建议。
public test2() {
initComponents();
jComboBox1.setRenderer(new MyComboBoxRenderer1());
jComboBox1.setBackground(new Color(0,0,0,0));
final JTextField textfield = (JTextField) jComboBox1.getEditor().getEditorComponent(); //it has error in this line
textfield.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent ke) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
comboFilter(textfield.getText());
}
});
}
});
}
也许它与文本字段有关。我的问题是我想编辑组合框的外观或设计。我希望它继承框架的背景。像透明的。示例在图片中。
这是图片。请点击以下链接查看。
It should be something like this
Rather than this one. This is the output of the codes above.
这是我的组合框渲染器中的代码。
public MyComboBoxRenderer1(){
setOpaque(true);
setFont(new Font ("Segoe UI Semibold", Font.PLAIN ,14));
setForeground(Color.WHITE);
}
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
setText(value.toString());
if (isSelected)
{
setBackground(Color.WHITE);
setForeground(Color.BLACK);
}
else {
setBackground(Color.GRAY);
setForeground(Color.WHITE);
}
return this;
}
}
为什么渲染器不能用这个?我应该怎么做才能让它发挥作用?任何人都可以帮助我吗?先感谢您。 :)
已编辑...
我已经将背景设置为透明。我只需要声明texfield的背景。 XD耶。 textfield.setBackground(新颜色(0,0,0,0)); textfield.setForeground(new Color(255,255,255));
但它留下了仍然不透明的一小部分。
我尝试在我的框架上添加一个额外的组合框。但它没有文本字段。而且效果很好!
上面是带有文本字段的组合框,我遇到的问题。较低的是没有文本字段的那个,我只是尝试了代码是否可以与普通的组合框一起使用。我需要让它看起来像较低的。
jComboBox1.setRenderer(new MyComboBoxRenderer1());
jComboBox1.setBackground(new Color(0,0,0,0));
jComboBox2.setRenderer(new MyComboBoxRenderer1());
jComboBox2.setBackground(new Color(0,0,0,0));
它具有相同的代码。但它不适用于另一个。也许又是因为文本字段? :(((
【问题讨论】:
标签: java swing jtextfield jcombobox renderer