猿问

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

嗨,我正在将 java eclipse 与 Swing UI 用于我的学校项目,但我在尝试将输入的值从文本字段添加到组合框时遇到了问题,无论是用户按下 Enter 还是按钮。


胡说叔叔
浏览 162回答 1
1回答

扬帆大鱼

假设您有一个按钮:JButton okButton = new JButton("OK");要使按钮在单击时执行某些操作,请实现一个 ActionListener:okButton.addActionListener(new java.awt.event.ActionListener() {&nbsp; &nbsp; public void actionPerformed(java.awt.event.ActionEvent evt) {&nbsp; &nbsp; &nbsp; &nbsp; // do stuff&nbsp; &nbsp; }});现在您想从输入字段中读取文本:JTextField userInput = new JTextField();并将其添加到组合框:JComboBox myComboBox = new JComboBox();也许您的组合框中已经有一些项目,如下所示:myComboBox.setModel(new DefaultComboBoxModel<>(new String[] { "First Item" }));无论如何 - 要读取输入并将其添加到组合框,您只需在 ActionListener 方法中执行以下操作:String userInputText = userInput.getText();&nbsp; // read the text from the JTextInputmyComboBox.addItem(userInputText);&nbsp; &nbsp;// add it as a new Item to the combobox编辑这是将它们组合在一起的一种方法。它与 Eclipse 或您可以使用的任何其他 IDE 无关。它只是 Java - 你会发现其他/更好的方法将它们组合在一起,你对 Java 了解得越多。希望这可以帮助您入门:public class MyProgram extends JFrame {&nbsp; &nbsp; // here you declare your global variables&nbsp; &nbsp; private JTextInput userInput;&nbsp; &nbsp; private JButton okButton;&nbsp; &nbsp; private JComboBox myComboBox;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; public MyProgram () {&nbsp; &nbsp; &nbsp; &nbsp; // here you create your objects&nbsp; &nbsp; &nbsp; &nbsp; okButton = new JButton("OK");&nbsp; &nbsp; &nbsp; &nbsp; myComboBox = new JComboBox<>();&nbsp; &nbsp; &nbsp; &nbsp; userInput = new JTextField();&nbsp; &nbsp; &nbsp; &nbsp; // then you initialize them&nbsp; &nbsp; &nbsp; &nbsp; myComboBox.setModel(new DefaultComboBoxModel<>(new String[] { "First Item" }));&nbsp; &nbsp; &nbsp; &nbsp; okButton.addActionListener(new java.awt.event.ActionListener() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void actionPerformed(java.awt.event.ActionEvent evt) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// and that is the code that gets executed once the user clicks the button&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;String userInputText = userInput.getText();&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;myComboBox.addItem(userInputText);&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; &nbsp; // this is what Eclipse will propably generate for you so you can launch the program and show your frame:&nbsp; &nbsp; public static void main(String args[]) {&nbsp; &nbsp; &nbsp; &nbsp; java.awt.EventQueue.invokeLater(new Runnable() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void run() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new MyProgram().setVisible(true);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答