ComboBox on selction

时间:2018-04-19 11:19:15

标签: java swing combobox

我试图在选择一个选项时得到组合框它会像打印一些文字那样做但我不知道如何在经过几个小时试图弄明白之后再做它。我知道这与它有关事件监听器。 Java新手。任何帮助表示赞赏。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JComboBox;

public class Frame extends JFrame
{
    //Instance Variables.
     private static final int FRAME_WIDTH = 500;
     private static final int FRAME_HEIGHT = 400;


     public Frame()
     {
        Venue1();
        setSize(FRAME_WIDTH, FRAME_HEIGHT);
     }

     private void Venue1()
     {
         //String [] Venues = {"Elvis","Gorillaz", "Imagine Dragons","Michael Jackson"};

         JComboBox DropMenu = new JComboBox();
         DropMenu.addItem("Elvis");
         DropMenu.addItem("Gorillaz");
         DropMenu.addItem("Imagine Dragons");
         DropMenu.addItem("Michael Jackson");
         DropMenu.setEditable(false);
         DropMenu.setVisible(true);

         JPanel panel = new JPanel();
         JLabel label = new JLabel("Pick a venue");

         add(panel);
         panel.add(label);
         panel.add(DropMenu);

        ActionListener listener = new listener();
        DropMenu.addActionListener(listener);

     }//End of Venue Method.
}//End of class.

//Button Listeners

class listener implements ActionListener
{
    public void actionPerformed(ActionEvent event)
    {

    }
}

    enter code here

2 个答案:

答案 0 :(得分:2)

  • JComboBox获取所选值非常简单:

DropMenu.getSelectedValue();

  • 更改选择时选择:

    MyItemListener actionListener = new MyItemListener();
    DropMenu.addItemListener(actionListener);
    
    class MyItemListener implements ItemListener {
        // This method is called only if a new item has been selected.
        public void itemStateChanged(ItemEvent evt) {
            JComboBox DropMenu = (JComboBox) evt.getSource();
            Object item = evt.getItem();
            if (evt.getStateChange() == ItemEvent.SELECTED) {
                // Item was just selected
            } else if (evt.getStateChange() == ItemEvent.DESELECTED) {
               // Item is no longer selected
            }
        }
    }
    

答案 1 :(得分:1)

ActionListener中,您需要确定事件的来源是否为JComboBox,如果是,您可以将其投射并获得selectdValue

class listener implements ActionListener
{
    public void actionPerformed(ActionEvent event)
    {
        if (event.getSource() instanceof JComboBox) {
            JComboBox cb = (JComboBox)event.getSource();
            System.out.println(cb.getSelectedItem());
        }
    }
}

我强烈建议您查看: