java小工具,使用Swing展示左树右表结构

代码直接上:

入口类

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

public class MainPane {

    public static void main(String[] args) throws Throwable {
        
        File file = new File("acl.properties");
        ProperityUtils.loadProperty2System(file.getAbsolutePath());
        //System.out.println(System.getProperty("username"));
        String userId = System.getProperty("username","user");
        String password = System.getProperty("password","pwd");
        String url = System.getProperty("url","http://127.0.0.1/web");
        String json = ""
        String session = Http.sendPost(url, json);
        JSONObject jsonobject = new JSONObject(session);
        String sid = jsonobject.getString("sessionId");
        String user = jsonobject.getString("id");
        String stationId = jsonobject.getString("stationId");
        String getGroupUrl = url;
        System.out.println(getGroupUrl);
        String groups = Http.sendGet(getGroupUrl);
        JSONArray array  = new JSONArray(groups);
        System.out.println(array.length());
        List<FolderMo> mo = new ArrayList<FolderMo>();
        for (int i = 0; i < array.length(); i++) {
            FolderMo fm = new FolderMo(array.getJSONObject(i).getString("name"),
                    array.getJSONObject(i).getString("id"),
                    "");
            mo.add(fm);
        }
        //启动面板
        new ShowPane(sid, stationId, url).start(mo);
    }
}

展示类:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import org.json.JSONArray;
import org.json.JSONObject;
 
public class ShowPane implements MouseListener, ActionListener{

    JPopupMenu popMenu;// 右键菜单
    JMenuItem addItem;// 添加
    JMenuItem delItem;// 删除
    JMenuItem editItem;// 修改
    
    JPopupMenu treePopMenu; //树菜单
    JMenuItem moveItem;// 移动到上一级
    
    JTable table;
    JTree tree;
    
    public String sid;
    
    public String stationId;
    
    public String url;
    
    Map<String,String> map = new HashMap<String, String>();
    
    Map<String,Integer> rowMap = new HashMap<String, Integer>();
    
    public ShowPane(String sid, String stationId, String url) {
        this.sid = sid;
        this.stationId = stationId;
        this.url = url;
        System.out.println(this.url+"="+this.sid+"="+this.stationId);
        popMenu = new JPopupMenu();
        addItem = new JMenuItem("添加");
        addItem.addActionListener(this);
        delItem = new JMenuItem("删除");
        delItem.addActionListener(this);
        editItem = new JMenuItem("提交");
        editItem.addActionListener(this);
        popMenu.add(addItem);
        popMenu.add(delItem);
        popMenu.add(editItem);
        
        treePopMenu = new JPopupMenu();
        moveItem = new JMenuItem("移动到上一级");
        moveItem.addActionListener(this);
        treePopMenu.add(moveItem);
    }



