嗨,我正在将 java eclipse 与 Swing UI 用于我的学校项目,但我在尝试将输入的值从文本字段添加到组合框时遇到了问题,无论是用户按下 Enter 还是按钮。
胡说叔叔
浏览 162回答 1
1回答
扬帆大鱼
假设您有一个按钮: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 JTextInputmyComboBox.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); } }); }}