[英]Obtain currently highlighted item from JComboBox popup (not selected item)
[英]JComboBox currently selected item background and Windows LaF
那時我找不到其他方法:
UIManager.put("ComboBox.background",new Color(31,0,104));
UIManager.put("ComboBox.selectionBackground",new Color(31,0,104));
在 JComboBox 中設置當前選定項的背景顏色。 不幸的是,這對我不想要的窗口中的所有組合框都有效。
這是它目前的工作方式:圖片
這就是我希望它的行為方式:圖片
我嘗試創建自定義 DefaultListCellRenderer 並在那里調用 setBackground ,但沒有幫助。 我也嘗試覆蓋 BasicComboBoxUI ,但我可能不知道應該覆蓋哪種方法來實現結果。
編輯:根據建議,這是我代碼的一小部分,但沒有幫助
public void colorizeComboBox(){
jComboBox1.setRenderer(new ColourListCellRenderer());
jComboBox1.setUI(new BasicComboBoxUI(){
@Override
protected JButton createArrowButton() {
JButton b = this.createCustomArrowButton();
b.setContentAreaFilled(false);
b.setBackground(new Color(31,0,104));
b.setBorder(BorderFactory.createEmptyBorder());
return b;
}
public JButton createCustomArrowButton() {
JButton b=new JButton(new ImageIcon(getClass().getResource("/server/Pictures/arrowdown.png")));
b.setBorder(new EmptyBorder(0, 0, 0, 0));
b.setOpaque(true);
return b;
}
});
和自定義渲染器:
public static class ColourListCellRenderer extends DefaultListCellRenderer {
@Override
public Color getBackground() {
return new Color(31,0,104);
}
}
但現在所有這一切都改變了,當前所選項目的背景是白色的。
覆蓋 DefaultListCellRenderer 的 getBackground 和 getListCellRendererComponent 方法。
public class ColoredListCellRenderer extends DefaultListCellRenderer {
private Color selectedColor;
private Color backgroundColor;
private Color lastColor;
public ColoredListCellRenderer(Color backgroundColor, Color selectedColor) {
this.selectedColor = selectedColor;
this.backgroundColor = backgroundColor;
lastColor = backgroundColor;
}
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (isSelected) {
lastColor = selectedColor;
} else {
lastColor = backgroundColor;
}
c.setBackground(lastColor);
return c;
}
@Override
public Color getBackground() {
return lastColor;
}
}
OP 的回答從問題變成了答案:
好吧終於找到解決方案:
jComboBox1.setUI(new BasicComboBoxUI(){ @Override public void paintCurrentValueBackground(Graphics g,Rectangle bounds,boolean hasFocus){ Color t = g.getColor(); if ( comboBox.isEnabled() ) g.setColor(new Color(31,0,104)); else g.setColor(DefaultLookup.getColor(comboBox, this, "ComboBox.disabledBackground", null)); g.fillRect(bounds.x,bounds.y,bounds.width,bounds.height); g.setColor(t); } }); jComboBox1.setFocusable(false);
我不得不在 BasicComboBoxUI 中覆蓋 paintCurrentValueBackground(..) ,然后將此 UI 設置為組合框,但焦點仍然存在問題並將組合框繪制為灰色,因此我禁用了對這個組合框的關注
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.