我有一个JComboBox,我想让用户选择颜色。JComboBox只显示颜色,没有任何文本。我想出了这个解决方案。请告诉我这是否好或应该避免以及为什么。我是Swing和Java的新手,所以请耐心等待:)
public class ToolBar{
private MainFrame mainFrame;
public ToolBar (MainFrame mainFrame) {
this.mainFrame = mainFrame;
}
public JPanel getToolBar(){
JPanel toolbarPanel = new JPanel(new FlowLayout(FlowLayout.LEADING,2,2));
toolbarPanel.setPreferredSize(new Dimension(mainFrame.getScreenWidth(),60));
toolbarPanel.setBorder(BorderFactory.createLineBorder(Color.gray));
JButton fillButton = new JButton("Fill: ");
fillButton.setPreferredSize(new Dimension(60,20));
//fillButton.setBackground(Color.red);
toolbarPanel.add(fillButton);
String[] test = {" ", " " , " " , " " , " " , " "};
JComboBox colorBox = new JComboBox(test);
colorBox.setMaximumRowCount(5);
colorBox.setPreferredSize(new Dimension(50,20));
colorBox.setRenderer(new MyCellRenderer());
toolbarPanel.add(colorBox);
return toolbarPanel;
}
class MyCellRenderer extends JLabel implements ListCellRenderer {
public MyCellRenderer() {
setOpaque(true);
}
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
setText(value.toString());
switch (index) {
case 0: setBackground(Color.white);
break;
case 1: setBackground(Color.red);
break;
case 2: setBackground(Color.blue);
break;
case 3: setBackground(Color.yellow);
break;
case 4: setBackground(Color.green);
break;
case 5: setBackground(Color.gray);
break;
}
return this;
}
}
}
这工作正常。它在JComboBox中以不同的颜色显示空的选择元素。问题是当用户选择颜色时,JComboBox中的选择颜色不会改变。我应该添加哪些代码行以及在哪里,以便当用户从列表中选择颜色时,该颜色将显示在JComboBox字段中?
我尝试了一些解决方案,但结果是当用户在 JComboBox 中选择颜色选择时总是更改为灰色......
我已经浏览了几个类似的问题,但我只是无法弄清楚代码的哪一部分正在处理 JComboBox 的颜色变化,当选择完成后......
试试这个,应该可以工作。您必须覆盖设置背景...因为,内部机制使用当前外观的默认颜色:
Color[] colors={Color.white,Color.red,Color.blue,Color.green};
JComboBox colorBox = new JComboBox(colors);
colorBox.setMaximumRowCount(5);
colorBox.setPreferredSize(new Dimension(50,20));
colorBox.setRenderer(new MyCellRenderer());
和ListCellRender:
class MyCellRenderer extends JButton implements ListCellRenderer {
public MyCellRenderer() {
setOpaque(true);
}
boolean b=false;
@Override
public void setBackground(Color bg) {
// TODO Auto-generated method stub
if(!b)
{
return;
}
super.setBackground(bg);
}
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
b=true;
setText(" ");
setBackground((Color)value);
b=false;
return this;
}
}
ComboBox 使用等于,所有字符串都是相等的。定义颜色名称
String[] test = {"red", "green" , "blue" ...};
但是在渲染器调用setText(" ");
为 index == -1 添加一个案例,并将单元格渲染器的背景色设置为最新的用户选择。