    public void start(List<FolderMo> folder) {
 
       
        DefaultMutableTreeNode top = new DefaultMutableTreeNode(this.stationId);
        DefaultMutableTreeNode node = new DefaultMutableTreeNode("");
        for (FolderMo folderMo : folder) {
            node = new DefaultMutableTreeNode(folderMo);
            top.add(node);
        }
        tree = new JTree(top);
        
        
        Vector<String> columnNames = new Vector<String>(); //设置列名
        columnNames.add("id");
        columnNames.add("type");
        columnNames.add("privileges");
         
         
        Vector<Vector<Object>> rowData = new Vector<Vector<Object>>();
        //Vector<Object> hang = new Vector<Object>();//设置每一行的值  
        //rowData.add(hang);//加入rowData中
        
        DefaultTableModel tablemodel = new DefaultTableModel(rowData,columnNames);
        table = new JTable(tablemodel);
       
        /* TableColumn column = table.getColumnModel().getColumn(1);
        column.setMinWidth(100);
        column.setMaxWidth(300);
        column.setPreferredWidth(150);
        
        column = table.getColumnModel().getColumn(2);
        column.setMinWidth(300);
        column.setMaxWidth(500);
        column.setPreferredWidth(400);*/
        
        JFrame f = new JFrame("demo");
        Box box = Box.createHorizontalBox(); //创建Box 类对象 
        //f.add(tree);
        JScrollPane treePane =  new JScrollPane(tree) {
            /**
             * 
             */
            private static final long serialVersionUID = 1L;

            @Override
               public Dimension getPreferredSize() {
                 return new Dimension(200, 600);
               }
        };
        box.add(treePane, BorderLayout.WEST); 
        box.add(new JScrollPane(table), BorderLayout.EAST); 
        
        f.getContentPane().add(box, BorderLayout.CENTER); 
        f.setLocation(100, 100);
        f.setSize(700, 700);
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 添加选择事件
        tree.addTreeSelectionListener(new TreeSelectionListener() {
 
            @Override
            public void valueChanged(TreeSelectionEvent e) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
                        .getLastSelectedPathComponent();
 
                if (node == null)
                    return;
 
                Object object = node.getUserObject();
                FolderMo folder = (FolderMo) object;
                System.out.println("你选择了:" + folder.showString());
                map.put("folderId", folder.getId());
                //更新表格
                updateTable(folder);
                //更新树
                updateTree(folder,node);
                
            }

            protected void updateTree(FolderMo folder,DefaultMutableTreeNode node) {

                String fs = getFolderList(url, sid, folder.getId());
                if("".equals(fs)) {
                    System.out.println(folder.getName()+"下未查询到子文件夹");
                }else {
                    if(node.isLeaf()) {
                        node.removeAllChildren();
                    }
                    JSONArray array  = new JSONArray(fs);
                    for (int i = 0; i < array.length(); i++) {
                        FolderMo fm = new FolderMo(array.getJSONObject(i).getString("name"),
                                array.getJSONObject(i).getString("id"),
                                array.getJSONObject(i).get("acl").toString());
                        DefaultMutableTreeNode node2 = new DefaultMutableTreeNode(fm);
                        node.add(node2);
                    }
tree.updateUI(); //更新树 tree.expandPath(
new TreePath(node)); } } protected void updateTable(FolderMo folder) { String acl = folder.getAcl(); if("".equals(acl)) { return; } tablemodel.getDataVector().clear(); JSONArray acls = new JSONArray(acl); for (int i = 0; i < acls.length(); i++) { Vector<Object> hang = new Vector<Object>();//设置每一行的值 hang.add(acls.getJSONObject(i).getString("id")); hang.add(acls.getJSONObject(i).getString("type")); hang.add(acls.getJSONObject(i).get("privileges").toString()); rowData.add(hang);//加入rowData中 } tablemodel.setDataVector(rowData, columnNames); //tree.updateUI();
          SwingUtilities.invokeLater(new Runnable(){ 
              public void run(){ 
                tree.updateUI(); 
              } 
           });

                     


            }
        });
        
        tree.addMouseListener(new MouseListener() {
            
            @Override
            public void mouseReleased(MouseEvent e) {
                // TODO Auto-generated method stub
                
            }
            
            @Override
            public void mousePressed(MouseEvent e) {
                TreePath path = tree.getPathForLocation(e.getX(), e.getY());
                if (path == null) {
                    return;
                }
                //System.out.println("当前目录"+path.toString());
                if(path.getPath().length < 3) {
                    System.out.println("当前目录"+path+"不允许上移");
                    return;
                }
                tree.setSelectionPath(path);

                if (e.getButton() == 3) {
                    treePopMenu.show(tree, e.getX(), e.getY());
                }
                
            }
            
            @Override
            public void mouseExited(MouseEvent e) {
                // TODO Auto-generated method stub
                
            }
            
            @Override
            public void mouseEntered(MouseEvent e) {
                // TODO Auto-generated method stub
                
            }
            
            @Override
            public void mouseClicked(MouseEvent e) {
                // TODO Auto-generated method stub
                
            }
        });
        
