Question

hello i am confused in reading values from JComboBox. I want a program that if user click and select any item from JComboBox. It will appear as output. example i choose apple it will appear apple the main problem of this is i have no button of my program so i really need it to click then output here is my code so far .

 import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class imagebut extends JFrame 
{
    ImageIcon we = new ImageIcon(getClass().getResource("ban.png"));
    ImageIcon wer = new ImageIcon(getClass().getResource("ba.png"));
    public static void main(String args [])
    {
        imagebut w = new imagebut();
        w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        w.setSize(300,300);
        w.setVisible(true);


    }
    String []kwe = {"Convertion","Adv.Calculator","Looping","Remarks","Average","MagicSquare","Calendar","Multiplication"};
      JComboBox box = new JComboBox(kwe);

    public imagebut()
    {   

      /*  JButton converter = new JButton("Convertion");
        JButton advancecalc = new JButton("Adv.Calculator");
        JButton calc = new JButton("Calculator");
        JButton Multiplication = new JButton("Multiplication");
        JButton Looping = new JButton("Looping");
        JButton Calendar = new JButton("Calendar");
        JButton Remarks = new JButton("Remarks");
        JButton Average = new JButton("Average");
        JButton Magicsq = new JButton("Magic Square");*/
        JLabel background = new JLabel(new ImageIcon(getClass().getResource("gif.gif")));   
        JPanel pan = new JPanel();

        box.setBounds(10,10,150,25);

        getContentPane().add(background);
        background.add(box);
       /* background.add(converter);
        background.add(calc);
        background.add(advancecalc);
        background.add(Magicsq);
        background.add(Remarks);
        background.add(Calendar);
        background.add(Average);
        background.add(Looping);
        background.add(Multiplication);*/





    }


}

this is my update so example if i click convertion it will make an Frame for Convertion if Average another frame .

Was it helpful?

Solution

Add ActionListener to your JComboBox component and to like:

private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
     System.out.println(jComboBox1.getSelectedItem().toString());
    }

this will get the selected item from your combo box, it will triggers every item you select from combobox

OTHER TIPS

Seems you need to use ItemListener, for example:

JComboBox box = new JComboBox(kwe);    
box.addItemListener(new ItemListener() {

    @Override
    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED){
            System.out.println(((JComboBox)e.getSource()).getSelectedItem());
            // other actions
        }
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top