我有一个JComboBox,我希望用户选择颜色。 JComboBox只显示颜色,没有任何文字。我已经想出了这个解决方案。请告诉我这是好还是应该避免,为什么。我是Swing和Java的新手,因此请耐心等待:)用JComboBox Java Swing挑选颜色
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;
}
}
}
This works ok。它在JComboBox中以不同的颜色显示空的选择元素。问题是,当用户选择颜色时,JComboBox中的选择颜色不会改变。我应该添加哪些代码行,以及当用户从JComboBox字段中显示颜色的列表中选择颜色时?
我尝试了一些解决方案,但结果是,当用户在挑选JComboBox的颜色选择总是变成灰色......
我通过几个类似的问题看,但我只是想不通的代码部分正在处理JComboBox在选择完成后颜色的变化...
请使用代码格式化代码,输入/输出结构化文档如HTML或XML。为此,请选择样本并单击邮件发布/编辑表单上方的“{}”按钮。 –
我使用CODE按钮来标记我的问题中的代码...我将在下次{}时尝试;}对于给您带来的不便,我们深表歉意。 –