怎样用Java写出一个下拉表框,点击标签,控制背景颜色?

解决方案 »

  1.   

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    /**
     * show a ComboBox
     * extends JFrame  
     * implements ItemListener
     * @author Lei   2010/12/3
     *@version eclipse-SDK-3.6
     */
    class ComboBox extends JFrame implements ItemListener{
    JComboBox cb;
    JLabel lb;
    ComboBox(){
    super("This is a ComboBox");

    setLayout(new GridLayout(2,1));
    setSize(400,300);
    Container cp=this.getContentPane();

    String []city={"北京","上海","洛阳","郑州"};
    cb=new JComboBox(city);
    cb.setFont(new Font("Normal",Font.BOLD,20));
    lb=new JLabel("Please choose a city");
    lb.setFont(new Font("Normal",Font.BOLD,20));
    cb.setEditable(true);
    cp.add(cb);
    cp.add(lb);
    setVisible(true);
    //pack();
    cb.addItemListener(this);
    addWindowListener(new WindowAdapter(){
           public void windowClosing(WindowEvent e){System.exit(0);}});
    }
    /**
     * this is the method required by the Interface ItemListener
     * to set the action when the ComboBox is clicked
     * @param ItemEvent e
     */
    public void itemStateChanged(ItemEvent e){
    if(e.getSource()==cb){
    lb.setText("您选择了"+cb.getSelectedItem());
    }
    }
    public static void main(String sd[]){
    //Create a object of ComboBox to start the program
    ComboBox frm=new ComboBox();
    }
    }
    这是我今天下午刚写的一个JComboBox的程序,先发给你,稍微改一下就能得到你想要的结果,如果可以了就把分给我吧??!!如果不行的话说一声我帮你改!
      

  2.   

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class JComboBoxExample extends JFrame {
        private Color[] colors = {Color.BLUE,Color.RED,Color.BLACK,Color.YELLOW};
        private JComboBox colorSelector = new JComboBox(colors);
        public JComboBoxExample(){
    super("JComboBoxExample"); final JPanel container = (JPanel)getContentPane();
    colorSelector.setOpaque(false);
    colorSelector.addItemListener(new ItemListener(){
    @Override public void itemStateChanged(ItemEvent e){
        container.setBackground((Color)(colorSelector.getSelectedItem()));
    }
        });
    colorSelector.setRenderer(new DefaultListCellRenderer(){
    @Override public Component getListCellRendererComponent(JList list,
    Object value,
    int index,
    boolean isSelected,
    boolean cellHasFocus){
        setText(value.toString());
        setForeground((Color)value);
        return this;
    }
        });
    container.setBackground((Color)(colorSelector.getSelectedItem()));
    container.add(colorSelector,BorderLayout.NORTH);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setPreferredSize(new Dimension(400,300));
    pack();
    setVisible(true);
        }    public static void main(final String[] args) {
    java.awt.EventQueue.invokeLater(new Runnable(){
    public void run(){
        new JComboBoxExample();
    }
        });
        }
    }