        table.addMouseListener(new MouseListener() {
            
            @Override
            public void mouseReleased(MouseEvent e) {
                // TODO Auto-generated method stub
                
            }
            
            @Override
            public void mousePressed(MouseEvent e) {
                //获取鼠标右键选中的行
                int row = table.rowAtPoint(e.getPoint());
                if (row == -1) {
                    rowMap.remove("row");
                    return ;
                }else {
                    rowMap.put("row", row);
                }
                //获取已选中的行
                int[] rows = table.getSelectedRows();
                boolean inSelected = false ;
                //判断当前右键所在行是否已选中
                for(int r : rows){
                    if(row == r){
                        inSelected = true ;
                        break ;
                    }
                }
                //当前鼠标右键点击所在行不被选中则高亮显示选中行
                if(!inSelected){
                    table.setRowSelectionInterval(row, row);
                }
                // TODO Auto-generated method stub
                if (e.getButton() == 3) {
                    popMenu.show(table, e.getX(), e.getY());
                }
                
            }
            
            @Override
            public void mouseExited(MouseEvent e) {
                // TODO Auto-generated method stub
                
            }
            
            @Override
            public void mouseEntered(MouseEvent e) {
                // TODO Auto-generated method stub
                
            }
            
            @Override
            public void mouseClicked(MouseEvent e) {
                // TODO Auto-generated method stub
                
            }

        });
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        
        if(e.getSource() == moveItem) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            if (node == null)
                return;
            Object object = node.getUserObject();
            FolderMo folder = (FolderMo) object;
            String moIds = folder.getId();
            System.out.println("当前节点:" + folder.showString());
            node = (DefaultMutableTreeNode)node.getParent();
            object = node.getUserObject();
            folder = (FolderMo) object;
            String targetFolderId = folder.getId();
            System.out.println("当前节点的父节点:" + folder.showString());
            
