Originariamente inviato da fermat
in pratica mi duplica sempre le voci sulla textfield.
sennò ottengo la sostituzione di quello che c'è.
Senza complicarti troppo, puoi fare così:
codice:
/**
* @(#)Example.java
*
*
* @author Vincenzo
* @version 1.00 2011/7/5
*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Example extends JFrame implements ItemListener{
JComboBox comboBox;
JTextField textField;
/**
* Creates a new instance of <code>Example</code>.
*/
public Example() {
super("Example");
this.comboBox = new JComboBox(new String[]{"*", "Primo", "Secondo", "Terzo", "Quarto"});
this.comboBox.addItemListener( this );
this.textField = new JTextField();
this.add( this.textField, BorderLayout.NORTH );
this.add( this.comboBox, BorderLayout.CENTER );
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(300, 80);
this.setVisible(true);
}
@Override
public void itemStateChanged(ItemEvent e){
if( e.getStateChange() == ItemEvent.SELECTED && !e.getItem().equals(this.comboBox.getItemAt(0)) ){
String text = this.textField.getText();
this.textField.setText( (text.equals("")) ? e.getItem().toString() : text.concat(", ").concat(e.getItem().toString()) );
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
new Example();
}
}