2009-11-24 7 views
1

사용자가 색인이 1 인 항목을 선택하고 "123"을 "abcd"로 변경하면 "123"대신 "abcd"를 설정할 수 있습니까 (NetBeans에서)? 또한 항목을 영원히 삭제할 수 있습니까?편집 가능한 JComboBox

+0

사용자가 설정 "ABCD"무엇을 의미합니까. 모델의 값을 변경 하시겠습니까? 그렇다면 어떤 모델을 사용합니까? –

+0

나는 "123"을 "abcd"로 바꾸고 싶다. 또한 기본 모델과 setEditable (true)을 사용하여 편집 가능한 ComboBox로 만듭니다. – Johanna

+0

다른 게시물에 제공된 제안 사항을 읽지 않는다면이 게시물에서 제안을하는 데 시간 낭비가 될 것입니다. – camickr

답변

1

다음을 시도해보십시오. 사용자가 값을 변경하고 [ENTER]를 누르면 이전 값이 제거되고 새 값이 추가됩니다.

같은 위치에서 값을 대체해야하는 경우 특정 위치에 값을 추가 할 수있는 고유 한 모델을 제공해야합니다.

final DefaultComboBoxModel model = new DefaultComboBoxModel(new String[] {"Red", "Green", "Blue"}); 

comboBox = new JComboBox(model); 
comboBox.setEditable(true); 
comboBox.addActionListener(new ActionListener() { 
    private int selectedIndex = -1; 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     int index = comboBox.getSelectedIndex(); 
     if(index >= 0) { 
      selectedIndex = index; 
     } 
     else if("comboBoxEdited".equals(e.getActionCommand())) { 
      Object newValue = model.getSelectedItem(); 
      model.removeElementAt(selectedIndex); 
      model.addElement(newValue); 
      comboBox.setSelectedItem(newValue); 
      selectedIndex = model.getIndexOf(newValue); 
     } 
    } 
}); 
comboBox.setSelectedIndex(0); 
+0

니스! 하지만 귀하의 코드로, 나는 그 이상, 왜 한 항목을 삭제할 수 있습니까 ?? – Johanna

+0

코드를 직접 디버그하여 어떤 일이 일어나는지 볼 수 있습니다! – camickr

+0

행을 삭제할 때 확실하지 않은 경우 ... 사용자가 입력을 지울 때 삭제하려는 경우 요소를 다시 추가하기 전에이를 확인하십시오 –

0

How to Use Combo Boxes

Editable combo box, before and after the arrow button is clicked http://java.sun.com/docs/books/tutorial/figures/uiswing/components/EditableComboBoxMenuMetal2.png

편집 가능한 콤보 상자, 전에 튜토리얼을 읽고 후 화살표 버튼을

가보기를 클릭 : 편집 가능한 콤보 상자 섹션을 사용 을 . 해당 페이지에서

발췌문 :

JComboBox patternList = new JComboBox(patternExamples); 
patternList.setEditable(true); 
patternList.addActionListener(this);