Allora, una cosa del genere?
codice:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
/**
*
* @author Andrea
*/
public class JComboBoxModelTest extends JFrame {
private class MyComboBoxModel extends DefaultComboBoxModel {
private Object[] elements;
public MyComboBoxModel(Object[] elements) {
super(elements);
this.elements = elements;
}
}
private class MyComboBoxActionListener implements ActionListener {
int index = 0;
public void actionPerformed (ActionEvent ae) {
if (!ae.getActionCommand().equalsIgnoreCase("comboboxedited") && box1.getSelectedIndex() != -1) {
index = box1.getSelectedIndex();
}
else {
box1.insertItemAt(box1.getEditor().getItem(), index);
box1.removeItemAt(index+1);
}
}
}
private JComboBox box1,box2;
private MyComboBoxModel commonModel;
private JFrame openWindow;
private String[] elements = {"pera", "banana", "mela", "anguria", "melone", "ciliegia"};
/** Creates a new instance of JComboBoxModelTest */
public JComboBoxModelTest() {
super("Test JComboBox");
this.setSize(300,500);
this.setLayout(new BorderLayout());
commonModel = new MyComboBoxModel(elements);
box1 = new JComboBox(commonModel);
box1.setEditable(true);
box1.addActionListener(new MyComboBoxActionListener());
box2 = new JComboBox(commonModel);
this.getContentPane().add(box1, BorderLayout.NORTH);
openWindow = new JFrame("Text JComboBox 2");
openWindow.setSize(300,500);
openWindow.getContentPane().add(box2, BorderLayout.NORTH);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
openWindow.setLocation(0,400);
openWindow.setVisible(true);
}
public static void main (String[] args) {
new JComboBoxModelTest();
}
}
Magari personalizza l'actionPerformed perché allo stato attuale puoi solo editare elementi e non aggiungerne di nuovi...