zoukankan      html  css  js  c++  java
  • 寻找对应括号

    package com.mingrisoft.jtextpane;
    
    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.border.EmptyBorder;
    import javax.swing.UIManager;
    
    public class MatcherTest extends JFrame {
        
        /**
         * 
         */
        private static final long serialVersionUID = 2190653167733357032L;
        private JPanel contentPane;
        private ParenthesisMatcher textPane;
        
        /**
         * Launch the application.
         */
        public static void main(String[] args) {
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
            } catch (Throwable e) {
                e.printStackTrace();
            }
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        MatcherTest frame = new MatcherTest();
                        frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        
        /**
         * Create the frame.
         */
        public MatcherTest() {
            setTitle("u6D4Bu8BD5u62ECu53F7u7684u5339u914Du72B6u6001");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setBounds(200, 200, 900, 500);
            contentPane = new JPanel();
            contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
            contentPane.setLayout(new BorderLayout(0, 0));
            setContentPane(contentPane);
            
            JPanel panel = new JPanel();
            contentPane.add(panel, BorderLayout.SOUTH);
            
            JButton button = new JButton("Check");
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    do_button_actionPerformed(e);
                }
            });
            button.setFont(new Font("微软雅黑", Font.PLAIN, 16));
            panel.add(button);
            
            JScrollPane scrollPane = new JScrollPane();
            contentPane.add(scrollPane, BorderLayout.CENTER);
            
            textPane = new ParenthesisMatcher();
            textPane.setFont(new Font("微软雅黑", Font.PLAIN, 16));
            scrollPane.setViewportView(textPane);
        }
        
        protected void do_button_actionPerformed(ActionEvent e) {
            textPane.validate();
        }
    }

    file2

    package com.mingrisoft.jtextpane;
    
    import java.awt.Color;
    import java.awt.Font;
    import java.util.ArrayList;
    import java.util.Stack;
    
    import javax.swing.JTextPane;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.MutableAttributeSet;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyleContext;
    import javax.swing.text.StyledDocument;
    import javax.swing.text.StyledEditorKit;
    
    public class ParenthesisMatcher extends JTextPane {
    
        private static Color getColor(int i) {
            Color[] a = { Color.PINK, Color.BLUE, Color.YELLOW, Color.GRAY,
                    Color.GREEN, Color.MAGENTA, Color.ORANGE };
    
            return a[i];
        }
    
        private static final long serialVersionUID = -5040590165582343011L;
        private AttributeSet mismatch;
        private AttributeSet match;
        private int j = 0;
        private StyleContext context = StyleContext.getDefaultStyleContext();
        Stack<Integer> stackInt = new Stack<Integer>();
    
        public ParenthesisMatcher() {
    
            mismatch = context.addAttribute(SimpleAttributeSet.EMPTY,
                    StyleConstants.Foreground, Color.RED);
            Font font = new Font("隶书",Font.BOLD,40);
            mismatch = context.addAttribute(mismatch, StyleConstants.Family, font.getFamily());
            mismatch=context.addAttribute(mismatch, StyleConstants.FontSize, 40);
            // match = context.addAttribute(SimpleAttributeSet.EMPTY,
            // StyleConstants.Foreground, getColor(j));
         
        }
    
        public void validate() {
            StyledDocument document = getStyledDocument();
        
            String text = null;
            try {
                text = document.getText(0, document.getLength());
            } catch (BadLocationException e) {
                e.printStackTrace();
            }
            Stack<String> stack = new Stack<String>();
            for (int i = 0; i < text.length(); i++) {
                char c = text.charAt(i);
                if (c == '(' || c == '[' || c == '{') {
                    
                    stack.push("" + c + i);
                    match = context.addAttribute(SimpleAttributeSet.EMPTY,
                            StyleConstants.Foreground, getColor(j));
                    Font font = new Font("隶书",Font.BOLD,25);
                    match = context.addAttribute(match, StyleConstants.Family, font.getFamily());
                    match=context.addAttribute(match, StyleConstants.FontSize, 25);
                    document.setCharacterAttributes(i, 1, match, false);
                    
                    
                    stackInt.push(j);
                    j++;
                    if (j == 6) {
                        j = 0;
                    }
    
                }
                if (c == ')' || c == ']' || c == '}') {
                    String peek = stack.empty() ? "." : (String) stack.peek();
                    if (match(peek.charAt(0), c)) {
                        stack.pop();
                        j = ((Integer) stackInt.pop()).intValue();
                        match = context.addAttribute(SimpleAttributeSet.EMPTY,
                                StyleConstants.Foreground, getColor(j));
                        Font font = new Font("隶书",Font.BOLD,25);
                        match = context.addAttribute(match, StyleConstants.Family, font.getFamily());
                        match=context.addAttribute(match, StyleConstants.FontSize, 25);
                        document.setCharacterAttributes(i, 1, match, false);
    
                    } else {
                        document.setCharacterAttributes(i, 1, mismatch, false);
                        
                    }
                }
            }
    
            while (!stack.empty()) {
                String pop = (String) stack.pop();
                int offset = Integer.parseInt(pop.substring(1));
                document.setCharacterAttributes(offset, 1, mismatch, false);
            }
        }
    
        @Override
        public void replaceSelection(String content) {
            getInputAttributes().removeAttribute(StyleConstants.Foreground);
            super.replaceSelection(content);
        }
    
        private boolean match(char left, char right) {
            if ((left == '(') && (right == ')')) {
                return true;
            }
            if ((left == '[') && (right == ']')) {
                return true;
            }
            if ((left == '{') && (right == '}')) {
                return true;
            }
            return false;
        }
    }
  • 相关阅读:
    双11实时物流订单最佳实践
    一文理解 K8s 容器网络虚拟化
    新能源汽车太猛了,这些卡脖子技术你了解吗?
    龙蜥社区成立系统运维SIG,重磅开源sysAK系统运维工具集
    sysAK(青囊)系统运维工具集:如何实现高效自动化运维?| 龙蜥技术
    零信任策略下云上安全信息与事件管理最佳实践
    MySQL 处理重复数据
    JavaScript toFixed()、toExponential、toPrecision方法
    Nginx 安装
    spring定时任务执行两次的原因与解决方法
  • 原文地址:https://www.cnblogs.com/MaxNumber/p/3226909.html
Copyright © 2011-2022 走看看