Swing使用总结

一、JTree :

http://hi.baidu.com/beer_zh/blog/item/5c135c8f4d7ad1ebf11f3666.html

http://blog.csdn.net/arjick/article/details/4526692 

1、常用方法:

(1)、选择模式改成只能单选

tree.getSelectionModel().setSelectionModel(TreeSelectionModel.SINGLE_TREE_SELECTION);

(2)、取得选中的节点

(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();

(3)、选中某个节点

TreePath newPath = new TreePath(node.getPath());

tree.expandPath(newPath);

tree.setSelectionPath(newPath); 

(3)、当鼠标双击了树节点时做一些事

tree.addMouseListener(new MouseAdapter(){

     @override

      public void mouseClicked(MouseEvent e){

        JTree sourceTree = (JTree)e.getSource();

        int count = sourceTree.getRowForLocation(e.getX(),e.getY());

        DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();

        if(count >= 0 && e.getClickCount() ==2 ){

            //todo

        }

      }

});

(4)、遍历一棵树的节点

private DefaultMutableTreeNode getNodeByName(String nodeName){

  Enumeration enu = root.breadFirstEnumeration();

  while(enu.hasMoreElements()){

    DefaultMutableTreeNode n = (DefaultMutableTreeNode)enu.nextElement();

    Object obj = n.getUserObject();

    if(null != obj){

        if(obj.toString().equals(nodeName)){//树节点的名字等于obj.toString(),欲正确显示节点名,你需要订制toString()方法

              return n;

        }

    }

  }

  return null;

}

二、JScrollPane:

1、不要试图将一个BorderLayout或者其他什么你常用的Layout设置给一个JScrollPane对象,否则程序会挂掉而且你很难查出问题。

三、JComboBox:

1、在使用addItem(Object obj)方法设值的时候,使用的是obj的equals()方法,所以大部分时候都需要手动改写equals方法才可以。 

在填充一个combobox对象并给出默认选择项的时候,可以用下面两个方法。

public class ComboboxUtil{

  public static List fillCombos(JComboBox combo,List contents){
     List result = new ArrayList();
     for(Object obj:contents){
       combo.addItem(obj);
       result.add(obj);
     }  
     return result;
  }

  public static void fillCombos(JComboBox combo,List content,Object target){
    List objs = fillCombos(combo,content);
    if(null != target){
      Object temp = null;
       for(Object t:objs){
         if(null != t && t.equals(target)){
           temp = t;
           break;
         }
       }
       if(null != temp){
         combo.setSelectedItem(temp);
       }
    }
  }
}
原文地址:https://www.cnblogs.com/mabaishui/p/2507759.html