【问题标题】:how to add values from a textfield to a jcombobox in eclipse [closed]如何在eclipse中将文本字段中的值添加到jcombobox [关闭]
【发布时间】:2018-08-22 12:42:22
【问题描述】:

您好,我正在为我的学校项目使用带有 Swing UI 的 java eclipse,我无法尝试将输入的值从文本字段添加到组合框,无论是通过用户按 Enter 还是按钮。

【问题讨论】:

标签: java eclipse swing combobox jbutton


【解决方案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 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);
            }
        });
    }
}

【讨论】:

  • 在初始化 JFrame 时执行此操作。在您创建按钮后,您可以将代码放入 okButton.addActionListener.... 。然后将注释// do stuff 替换为单击按钮时要执行的代码。
  • 执行此操作后,我留下了错误 myComboBox 无法解析
  • 使所有 GUI 对象成为全局对象更容易。无论如何,您周围的 JFrame 对象都会在那里,因此将您的按钮和组合框设置为全局并没有什么坏处。所以,private JComboBox myComboBox; 当你初始化它时使用this.myComboBox = new JComboBox();。然后你也可以在 actionListener 中解决它。
  • 对不起,我对 eclipse 很陌生,初始化和私有 jcombobox 是什么意思,我应该把这些放在哪里
  • 我编辑了我的答案并提供了一个完整的例子。希望这有助于得到一个想法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-06
  • 2014-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多