2013-03-25 98 views
0

我想用Colour.java中聲明的枚舉來填充JComboBox。我可以使用Colour.values()來訪問枚舉的描述,但可以訪問枚舉聲明本身嗎?我想用JComboBox填充藍色和紅色。我看過http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html無濟於事。使用枚舉類填充JComboBox

package example; 
import javax.swing.*; 

public class ColourView extends View { 

private JLabel colourLabel; 
private JComboBox comboBox; 
private DefaultComboBoxModel model; 

public ColourView() { 
    colourLabel = new JLabel(); 
    colourLabel.setText("Colours"); 
    colourLabel.setBounds(20, 30, 70, 20); 
    mainContentLayeredPane.add(colourLabel, JLayeredPane.DEFAULT_LAYER); 

    comboBox = new JComboBox(Colour.values());  

    comboBox.setSize(100, 20); 
    mainContentLayeredPane.add(comboBox, JLayeredPane.DEFAULT_LAYER); 
} 

public void setComboBox(String[] list) { 
    model = new DefaultComboBoxModel(list); 
    comboBox.setModel(model); 
} 
} 

package example; 

public enum Colour { 
BLUE("Blue Paint", 12), 
RED("Red Paint", 4); 
private String description; 
private int value; 

Colour(String description, int value){ 
    this.description = description; 
    this.value = value; 
} 

public String getDescription() { 
    return description; 
} 

public void setDescription(String description) { 
    this.description = description; 
} 

public int getValue() { 
    return value; 
} 

@Override 
public String toString() { 
    return description; 
} 
} 
+1

你能解釋一下目前的解決方案有什麼問題嗎? – 2013-03-25 12:18:20

+0

當前的解決方案將藍色塗料和紅色塗料添加到組合框。在藍色和紅色之後。 – user1783462 2013-03-25 12:56:30

回答

2

如果你想在相同顏色的少許樣本旁邊的顏色名稱顯示,你需要一個custom renderer。如果您以DefaultListCellRenderer開頭,則可以添加用相同顏色繪製的Icon,或更改背景,如顯示here

+2

+1,用於鏈接到Swing教程 – camickr 2013-03-25 15:02:32