1 回答
![?](http://img1.sycdn.imooc.com/54584f850001c0bc02200220-100-100.jpg)
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);
}
});
}
}
添加回答
举报