我有一個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按鈕來標記我的問題中的代碼...我將在下次{}時嘗試;}對於給您帶來的不便,我們深表歉意。 –