            String result = moveFolderToUp(moIds,targetFolderId);
            if("".equals(result)) {
                tree.collapsePath(new TreePath(node)); //关闭
            }else {
                System.out.println("移动文件夹失败"+result);
            }
            return;
        }
        
        DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
        if (e.getActionCommand().equals("添加")) {
            tableModel.addRow(new Object[] { "", "Group", "["refRead","write","delete","read","editAcl","create","list"]" });
        }
        if (e.getActionCommand().equals("删除")) {
            //tableModel.removeRow(rowMap.get("row"));// rowIndex是要删除的行序号
            int[] rows = table.getSelectedRows();
            for (int i = 0; i < rows.length; i++) {
                int row = rows[i]-i;
                tableModel.removeRow(row);// rowIndex是要删除的行序号
            }
        }
        if (e.getActionCommand().equals("提交")) {
            // 更新acl
            System.out.println("文件夹Id:" + map.get("folderId"));
            int rowCount = tableModel.getRowCount();
            AclMo[] acls = new AclMo[rowCount]; 
            for (int i = 0; i < rowCount; i++) {
                AclMo mo = new AclMo();
                mo.setId((String)tableModel.getValueAt(i, 0));// 取得第i行第一列的数据
                mo.setType((String)tableModel.getValueAt(i, 1));// 取得第i行第二列的数据
                String privileges = (String)tableModel.getValueAt(i, 2);
                mo.setPrivileges(privileges.replace("[", "").replace("]", "").replaceAll(""", ""));// 取得第i行第三列的数据
                acls[i] = mo;
            }
            System.out.println("更新权限请求参数如下:");
            System.out.println(JSONObject.valueToString(acls));
            String result = updateAcl(map.get("folderId"),JSONObject.valueToString(acls));
            if("".equals(result)) {
                System.out.println(map.get("folderId") + "更新权限成功");
            }else {
                System.out.println(map.get("folderId") +"更新权限失败:"+result);
            }
            
        }

    }

    @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub
        
    }



    @Override
    public void mousePressed(MouseEvent e) {
        //菜单被按下
    }



    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub
        
    }



    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub
        
    }



    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub
        
    }
    
    public String updateAcl(String moId, String acls) {
        
        String result = Http.sendPost2(updateAclUrl,acls);
        return result;
    }
    
    public String moveFolderToUp(String moIds, String targetFolderId) {
        
        String result = Http.sendPost2(moveFolderurl,"");
        return result;
    }

    public static String getFolderList(String url, String sid, String parentId) {
        
        String folders = Http.sendGet(getFolderurl);
        return folders;
    }
}
 

工具类:

1、
https://repo1.maven.org/maven2/org/json/json/20190722/json-20190722.jar

2import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Properties;

public class ProperityUtils {

    public static String loadProperty2System(String location) throws IOException {
        File file = new File(location);
        if (file.isFile() && file.getName().endsWith(".properties")) {
            Properties ppt = new Properties();
            FileInputStream fi = new FileInputStream(file);
            Throwable e = null;

            try {
                ppt.load(fi);
                Iterator<String> iterator = (Iterator<String>) ppt.stringPropertyNames().iterator();

                while (iterator.hasNext()) {
                    String key = iterator.next();
                    System.setProperty(key, ppt.getProperty(key));
                    // if (!System.getProperties().containsKey(key)) {
                    // }
                }
            } catch (Throwable e2) {
                e = e2;
                throw e2;
            } finally {
                if (fi != null) {
                    if (e != null) {
                        try {
                            fi.close();
                        } catch (Throwable e3) {
                            e.addSuppressed(e3);
                        }
                    } else {
                        fi.close();
                    }
                }

            }
        } else {
            System.out.println("“" + location + "”,Can not load any property file.");
        }

        return file.getAbsolutePath();
    }

}

3import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Http {
    
      public static String sendPost2(String u, String param) {
            StringBuffer sbf = new StringBuffer();
            try {
                URL url = new URL(u);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(true);
                connection.addRequestProperty("Content-Type", "application/json");
                connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                connection.connect();
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                if (!"".equals(param)) {
                     // 正文,正文内容其实跟get的URL中 '? '后的参数字符串一致
                  //  String content = "字段名=" + URLEncoder.encode("字符串值", "编码");
                    
                    out.writeBytes(param);
                }
                out.flush();
                out.close();

                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String lines;
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), "utf-8");
                    sbf.append(lines);
                }
                System.out.println(sbf);
                reader.close();
                // 断开连接
                connection.disconnect();
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return sbf.toString();
        }
     /**
     * 发送http POST请求
     *
     * @param
     * @return 远程响应结果
     */
    public static String sendPost(String u, String json) {
        StringBuffer sbf = new StringBuffer();
        try {
            URL url = new URL(u);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.addRequestProperty("role", "Admin");
            connection.addRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            connection.connect();
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            if (!"".equals(json)) {
                out.writeBytes(json);
            }
            out.flush();
            out.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sbf.append(lines);
            }
            System.out.println(sbf);
            reader.close();
            // 断开连接
            connection.disconnect();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return sbf.toString();
    }

    public static String sendGet(String u) {
        StringBuffer sbf = new StringBuffer();
        try {
            URL url = new URL(u);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true); // 设置可输入
            connection.setDoOutput(true); // 设置该连接是可以输出的
            connection.setRequestMethod("GET"); // 设置请求方式
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sbf.append(lines);
            }
            System.out.println(sbf);
            reader.close();
            // 断开连接
            connection.disconnect();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return sbf.toString();
    }

    /**
     * 解决编码问题
     * @param uri
     * @param data
     */
    public void sendGet2(String uri,String data) {
        try {
            URL url = new URL(uri);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setDoInput(true); // 设置可输入
            connection.setDoOutput(true); // 设置该连接是可以输出的
            connection.setRequestMethod("GET"); // 设置请求方式
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

            PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()));
            pw.write(data);
            pw.flush();
            pw.close();

            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line = null;
            StringBuilder result = new StringBuilder();
            while ((line = br.readLine()) != null) { // 读取数据
                result.append(line + "
");
            }
            connection.disconnect();

            System.out.println(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

4、model:

public class FolderMo {
    
    private String name;

    private String id;

    private String acl;
    
    public FolderMo(String n) {
        name = n;
    }

    public FolderMo(String n, String id,String acl) {
        name = n;
        this.id = id;
        this.acl = acl;
    }
    
    public FolderMo() {
    }

    // 重点在toString,节点的显示文本就是toString
    public String toString() {
        return name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getAcl() {
        return acl;
    }

    public void setAcl(String acl) {
        this.acl = acl;
    }

    public String showString() {
        return id+"-"+name;
    }
    
}
public class AclMo {

    private String id;
    
    private String type;
    
    private String privileges;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getPrivileges() {
        return privileges;
    }

    public void setPrivileges(String privileges) {
        this.privileges = privileges;
    }
    
    
    
}

 解决启动乱码:

新建start.bat.输入下面两行

java -Dfile.encoding=utf-8 -jar your.jar
pause

和jar包放置的同一个目录下面

------------------------------------------------------------------------

JTree中调用UpdateUI()报null指针错误 

必须在事件处理线程中操作Swing组件,如果像你的程序中那样需要在别的线程中操作Swing组件的话,要使用下面这样的方法: 
   
SwingUtilities.invokeLater(new   Runnable() 

public   void   run() 

tree.updateUI(); 

});

原文地址:https://www.cnblogs.com/liangblog/p/13976525.html