2009-09-17 2 views
4

2 개의 확인란과 레이블이 포함 된 각 노드에 JTree가 있어야하는 경우가 있습니다 (잠재 확인란을 선택할 때 청취자를 추가 할 수 있음) . 루트 노드 중 하나가 선택되어 있으면 트리 아래의 모든 체크 박스를 선택할 수있는 동일한 레이아웃 (두 개의 JCheckBoxes 및 JLabel이있는 JPanel을 만드는 것으로 가정 함)을 가질 루트 노드가 필요합니다.JCheckBox로 JTree를 만드는 데 도움이 됨

어떤 안내 또는 예입니까? 이전 질문이나 관련 예제를 살펴 보았습니다. 그 중 일부는 트리가 "보이게"되는 지점에 도달 할 수 있지만 그 뒤에 액션을 구현하는 방향을 제시하지 않았습니다.

감사합니다.

답변

5

한 번 봐 이렇게하면 첫 번째 열에서 렌더링 나무를 줄 것이다 이전 JTreeTable 코드를 볼 수있는 좋은 시간, 각 열의 셀을 렌더링 할 수있는 자유 수 있습니다 귀하가 원하는 경우 트리 노드의 오른쪽, 확인란 및 레이블을 넣고 JTable에서 TableCellEditors를 사용하게 할 수 있습니다. 경고는 링크의 코드가 작동하지만 약간 뒤얽힌 것입니다.

다른 대안이 있습니다. NetBeans에서 제공하는 Outline이라는 더 나은 것으로 간주되는 트리 테이블 구현을 데모했습니다 (NetBeans IDE로 개발할 필요는 없지만 jar 만 필요함). This article은 시작하는 것이 얼마나 쉬운지를 나타냅니다.

약 30 분 만에 Eclipse의 개요 트리 테이블 (프로젝트에 가져온 org-netbeans-swing-outline.jar 포함)의 간단한 예제를 실습 할 수있었습니다 :

private void buildFrame() { 
    frame = new JFrame("Demo"); 
    frame.setSize(300, 300); 
    addStuffToFrame(); 
    frame.setVisible(true); 

} 


private void addStuffToFrame() { 
    MyTreeNode top = new MyTreeNode("top"); 
    createNodes(top); 
    DefaultTreeModel model = new DefaultTreeModel(top);  
    //here are the netBeans tree table classes 
    OutlineModel outlineModel = 
      DefaultOutlineModel.createOutlineModel(model, new MyRowModel()); 
    Outline outline = new Outline(); 
    outline.setRootVisible(true); 
    outline.setModel(outlineModel); 
    frame.getContentPane().add(new JScrollPane(outline)); 
} 

private void createNodes(MyTreeNode top) { 
    MyTreeNode child = new MyTreeNode("child 2"); 
    top.add(new MyTreeNode("child 1")); 
    child.add(new MyTreeNode("g-child1")); 
    child.add(new MyTreeNode("g-child2")); 
    child.add(new MyTreeNode("g-child3")); 
    top.add(child); 
    top.add(new MyTreeNode("child3")); 
    top.add(new MyTreeNode("child4")); 

} 

은 내가 JTable 's에 내장 된 체크 박스 렌더링 mechnanism과 잘 연동됩니다 Boolean의를 개최하는 TreeNode를을 만들 수 있습니다.

public class MyTreeNode extends DefaultMutableTreeNode { 
    Boolean data1 = null; 
    Boolean data2 = null; 
    String name = null; 
    MyTreeNode (String name) { 
     this.name=name; 
    } 

    void setData1(Boolean val) {data1=val;} 
    void setData2(Boolean val) {data2=val;} 
    Boolean getData1() {return data1;} 
    Boolean getData2() {return data2;} 
    String getName() {return name;} 

} 

넷빈즈 RowModel 대신 간단한의 JTree의이 테이블을 만드는 열쇠입니다 :

alt text http://img17.imageshack.us/img17/6643/picture1hz.png

: 여기

public class MyRowModel implements RowModel { 

    public Class getColumnClass(int col) { 
     switch (col) { 
     case 0: return String.class; 
     case 1: return Boolean.class; //these return class definitions will 
     case 2: return Boolean.class; //trigger the checkbox rendering 
     default:return null;  
     } 
    } 

    public int getColumnCount() { 
     return 3; 
    } 

    public String getColumnName(int col) { 
     return ""; 
    } 

    public Object getValueFor(Object node, int col) { 
     MyTreeNode n = (MyTreeNode)node; 
     switch (col) { 
     case 0: return n.getName(); 
     case 1: return n.getData1(); 
     case 2: return n.getData2(); 
     default:return null; 
     } 
    } 

    public boolean isCellEditable(Object node, int col) { 
     return col > 0; 
    } 

    public void setValueFor(Object node, int col, Object val) { 
     MyTreeNode n = (MyTreeNode)node; 
     if (col == 1)  {n.setData1((Boolean)val);} 
     else if (col == 2) {n.setData2((Boolean)val);} 
     //EDIT: here is a recursive method to set all children 
     //  selected for one of the two checkboxes as it is 
     //  checked by the parent 
     for (Enumeration children = n.children(); 
         children.hasMoreElements();) { 
      MyTreeNode child = (MyTreeNode) children.nextElement(); 
      setValueFor(child, col, val); 
     } 


    } 

} 

단순한이기는하지만, 완성 된 제품입니다 setValueFor 메소드를 업데이트하여 노드의 하위를 반복하고 부모가 수정되었을 때 선택되거나 선택 해제 된 체크 박스를 설정합니다. 디.

0

buildFrame(), addStuffToFrame() 및 createNodes() 메소드가 어디에 있는지 분명하지 않았습니다. 나는 JFrame을 확장하고 프레임을 삭제 한 OutlineJFrame 클래스에 이들을 모두 넣었습니다. 어디서든 등장한 서언. 그런 다음 내 프로젝트의 main() 메서드에서 OutlineJFrame 객체 중 하나를 만들고 그 객체를 true로 설정했습니다. 그것이 실행되면 크기를 조정할 수 있지만 빈 창이 나타납니다. 행이 어디에 있니? 노드는 어디에 있습니까?

그런 다음 NetBeans의 전문가 인 Geertjan에게 내가 잘못하고있는 것을 물어 보았습니다. 그리고 그는 저에게 다시 글쓰기를 보냈습니다. 그러나 그것은 같은 행동을했습니다.

하지만 필자는 다른 데모 프로젝트 (FileTreeJFrame)가 outline.java 객체를 표시하기 때문에 내 Java가 훌륭하다는 것을 알고 있습니다.

+0

여전히'addStuffToFrame()'메소드를 호출해야합니다. 그것은'Outline'을 설정하고'JFrame'에 표시를 추가하는 것입니다. 내가 거기에 넣은 방법은 데모 응용 프로그램의 목적을위한 것임을 유의하십시오. – akf