Ben said:
Nope. I have tried it now, and it behaves in a very interesting but
generally useless way.
If the combobox editor is empty, this seems to assign it some text. If
the combobox editor is non-empty, it seems to do absolutely nothing.
It works here.
Getting the item out of the combobox is equally troublesome: the
combobox method returns null sometimes, even when there is text in the
box! There, myComboBox.getEditor().getItem().toString() seems to do the
trick.
But there doesn't seem to be a simple way of changing the text
programmatically in a way that is indistinguishable in its semantics to
the user pasting a line of text into the edit field!
Maybe you could post your code and/or explain better exactly what you're doing
and how it fails.
This code thrown together very quickly in Netbeans does what I expect. I press
jButton1 and it sets the editable text to ONE, press jButton2 and it sets the
text to TWO, regardless of what I have entered into the editable field:
public class TestSetCombo extends javax.swing.JFrame {
public TestSetCombo() {
initComponents();
}
private void initComponents() {
jComboBox1 = new javax.swing.JComboBox();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new java.awt.FlowLayout());
jComboBox1.setEditable(true);
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[]
{ "Item 1", "Item 2", "Item 3", "Item 4" }));
getContentPane().add(jComboBox1);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1);
jButton2.setText("jButton2");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
getContentPane().add(jButton2);
pack();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1.getEditor().setItem("ONE");
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1.getEditor().setItem("TWO");
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TestSetCombo().setVisible(true);
}
});
}
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JComboBox jComboBox1;
}