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("文件夹权限(运维人员使用)");
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.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);
table.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 2、
import 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();
} } 3、
import 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 + "\n");
}
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;
} }
java小工具,使用Swing展示左树右表结构的更多相关文章
- eas左树右表基础资料界面引用为左树右表F7的简单方法
age: /** * 加载配件F7(左树右表) * @param F7Filed 要加载的F7控件 * @param ctx 界面上下文 * @单据 ...
- F9 开发之左树右表中的左树
1 首先在前端应用树树控件 <div class="fui-left"> <div role="head" title="地区选择& ...
- pt-online-schema-change工具使用教程(在线修改大表结构)
percona-toolkit中pt-online-schema-change工具安装和使用 pt-online-schema-change介绍 使用场景:在线修改大表结构 在线数据库的维护中,总会涉 ...
- java小工具:通过URL连接爬取资源(图片)
java语言编写一个简单爬取网站图片工具,实现简单: 通过 java.net.HttpURLConnection 获取一个URL连接 HttpURLConnection 连接成功返回一个java.io ...
- Java小工具 根据文本批量修改文件名
功能 可以根据使用路径修改文件名,已经测试,可以成功运行 思路 先是读取到txt文本文件,之后使用String的spilt进行分割,每一行的格式为 旧名字 新名字,中间的空格可以使用|或者其他字符代替 ...
- JAVA小工具打包
D: cd D:\xxx\IPOSpider javac -d bin/ src/com/xxx/IPOSpider.java src/com/xxx/ConfigProperties.java -c ...
- 【java小工具】从.java文件中筛选出方法,并计算出方法在这些文件中出现的次数
package getMethod; import java.io.*; import java.util.*; import java.util.regex.Matcher; import java ...
- java小工具——timer
定时器Timer 用途:做定时器用的. public static void main(String[] args) { Timer timer = new Timer(); timer.schedu ...
- Java小工具类
计时器(秒表),计算程序运行时间用的 public class Stopwatch { private static long startTime=0; private static long end ...
随机推荐
- try-finally的时候try里面带return
最近学习的JVM小册中老师提了个问题: 最开始我觉得是1,结果程序跑出来是0,感到很疑惑,于是查看了下字节码: 从字节码可以看出: 0:定义变量0 1:将0存入本地变量表slot-0 2:加载slot ...
- C# Socket TCP发送图片与接收图片
如果需要查看更多文章,请微信搜索公众号 csharp编程大全,需要进C#交流群群请加微信z438679770,备注进群, 我邀请你进群! ! ! --------------------------- ...
- 扩展、接管MVC都不会,还会用Spring Boot?
持续原创输出,点击上方蓝字关注我 目录 前言 Spring Boot 版本 如何扩展MVC? 如何自定义一个拦截器? 什么都不配置为什么依然能运行MVC相关的功能? 如何全面接管MVC?[不推荐] 为 ...
- 习题3-3 数数字(Digit Counting , ACM/ICPC Danang 2007, UVa1225)
#include<stdio.h> #include<string.h> int main() { char s[100]; scanf("%s",s); ...
- spring boot:使mybatis访问多个druid数据源(spring boot 2.3.2)
一,为什么要使用多个数据源? 1,什么情况下需要使用多个数据源? 当我们需要访问不同的数据库时,则需要配置配置多个数据源, 例如:电商的业务数据库(包括用户/商品/订单等) 和统 ...
- influxdb集群部署
环境准备 influxdb enterprise运行条件最低需要三个meta nodes节点以及两个data nodes Meta nodes之间使用TCP和Raft一致性协议通信,默认端口为8089 ...
- JS变量作用域与解构赋值
用var变量是有作用域的 变量在函数内部声明时,那么该变量只属于整个函数体,函数外不可调用 当两个不同的函数里,使用了用一个相同的变量名,二者不互相影响,相互独立 遇到嵌套函数时,外部函数不可调用内部 ...
- 实战三:将nacos作为配置中心
一,引入nacos配置中心依赖 <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId&g ...
- ES index not_analyzed
在最初创建索引mapping时,未指定index:not_analyzed "exact_value": { "type": "string" ...
- MYSQL 那些事
1.一条update语句 1.先通过引擎找到对应的行数据,并加锁 2.对行数据进行修改并调用引擎接口修改这条数据,然后释放锁(此时并没有把数据在磁盘上做出修改) 3.redo log在内存中生成这条u ...