2011-09-29 2 views
3

테이블이 있습니다. 해당 테이블 업데이트 데이터베이스의 변경 사항. 하나의 열은 해당 테이블의 JComboBox에 의해 편집됩니다. 해당 열의 셀을 클릭하면 tableChanged 이벤트가 발생합니다. 그러나 JComboBox의 항목을 선택한 후에 해고해야합니다. 선택 후에 tableChanged를 어떻게 만들 수 있습니까?JComboBox를 사용자 정의 TableCellEditor로 사용

public class JIDCellEditor extends AbstractCellEditor implements TableCellEditor { 

    JComboBox jComboBox; 

    @Override 
    public Object getCellEditorValue() { 
     return jComboBox.getSelectedItem(); 
    } 

    @Override 
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { 
     Vector vector = new Vector(); 
     vector.add(0); 
     for (int i = 0; i < table.getRowCount(); i++) { 
      if (!vector.contains(table.getValueAt(i, 0)) && table.getValueAt(i, 3).toString().equals("Female")) { 
       vector.add(table.getValueAt(i, 0)); 
      } 
     } 
     vector.remove(table.getValueAt(row, 0)); 
     jComboBox = new JComboBox(vector); 
     jComboBox.setSelectedItem(value); 
     return jComboBox; 
    } 
} 
+0

