JComboBox中的麻烦

时间:2014-03-07 12:41:32

标签: java swing user-interface listener jcombobox

你好我在阅读JComboBox的值时很困惑。我想要一个程序,如果用户点击并选择JComboBox中的任何项目。它将显示为输出。例如我选择苹果它会出现苹果主要问题是我没有我的程序按钮所以我真的需要它点击然后输出这里是我的代码到目前为止。

 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);*/





    }


}

这是我的更新,所以如果我单击转换它将为转换框架生成另一帧的平均值。

2 个答案:

答案 0 :(得分:2)

似乎您需要使用ItemListener,例如:

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
        }
    }
});

答案 1 :(得分:2)

ActionListener添加到您的JComboBox组件并添加:

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

这将从您的组合框中获取所选项目,它将触发您从组合框中选择的每个项目