javaswing json格式化工具

效果展示

在這里插入圖片描述
代碼

package com.example.springbootdemo;import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;public class AdvancedJsonViewerGUI extends JFrame {private JTextArea inputTextArea;private JTextArea outputTextArea;private JTree jsonTree;private DefaultTreeModel treeModel;private JButton formatButton;private JButton validateButton;private JButton clearButton;private JButton copyButton;private JButton minifyButton;private JButton sampleButton;private JButton treeViewButton;private JLabel statusLabel;private JCheckBox autoFormatCheckBox;private JTabbedPane outputTabbedPane;private ObjectMapper objectMapper;public AdvancedJsonViewerGUI() {objectMapper = new ObjectMapper();initializeComponents();setupLayout();setupEventHandlers();setupWindow();}private void initializeComponents() {// 輸入區域inputTextArea = new JTextArea(15, 50);inputTextArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));inputTextArea.setBorder(new TitledBorder("輸入JSON (Input JSON)"));inputTextArea.setLineWrap(true);inputTextArea.setWrapStyleWord(true);// 輸出區域 - 文本視圖outputTextArea = new JTextArea(15, 50);outputTextArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));outputTextArea.setBorder(new TitledBorder("格式化結果 (Formatted Result)"));outputTextArea.setEditable(false);outputTextArea.setLineWrap(true);outputTextArea.setWrapStyleWord(true);// 輸出區域 - 樹形視圖DefaultMutableTreeNode root = new DefaultMutableTreeNode("JSON");treeModel = new DefaultTreeModel(root);jsonTree = new JTree(treeModel);jsonTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);jsonTree.setShowsRootHandles(true);jsonTree.setEditable(false);jsonTree.setBorder(new TitledBorder("樹形視圖 (Tree View)"));// 標簽頁面板outputTabbedPane = new JTabbedPane();outputTabbedPane.addTab("文本視圖 (Text View)", new JScrollPane(outputTextArea));outputTabbedPane.addTab("樹形視圖 (Tree View)", new JScrollPane(jsonTree));// 按鈕formatButton = new JButton("格式化 (Format)");validateButton = new JButton("驗證 (Validate)");clearButton = new JButton("清空 (Clear)");copyButton = new JButton("復制結果 (Copy)");minifyButton = new JButton("壓縮 (Minify)");sampleButton = new JButton("示例 (Sample)");treeViewButton = new JButton("生成樹 (Build Tree)");// 復選框autoFormatCheckBox = new JCheckBox("自動格式化 (Auto Format)", false);// 狀態標簽statusLabel = new JLabel("就緒 (Ready)");statusLabel.setForeground(Color.BLUE);}private void setupLayout() {setLayout(new BorderLayout());// 頂部面板 - 按鈕區域JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));topPanel.add(formatButton);topPanel.add(validateButton);topPanel.add(minifyButton);topPanel.add(copyButton);topPanel.add(clearButton);topPanel.add(sampleButton);topPanel.add(treeViewButton);topPanel.add(autoFormatCheckBox);// 中部面板 - 文本區域JPanel textPanel = new JPanel(new GridLayout(1, 2, 10, 0));JPanel inputPanel = new JPanel(new BorderLayout());inputPanel.add(new JScrollPane(inputTextArea), BorderLayout.CENTER);textPanel.add(inputPanel);textPanel.add(outputTabbedPane);// 底部狀態欄JPanel statusPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));statusPanel.add(statusLabel);add(topPanel, BorderLayout.NORTH);add(textPanel, BorderLayout.CENTER);add(statusPanel, BorderLayout.SOUTH);}private void setupEventHandlers() {// 格式化按鈕formatButton.addActionListener(e -> formatJson());// 驗證按鈕validateButton.addActionListener(e -> validateJson());// 清空按鈕clearButton.addActionListener(e -> clearAll());// 復制按鈕copyButton.addActionListener(e -> copyToClipboard());// 壓縮按鈕minifyButton.addActionListener(e -> minifyJson());// 示例按鈕sampleButton.addActionListener(e -> loadSample());// 樹形視圖按鈕treeViewButton.addActionListener(e -> buildTreeView());// 自動格式化autoFormatCheckBox.addActionListener(e -> {if (autoFormatCheckBox.isSelected()) {inputTextArea.addKeyListener(new KeyAdapter() {@Overridepublic void keyReleased(KeyEvent e) {// 延遲執行格式化,避免頻繁觸發Timer timer = new Timer(500, ev -> formatJson());timer.setRepeats(false);timer.start();}});showStatus("已啟用自動格式化", Color.GREEN);}});// 輸入區域按鍵監聽inputTextArea.addKeyListener(new KeyAdapter() {@Overridepublic void keyPressed(KeyEvent e) {// Ctrl+Enter 格式化if (e.getKeyCode() == KeyEvent.VK_ENTER && e.isControlDown()) {formatJson();}}});}private void setupWindow() {setTitle("高級JSON查看器 - Advanced JSON Viewer");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);pack();setLocationRelativeTo(null);setResizable(true);setMinimumSize(new Dimension(900, 700));}private void formatJson() {String input = inputTextArea.getText().trim();if (input.isEmpty()) {showStatus("請輸入JSON內容", Color.RED);return;}try {JsonNode jsonNode = objectMapper.readTree(input);String formattedJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);outputTextArea.setText(formattedJson);showStatus("格式化成功", Color.GREEN);} catch (Exception e) {outputTextArea.setText("錯誤: 無效的JSON格式\n\n" + e.getMessage());showStatus("格式化失敗: " + e.getMessage(), Color.RED);}}private void minifyJson() {String input = inputTextArea.getText().trim();if (input.isEmpty()) {showStatus("請輸入JSON內容", Color.RED);return;}try {JsonNode jsonNode = objectMapper.readTree(input);String minifiedJson = objectMapper.writeValueAsString(jsonNode);outputTextArea.setText(minifiedJson);showStatus("壓縮成功", Color.GREEN);} catch (Exception e) {outputTextArea.setText("錯誤: 無效的JSON格式\n\n" + e.getMessage());showStatus("壓縮失敗: " + e.getMessage(), Color.RED);}}private void validateJson() {String input = inputTextArea.getText().trim();if (input.isEmpty()) {showStatus("請輸入JSON內容", Color.RED);return;}try {objectMapper.readTree(input);showStatus("? 有效的JSON格式", Color.GREEN);JOptionPane.showMessageDialog(this, "? 有效的JSON格式", "驗證結果", JOptionPane.INFORMATION_MESSAGE);} catch (Exception e) {showStatus("? 無效的JSON格式", Color.RED);JOptionPane.showMessageDialog(this, "? 無效的JSON格式:\n" + e.getMessage(), "驗證結果", JOptionPane.ERROR_MESSAGE);}}private void copyToClipboard() {String output = outputTextArea.getText();if (!output.isEmpty()) {StringSelection stringSelection = new StringSelection(output);Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();clipboard.setContents(stringSelection, null);showStatus("結果已復制到剪貼板", Color.GREEN);} else {showStatus("沒有內容可復制", Color.RED);}}private void clearAll() {inputTextArea.setText("");outputTextArea.setText("");treeModel.setRoot(new DefaultMutableTreeNode("JSON"));showStatus("已清空", Color.BLUE);}private void loadSample() {String sampleJson = "{\n" +"  \"name\": \"張三\",\n" +"  \"age\": 30,\n" +"  \"email\": \"zhangsan@example.com\",\n" +"  \"address\": {\n" +"    \"street\": \"長安街100號\",\n" +"    \"city\": \"北京\",\n" +"    \"zipcode\": \"100000\"\n" +"  },\n" +"  \"skills\": [\"Java\", \"Python\", \"JavaScript\"],\n" +"  \"married\": true,\n" +"  \"children\": null,\n" +"  \"projects\": [\n" +"    {\n" +"      \"name\": \"項目A\",\n" +"      \"duration\": 12,\n" +"      \"technologies\": [\"Spring\", \"React\"]\n" +"    },\n" +"    {\n" +"      \"name\": \"項目B\",\n" +"      \"duration\": 8,\n" +"      \"technologies\": [\"Node.js\", \"Vue.js\"]\n" +"    }\n" +"  ]\n" +"}";inputTextArea.setText(sampleJson);showStatus("已加載示例數據", Color.BLUE);}private void buildTreeView() {String input = inputTextArea.getText().trim();if (input.isEmpty()) {showStatus("請輸入JSON內容", Color.RED);return;}try {JsonNode jsonNode = objectMapper.readTree(input);DefaultMutableTreeNode root = new DefaultMutableTreeNode("JSON");buildTreeNodes(jsonNode, root, "root");treeModel.setRoot(root);outputTabbedPane.setSelectedIndex(1); // 切換到樹形視圖showStatus("樹形視圖構建成功", Color.GREEN);} catch (Exception e) {showStatus("構建樹形視圖失敗: " + e.getMessage(), Color.RED);}}private void buildTreeNodes(JsonNode jsonNode, DefaultMutableTreeNode parent, String fieldName) {if (jsonNode.isObject()) {DefaultMutableTreeNode objectNode = new DefaultMutableTreeNode(fieldName + " (Object)");parent.add(objectNode);jsonNode.fields().forEachRemaining(entry -> {String key = entry.getKey();JsonNode value = entry.getValue();buildTreeNodes(value, objectNode, key);});} else if (jsonNode.isArray()) {DefaultMutableTreeNode arrayNode = new DefaultMutableTreeNode(fieldName + " (Array[" + jsonNode.size() + "])");parent.add(arrayNode);for (int i = 0; i < jsonNode.size(); i++) {JsonNode element = jsonNode.get(i);buildTreeNodes(element, arrayNode, "[" + i + "]");}} else {String valueStr = jsonNode.asText();if (jsonNode.isNull()) {valueStr = "null";} else if (jsonNode.isNumber()) {valueStr = jsonNode.asText();} else if (jsonNode.isBoolean()) {valueStr = String.valueOf(jsonNode.asBoolean());} else {valueStr = "\"" + valueStr + "\"";}parent.add(new DefaultMutableTreeNode(fieldName + ": " + valueStr));}}private void showStatus(String message, Color color) {statusLabel.setText(message);statusLabel.setForeground(color);}public static void main(String[] args) {try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());} catch (Exception e) {e.printStackTrace();}SwingUtilities.invokeLater(() -> {new AdvancedJsonViewerGUI().setVisible(true);});}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/92921.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/92921.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/92921.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

真實案例 | 如何用iFlyCode開發Webpack插件?

01案例背景在項目中&#xff0c;我們經常需要存檔前端每次打包的版本&#xff0c;方便線上快速切換不同版本使用。經過思考&#xff0c;我們可以在打包時&#xff0c;將本次打包結果另存為zip壓縮包&#xff0c;方便后續使用。于是我準備開發一個Webpack插件實現此功能&#xf…

19day-人工智能-機器學習-分類算法-決策樹

1. 什么是決策樹學過數據結構與算法的小伙伴應該對樹不陌生吧&#xff0c;這里的決策樹也是大同小異的&#xff0c;只是每次反之都有一個條件來決定流向的。1.1 決策節點通過條件判斷而進行分支選擇的節點。如&#xff1a;將某個樣本中的屬性值(特征值)與決策節點上的值進行比較…

地球磁層全球MHD模型中模擬Dst指數的半經驗方法

A semi-empirical approach to simulating the Dst index in global MHD models of Earth’s magnetosphere pdf 1 Introduction Dst指數 (Disturbance storm time index, 地磁暴時擾動指數) 是描述磁暴活動強度應用最廣泛的指數&#xff0c;對于研究地磁擾動和磁暴具有重要意…

什么是臟讀、幻讀、不可重復讀?

臟讀、幻讀和不可重復讀是數據庫事務隔離級別中常見的三種數據一致性問題。它們描述了在并發事務環境下可能出現的異常現象。下面通過對比表格和具體示例進行清晰解析&#xff1a;核心概念對比表問題類型觸發場景本質原因示例臟讀 (Dirty Read)事務A讀取了事務B未提交的修改讀取…

騰訊位置商業授權微信小程序關鍵詞輸入提示

微信小程序JavaScript SDK 開發指南 關鍵詞輸入提示 getSuggestion(options:Object) 用于獲取輸入關鍵字的補完與提示&#xff0c;幫助用戶快速輸入 注&#xff1a;坐標系采用gcj02坐標系 options屬性說明 屬性類型必填說明keywordString是用戶輸入的關鍵詞&#xff08;希望…

LabVIEW菜單操控

該程序圍繞運行時菜單欄操作&#xff0c;實現從初始化構建菜單結構&#xff08;含菜單項、快捷鍵 &#xff09;&#xff0c;到響應交互刪除特定菜單項&#xff0c;再到監控界面事件驅動邏輯&#xff0c;完成自定義菜單交互全流程&#xff0c;適配需靈活菜單控制的程序開發場景。…

Web 服務詳解:HTTP 與 HTTPS 配置

Web 服務詳解&#xff1a;HTTP 與 HTTPS 配置 一、HTTP 服務概述 HTTP&#xff08;Hypertext Transfer Protocol&#xff0c;超文本傳輸協議&#xff09;是用于在網絡上傳輸網頁數據的基礎協議&#xff0c;默認使用80 端口&#xff0c;以明文形式傳輸數據。常見的 HTTP 服務軟…

YOLO-v2-tiny 20種物體檢測模型

一、簡介 YOLO-v2-tiny是基于YOLO(You Only Look Once)實時目標檢測算法的輕量級版本&#xff0c;專門為嵌入式設備和資源受限環境優化。本模型能夠檢測20種常見物體類別&#xff0c;在保持較高檢測精度的同時大幅減少了計算量和模型大小。 20種物體檢測模型&#xff0c; 使用…

heterophilic graph和hetergeneous graph區別(附帶homophilic graph 和homoegeneous graph)

Heterophilic Graph&#xff08;異配圖&#xff09;連接的節點在屬性上不相似,但是所有節點和邊的類別都是同一種類型&#xff0c;數據集如squirrel / chameleon&#xff0c;它們是 heterogeneous graph&#xff08;異質圖&#xff09;而不是Heterophilic Graph&#xff08;異配…

Thinkphp(GUI)漏洞利用工具,支持各版本TP漏洞檢測,命令執行,Getshell

工具介紹 Thinkphp(GUI)漏洞利用工具&#xff0c;支持各版本TP漏洞檢測&#xff0c;命令執行&#xff0c;Getshell。JAVAFX可視化編寫&#xff0c;博主第一次用javafx來寫界面&#xff0c;第一次學習嘗試&#xff0c;僅僅只用于學習嘗試如果缺少什么payload&#xff0c;歡迎提交…

GitHub分支保護介紹(Branch Protection)(git分支保護)(通過設置規則和權限來限制對特定分支的操作的功能)

文章目錄**1. 核心功能****a. 防止誤操作****b. 強制代碼審查****c. 狀態檢查&#xff08;Status Checks&#xff09;****d. 權限控制****2. 如何設置分支保護&#xff1f;**1. **進入倉庫設置**2. **添加分支保護規則**3. **配置保護規則**4. **保存設置****3. 常見應用場景**…

怎么理解On-Premises

On-Premises 指的是—— 軟件、系統、數據中心等部署并運行在企業自己管理的本地硬件或機房里&#xff0c;而不是放在云端或第三方托管環境中。 你可以把它理解成&#xff1a;“服務器在你自己家里&#xff08;公司機房&#xff09;&#xff0c;而不是寄放在別人家&#xff08;…

UserController類講解

用戶管理控制器&#xff0c;實現了用戶CRUD操作的RESTful API&#xff1a; 1. 類結構與核心注解 1.1 控制器聲明 RestController RequestMapping("/api/users") public class UserControllerRestController 深度解析&#xff1a; 組合注解&#xff1a;Controller Re…

【劍指offer】搜索算法

目錄 &#x1f4c1; JZ53 數字在升序數組中出現的次數?編輯 &#x1f4c1; JZ4 二維數組中的查找?編輯 &#x1f4c1; JZ11 旋轉數組的最小數字 &#x1f4c1; JZ38 字符串的排列?編輯 &#x1f4c1; JZ53 數字在升序數組中出現的次數 這就是一道簡單的模板題&#xff0…

ETLCloud批流一體化體現在哪

ETLCloud批流一體化體現在哪 企業對數據處理的實時性、高效性和準確性的要求越來越高。批流一體化作為一種先進的數據處理理念&#xff0c;逐漸被企業所采用。 目前許多國產化ETL工具也裝配了十分強大的批流一體化能力&#xff0c;ETLCoud就是一個很好的代表&#xff0c;它能夠…

Mybatis學習之緩存(九)

這里寫目錄標題一、MyBatis的一級緩存1.1、工作原理1.2、一級緩存失效的四種情況1.3、不同的SqlSession對應不同的一級緩存1.4、同一個SqlSession但是查詢條件不同1.5、同一個SqlSession兩次查詢期間執行了任何一次增刪改操作1.6、同一個SqlSession兩次查詢期間手動清空了&…

windows10裝Ubuntu22.04系統(雙系統)

參考鏈接&#xff1a;Windows和Linux雙系統的保姆級安裝教程&#xff0c;新手小白跟著也能裝_windows安裝linux雙系統-CSDN博客 1 前期準備 1.下載Ubuntu22.04.5 的iso鏡像文件&#xff1a;Download Ubuntu Desktop | Ubuntu 2.準備一個U盤&#xff08;空&#xff0c;已有文…

Pandas數據處理與分析實戰:Pandas數據清洗與處理入門

數據清洗&#xff1a;Pandas數據處理入門 學習目標 本課程將引導學員了解數據清洗的基本概念&#xff0c;掌握使用Pandas庫處理數據集中的缺失值、重復數據和異常值的方法&#xff0c;確保數據的質量&#xff0c;為后續的數據分析和機器學習任務打下堅實的基礎。 相關知識點 Pa…

Python爬蟲實戰:研究ScrapyRT框架,構建圖書商城數據采集系統

1. 引言 1.1 研究背景 在當今數字化時代,互聯網已成為全球最大的信息庫,蘊含著海量的有價值數據,涵蓋商業、教育、科研、醫療等各個領域。根據 IDC(國際數據公司)預測,到 2025 年全球數據圈將增長至 175ZB,其中網絡數據占比超過 60%。這些數據不僅是企業制定商業策略、…

springboot接口請求參數校驗

參數校驗 參數校驗可以防止無效或錯誤的數據進入系統。通過校驗前端輸入的參數&#xff0c;可以確保數據的完整性&#xff0c;避免因為缺少必要的信息而導致程序錯誤或異常。例如&#xff0c;對于密碼字段&#xff0c;可以通過校驗規則要求用戶輸入至少8個字符、包含字母和數字…