java - 选择组合框中的项目时执行操作

标签 java swing actionlistener jcombobox itemlistener

<分区>

我有一个包含 item1 和 item2 的 jcombobox,还有一个 jtextfield。当我在我的 jcombobox 上选择 item1 时,我希望 30 出现在我的 jtextfield 上,而如果选择了 Item2,则为 40 ...我该怎么做?

最佳答案

这就是使用 ActionLIstener 的方法

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

关于java - 选择组合框中的项目时执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15173325/

相关文章:

java - 调整列宽后垂直滚动条消失

java - 使用 DefaultHttpClient 和 Swingworker 实现 cookie 持久化

java - 用鼠标绘图

java - JViewport 是不是定位了它的 View ?

java - 如何在 JButton ActionListener 中调用需要 InterruptedException 的方法

java - 将类实现 ActionListener 转换为线程

java - 如何在java中存储一组唯一的整数数组

java - 如何手动触发 Spring 验证?

java - 无法从 firebase 实时数据库的列表/数组中获取数据

java - 从 Java 服务到 AWS Lambda 和 AWS Gateway API