我想创建一个combobox
和一个textbox
。用户将在文本框中输入文本,文本将作为combobox
项添加。
我该怎么办?我写了一段代码,但我找不到我在actionlistener
写的内容。
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Q2 extends JFrame {
JTextField t;
JComboBox combobox = new JComboBox();
public Q2() {
t = new JTextField("Enter text here", 20);
t.setEditable(true);
t.addActionListener(new act());
add(t);
add(combobox);
combobox.addItem(t.getText().toString());
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
setVisible(true);
}
public class act implements ActionListener {
public void actionPerformed(ActionEvent e) {
}
}
public static void main(String[] args) {
Q2 test = new Q2();
}
}
答案 0 :(得分:0)
我添加了一个按钮,并将功能添加到按钮上的JComboBox
。这是一个例子:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Q2 extends JFrame {
JTextField t;
JComboBox combobox;
JButton b;
public Q2() {
combobox = new JComboBox();
t = new JTextField("Enter text here", 20);
t.setEditable(true);
b = new JButton("Add");
b.addActionListener(new act()); //Add ActionListener to button instead.
add(t);
add(combobox);
add(b);
//combobox.addItem(t.getText().toString()); //Moved to ActionListener.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
setVisible(true);
}
public class act implements ActionListener {
public void actionPerformed(ActionEvent e) {
combobox.addItem(t.getText()); //Removed .toString() because it returns a string.
}
}
public static void main(String[] args) {
Q2 test = new Q2();
}
}
答案 1 :(得分:0)
private JTextComponent comboboxEditor;
Vector ComboData = new Vector();
public void addActionListners() {
//adding action listner to the NameComboBox
this.comboboxEditor = (JTextComponent) yourCombo.getEditor().getEditorComponent();
comboboxEditor.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent evt) {
int i = evt.getKeyCode();
if (i == 10) {
//combobox action on enter
ComboData.add(comboboxEditor.getText());
yourCombo.setListData(ComboData);
}
}
});
}
您必须将comboBox中的editable属性设置为true,否则您将无法在comboBox上编写。确保调用addActionListners()方法 在启动时(构造函数)。我通过将组合框的编辑器更改为jtextComponent来为组合框提供jtext字段的功能。试试这个例子