为了账号安全,请及时绑定邮箱和手机立即绑定

如何将文本字段中的值添加到 eclipse 中的 jcombobox

如何将文本字段中的值添加到 eclipse 中的 jcombobox

胡说叔叔 2021-08-06 10:23:56
嗨,我正在将 java eclipse 与 Swing UI 用于我的学校项目,但我在尝试将输入的值从文本字段添加到组合框时遇到了问题,无论是用户按下 Enter 还是按钮。
查看完整描述

1 回答

?
扬帆大鱼

TA贡献1799条经验 获得超9个赞

假设您有一个按钮:


JButton okButton = new JButton("OK");

要使按钮在单击时执行某些操作,请实现一个 ActionListener:


okButton.addActionListener(new java.awt.event.ActionListener() {

    public void actionPerformed(java.awt.event.ActionEvent evt) {

        // do stuff

    }

});

现在您想从输入字段中读取文本:


JTextField userInput = new JTextField();

并将其添加到组合框:


JComboBox myComboBox = new JComboBox();

也许您的组合框中已经有一些项目,如下所示:


myComboBox.setModel(new DefaultComboBoxModel<>(new String[] { "First Item" }));

无论如何 - 要读取输入并将其添加到组合框,您只需在 ActionListener 方法中执行以下操作:


String userInputText = userInput.getText();  // read the text from the JTextInput

myComboBox.addItem(userInputText);   // add it as a new Item to the combobox

编辑


这是将它们组合在一起的一种方法。它与 Eclipse 或您可以使用的任何其他 IDE 无关。它只是 Java - 你会发现其他/更好的方法将它们组合在一起,你对 Java 了解得越多。希望这可以帮助您入门:


public class MyProgram extends JFrame {

    // here you declare your global variables

    private JTextInput userInput;

    private JButton okButton;

    private JComboBox myComboBox;    


    public MyProgram () {

        // here you create your objects

        okButton = new JButton("OK");

        myComboBox = new JComboBox<>();

        userInput = new JTextField();


        // then you initialize them

        myComboBox.setModel(new DefaultComboBoxModel<>(new String[] { "First Item" }));


        okButton.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {

                 // and that is the code that gets executed once the user clicks the button

                 String userInputText = userInput.getText(); 

                 myComboBox.addItem(userInputText);   

            }

        });

    }


    // this is what Eclipse will propably generate for you so you can launch the program and show your frame:

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {

                new MyProgram().setVisible(true);

            }

        });

    }

}


查看完整回答
反对 回复 2021-08-06
  • 1 回答
  • 0 关注
  • 161 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信