편집기에 콤보 상자를 사용하십시오. 자습서와이 포럼의 게시물에서이 작업을 수행하는 방법에 대한 몇 가지 예가 있습니다. 나는 그것을 시도해보고, 실패 할 경우 최선의 시도를 보여주는 [SSCCE] (http://SSCCE.org)를 게시하십시오. –

+0

편집기 용 콤보 박스를 사용합니다. – MOD

+1

또한, 마치 당신이 당신의 questio에 입력을 끝내지 않은 것처럼 보입니다. –

답변

4

이제 작동합니다. getTableCellEditorComponent 메서드가 호출 될 때마다 JComboBox를 다시 초기화해야합니다. 그리고이 JComboBox의 itemstatechange에서 stopCellEditing() 메서드는 항목이 선택되었을 때 편집이 완료되었음을 리스너에게 알려야합니다. 이것에 의해, TableModelListener의 fireTableChanged 이벤트가 작성됩니다. (고정) 그러나 선택하지 않고 다른 JComboBox를 클릭 한 후 JComboBox를 클릭하면 해당 이벤트가 발생합니다. (/ 고정)

편집 : 다음 코드는 마지막 버전입니다. 이 TableModelListener에 의해, 항목이 선택되고있는 경우에게만 통지됩니다. 위의 문제는 해결되었습니다. 기본 stopCellEditing() 메소드가 항상 true를 리턴했기 때문입니다. 이로 인해 예상치 못한 방식으로 셀 편집이 중지됩니다. 필요에 따라 재정의되어야하고 fireEditingStopped(); TableModelListener에 통지하는 데 사용해야합니다.

public class JIDCellEditor extends AbstractCellEditor implements TableCellEditor { 

    private JComboBox jComboBox = new JComboBox(); 
    boolean cellEditingStopped = false; 

    @Override 
    public Object getCellEditorValue() { 
     return jComboBox.getSelectedItem(); 
    } 

    @Override 
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { 
     Vector vector = new Vector(); 
     ArrayList<Integer> arrayList = new ArrayList<Integer>(); 
     arrayList.add(Integer.parseInt(value.toString())); 
     vector.add(0); 
     for (int i = 0; i < table.getRowCount(); i++) { 
      if (!vector.contains(table.getValueAt(i, 0)) && table.getValueAt(i, 3).toString().equals("Sheep")) { 
       vector.add(table.getValueAt(i, 0)); 
      } 
     } 
     vector.remove(table.getValueAt(row, 0)); 

     for (int i = 0; i < vector.size(); i++) { 
     } 
     jComboBox = new JComboBox(vector); 
     jComboBox.setSelectedItem(value); 

     jComboBox.addItemListener(new ItemListener() { 

      @Override 
      public void itemStateChanged(ItemEvent e) { 
       if (e.getStateChange() == ItemEvent.SELECTED) { 
        fireEditingStopped(); 
       } 
      } 
     }); 
     jComboBox.addPopupMenuListener(new PopupMenuListener() { 

      @Override 
      public void popupMenuWillBecomeVisible(PopupMenuEvent e) { 
       cellEditingStopped = false; 
      } 

      @Override 
      public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { 
       cellEditingStopped = true; 
       fireEditingCanceled(); 
      } 

      @Override 
      public void popupMenuCanceled(PopupMenuEvent e) { 

      } 
     }); 
     return jComboBox; 
    } 

    @Override 
    public boolean stopCellEditing() { 
     return cellEditingStopped; 
    } 
} 
6

내가보기 엔 ComboBoxCellEditor 구성 요소가 SwingX를 사용하는 것이 좋습니다 것입니다. 그것은 본질적으로 스윙 구성 요소가 가져야하는 기능을위한 Sun의 인큐베이터입니다. 프로젝트가 여전히 활발하게 개발되었는지는 모르지만 성숙한 프로젝트인지 많은 프로젝트에서 사용했습니다.

참고 : 어떤 이유로, 당신은 나 외부 라이브러리를 사용하지 않을 수없는 경우

가 여기에 그대로 의견 (사용자 정의 SwingX 기능을 제거하기 위해 수정 부품) 자신의 코드입니다 라이브러리는 GPL 코드입니다.

/* 
* $Id: ComboBoxCellEditor.java 3738 2010-07-27 13:56:28Z bierhance $ 
* 
* Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved. 
* 
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as 
* published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. 
* 
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of 
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. 
* 
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software 
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 
*/ 

import java.awt.event.ActionEvent; 
import java.awt.event.MouseEvent; 
import java.util.EventObject; 

import javax.swing.DefaultCellEditor; 
import javax.swing.JComboBox; 

/** 
* <p> 
* This is a cell editor that can be used when a combo box (that has been set up for automatic completion) is to be used in a JTable. The 
* {@link javax.swing.DefaultCellEditor DefaultCellEditor} won't work in this case, because each time an item gets selected it stops cell 
* editing and hides the combo box. 
* </p> 
* <p> 
* Usage example: 
* </p> 
* <p> 
* 
    * <pre> 
* <code> 
* JTable table = ...; 
* JComboBox comboBox = ...; 
* ... 
* TableColumn column = table.getColumnModel().getColumn(0); 
* column.setCellEditor(new ComboBoxCellEditor(comboBox)); 
* </code> 
* </pre> 
* 
* </p> 
*/ 
public class ComboBoxCellEditor extends DefaultCellEditor { 

    /** 
    * Creates a new ComboBoxCellEditor. 
    * 
    * @param comboBox the comboBox that should be used as the cell editor. 
    */ 
    public ComboBoxCellEditor(final JComboBox comboBox) { 
     super(comboBox); 

     comboBox.removeActionListener(this.delegate); 

     this.delegate = new EditorDelegate() { 
      @Override 
      public void setValue(final Object value) { 
       comboBox.setSelectedItem(value); 
      } 

      @Override 
      public Object getCellEditorValue() { 
       return comboBox.getSelectedItem(); 
      } 

      @Override 
      public boolean shouldSelectCell(final EventObject anEvent) { 
       if (anEvent instanceof MouseEvent) { 
        final MouseEvent e = (MouseEvent) anEvent; 
        return e.getID() != MouseEvent.MOUSE_DRAGGED; 
       } 
       return true; 
      } 

      @Override 
      public boolean stopCellEditing() { 
       if (comboBox.isEditable()) { 
        // Commit edited value. 
        comboBox.actionPerformed(new ActionEvent(ComboBoxCellEditor.this, 0, "")); 
       } 
       return super.stopCellEditing(); 
      } 

      @Override 
      public void actionPerformed(final ActionEvent e) { 
       ComboBoxCellEditor.this.stopCellEditing(); 
      } 
     }; 
     comboBox.addActionListener(this.delegate); 
    } 
} 
+0

이것은 ComboBox 항목을 선택한 후에 tableChanged 이벤트를 발생시키고 다른 항목이있는 셀에서 JComboBox를 사용할 수있게 할 것입니까? – MOD

+0

그래, 다른 셀의 동일한 콤보 박스를 사용할 수 있지만 콤보 박스에서 사용할 수있는 값은 동일합니다. 드롭 다운의 값을 다르게하려면 startCellEditing()을 덮어 쓰고 거기에서 값을 채 웁니다. –

+0

어떻게 시작할 수 있습니다 .CellEditing()? – MOD

관련 문제