0

I'm developing my first (extremely basic) Java app. I'm having trouble though with saving user information; specifically, appending user input from a textfield to a JComboBox selection. How do I do this? As of now I have:

String comps[] = {Computer 1, Computer 2, Computer 3}; //array for JComboBox
jcbb = new JComboBox<String>(comps); //create JComboBox

if (ae.getActionCommand().equals("Save")) { //user hits the Save button

        StringBuilder sb = new StringBuilder(); //string to hold data
        sb.append((String) macTF.getText()); //get data from textfield
        sb.append(" ");
        sb.append((String) jcbb.getSelectedItem()); //get JComboBox item
        sb.append(" ");
        //***what to do with the held data?***
    }

I know I'm missing a lot, but just a nudge in the right direction will help. I have been searching through books and the Web, and have found so many different answers, but I cannot apply them. Do I output StringBuilder to text file and load that? Or build an array some how with both sets of data? Or something completely different?

Thanks for any help.

4

2 回答 2

0

您可以使用addItem方法(doc):

if (ae.getActionCommand().equals("Save")) { //user hits the Save button
    String toAdd = (String) macTF.getText(); //get data from textfield
    jcbb.addItem(toAdd); //add String to the combo box
}

另外,您会在这里遇到问题:

String comps[] = {Computer 1, Computer 2, Computer 3}; //array for JComboBox
jcbb = new JComboBox<String>(comps); //create JComboBox

那应该是:

String comps[] = {"Computer 1", "Computer 2", "Computer 3"}; //array for JComboBox
jcbb = new JComboBox(comps); //create JComboBox
于 2012-04-19T20:39:03.287 回答
0

所以一个可能的解决方案如下,虽然缺点是它会由于元素的添加/删除和选择的变化而产生很多事件。但是,这就是您正在寻找的行为

public <E> void replaceComboBoxItem( JComboBox<E> combo, E itemToReplace, E replacement ){
   boolean selected = combo.getSelectedItem() == itemToReplace;
   combo.insertItemAt( replacement, indexOf( combo, itemToReplace ) );
   combo.removeItem( itemToReplace );
   if ( selected ){
      combo.setSelectedItem( itemToReplace );
   }
}
private <E> int indexOf( JComboBox<E> combo, E item ){
  for( int i =0; i < combo.getItemCount(); i++ ){
    if ( combo.getItemAt( i ).equals( item ) ){
       return i;
    }
  }
  return -1;
}

然后你可以使用

replaceComboBoxItem( jcbb, jcbb.getSelectedItem(), sb.toString() );

注意:代码只是在这里输入的,可能包含小的语法错误

于 2012-04-19T20:44:11.603 回答