How to use ActionListener on a ComboBox to give a variable a value

时光总嘲笑我的痴心妄想 提交于 2019-11-29 10:51:15
David Kroukamp

1) Well firstly you'd need an ActionListener added to the JComboBox to listen for selected item changes.

2) Within actionPerformed(...) of ActionListener get the selected item via getSelectedItem() and cast to a String as the method returns an Object.

3) Use a switch statement to check which one the selected item matches i.e day, month,week and than assign a value accordingly.

For example:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class MonthlyData {

    public double emailvalue;
    private String[] date = {"Day", "Week", "Month"};
    private JFrame frame;

    public MonthlyData() {
        frame = new JFrame();//use an instance rather than extending the class
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        final JComboBox date1 = new JComboBox(date);

        ActionListener cbActionListener = new ActionListener() {//add actionlistner to listen for change
            @Override
            public void actionPerformed(ActionEvent e) {

                String s = (String) date1.getSelectedItem();//get the selected item

                switch (s) {//check for a match
                    case "Day":
                        emailvalue = 1.1;
                        System.out.println("Day selected, emailvalue:" + emailvalue);
                        break;
                    case "Week":
                        emailvalue = 2.2;
                        System.out.println("Week selected, emailvalue:" + emailvalue);
                        break;
                    case "Month":
                        emailvalue = 3.3;
                        System.out.println("Month selected, emailvalue:" + emailvalue);
                        break;
                    default:
                        emailvalue = 4.4;
                        System.out.println("No match selected, emailvalue:" + emailvalue);
                        break;
                }
            }
        };

        date1.addActionListener(cbActionListener);

        frame.add(date1);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new MonthlyData();
            }
        });
    }
}

UPDATE:

After you added an SSCCE and commented:

If you go down to the SliderHandler class, type in email2=(Email.getValue() * 0.002)*emailvalue; if you do the label wont update in real time. but if you replace emailvalue with lets say 5, it will update

The problem is

On start up the emailvalue is not yet set. It will only be set on the first time the selected item/index is changed.

To solve this we must simply give it a default selected value by calling setSelectedItem(..) before its visible:

final JComboBox date1 = new JComboBox(date);
date1.addActionListener(new ActionListener() {//add actionlistner to listen for change
    @Override
    public void actionPerformed(ActionEvent e) {

        String s = (String) date1.getSelectedItem();//get the selected item

        switch (s) {//check for a match
            case "Day":
                emailvalue = 30;
                break;
            case "Week":
                emailvalue = 4;
                break;
            case "Month":
                emailvalue = 1;
                System.out.println("Month selected, emailvalue:" + emailvalue);
                break;
        }
    }
});
date1.setSelectedItem(date[0]);//set Day as default selected item/emailvalue

Suggestions on your code:

  • Swing components should be created and manipulated on EDT via SwingUtilities.invokeLater(Runnable r) block.

  • Dont override paint(..) of JFrame rather add JPanel and override paintComponent(Graphics g)

  • Dont call setBounds or setSize rather use an appropriate LayoutManager and/or override getPreferredSize() of JPanel and return Dimensions which fit its contents than call pack() on JFrame before setting it visible.

  • Dont extend JFrame unnecessarily

  • Dont implement ActionListener on the class unless the class will be used as one and or its methods must be exposed to other classes

Simply have a map and use it in selection listener.

HashMap<String,Integer> map = new HashMap();
map.put("Day",1);
map.put("Week",7);
map.put("Month",30);

Add a actionListener to the JComboBox:

JComboBox date1 = new JComboBox (date);
date1.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
    {
        String selectedItem = (String) date1.getSelectedItem();
        if(selectedItem.equals("date")
        {
            emailValue = 30;
        }
    }
});

Since your class already implements ActionListener, you can do this as well (as an alternative to the above):

Add a actionCommand to your JComboBox:

JComboBox date1 = new JComboBox (date);
date1.setActionCommand("date1");
date1.addActionListener(this)

Note: date1 should be a class level variable (field) so that it is accessible to the actionPerformed method.

Add an actionPerformed method to the class (you most likely already have this).

public void actionPerformed(ActionEvent ae)
{
    if(ae.getActionCommand().equals("date1")
    {
        String selectedItem = date1.getSelectedItem();
        if(selectedItem.equals("date")
        {
           emailValue = 30;
        }
        …
        //Note: From Java 7, you can use Strings with switch
    }
}
driss

this is just an example

implements ItemListener //on your class addItemListener to your combo


public void itemStateChanged(ItemEvent e) {

     String i = "" + cboMonth.getSelectedItem();
     String b = "" + cboMonth1.getSelectedItem();
     System.out.println("The number  Start:" + i);
     System.out.println("The number End:" + b);
     if(e.getStateChange() == ItemEvent.SELECTED){
          int mSatrt = Integer.parseInt(i);
          int mEnd = Integer.parseInt(b);
          // System.out.println("The number m FROM ITEMSTATE is:" + mSatrt +"   == " + "M1 is :  "+ mEnd);

          if(mSatrt >= mEnd){ JOptionPane.showMessageDialog (this, " Next Date Payment est moin que la date de paiement" + mSatrt + ">=" + "" + mEnd);}
              //else if (mSatrt> mEnd) { JOptionPane.showMessageDialog (this, "la date Erroné" + mSatrt + ">" + "" + mEnd);}
              //else{JOptionPane.showMessageDialog (this, "la date Erroné" + mSatrt + "=" + "" + mEnd);}
          }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!