如何在JComboBox中显示颜色?

时间:2014-05-08 23:19:37

标签: java colors jcombobox

主要思想是,组合框应该在选择区域中显示颜色而不是普通的字符串。 这是我到目前为止所做的代码。

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class Colors extends JFrame implements ActionListener {

private JComboBox combo;
private JPanel panel;
private final Color[] content = {Color.red, Color.blue, Color.green, Color.black,   
                                 Color.yellow};

public Colors() {
    super("Colors");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocation(500, 150);
    setSize(250, 100);
    setResizable(false);
    Container c = getContentPane();
    c.setLayout(new FlowLayout());
    panel = new JPanel();
    c.add(panel);
    getCombo();
}

private void getCombo() {

    combo = new JComboBox(content);
    combo.setSelectedIndex(4);
    combo.addActionListener(this);
    panel.add(combo);
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == combo) {
        int choose = combo.getSelectedIndex();
        if (choose == 0) {
            panel.setBackground(content[0]);
        } else if (choose == 1) {
            panel.setBackground(content[1]);
        } else if (choose == 2) {
            panel.setBackground(content[2]);
        } else if (choose == 3) {
            panel.setBackground(content[3]);
        } else if (choose == 4) {
            panel.setBackground(content[4]);
        } else if (choose == 5) {
            panel.setBackground(content[5]);
        }
    }
}

public static void main(String[] args) {
    Colors run = new Colors();
    run.setVisible(true);
}
}

这只是显示awt引用和GBR编号,我希望颜色显示在组合框中

0 个答案:

没有答案