单击表格中的组合框时如何获取所选行

时间:2016-07-31 16:26:49

标签: java

我有一个表,每行都有一个运算符的combox,我们可以从中选择任何运算符和value1字段值2字段。 COMBO BOX DEFAULT OPERATOR是"等于"。所以我的问题是,当你在任何一行中点击组合框时,我应该得到所选行的值并获得我选择的操作员,以便我可以根据选定的操作员执行某些操作.... 否则,如果我将组合框操作符从中间更改为等于i,则应清除值2字段.... 帮助我摆脱这个..

1 个答案:

答案 0 :(得分:0)

您应该有一个事件要知道单击组合中的项目。

像这样:

combo.addActionListener (new ActionListener () {
    public void actionPerformed(ActionEvent e) {
        //doSomething();
    }
});

您有三种方法可以选择当前项目:

  

将获得该项目的索引是订单号。

int selectedIndex = myComboBox.getSelectedIndex();

- 或 -

  

将使用Object选择项目。你可以在这个Object中做很多方法。

     

Object selectedObject = myComboBox.getSelectedValue();

- 或 -

  

将获得使用字符串类型选择的项目的实际值。      String selectedValue = myComboBox.getSelectedValue().toString();

您可以在此处查看完整的示例代码(来自@secario会员):

import java.awt.FlowLayout;
import java.awt.event.*;

import javax.swing.*;

public class MyWind extends JFrame{

    public MyWind() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JTextField field = new JTextField();
        field.setSize(200, 50);
        field.setText("              ");

        JComboBox comboBox = new JComboBox();
        comboBox.setEditable(true);
        comboBox.addItem("item1");
        comboBox.addItem("item2");

        //
        // Create an ActionListener for the JComboBox component.
        //
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                //
                // Get the source of the component, which is our combo
                // box.
                //
                JComboBox comboBox = (JComboBox) event.getSource();

                Object selected = comboBox.getSelectedItem();
                if(selected.toString().equals("item1"))
                field.setText("30");
                else if(selected.toString().equals("item2"))
                    field.setText("40");

            }
        });
        getContentPane().add(comboBox);
        getContentPane().add(field);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MyWind().setVisible(true);
            }
        });
    }
}