我们这一家

check brackets-2

file1

package com.mingrisoft.jtextpane;

import java.awt.Color;
import java.awt.Font;
import java.util.ArrayList;
import java.util.Stack;

import javax.swing.JOptionPane;
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.ORANGE, Color.BLUE, Color.GREEN, Color.GRAY,
                Color.cyan, Color.MAGENTA, Color.PINK };

        return a[i];
    }

    private static final long serialVersionUID = -5040590165582343011L;
    private AttributeSet mismatch;
    private AttributeSet match;
    private int j;
    private StyledDocument document;
    private StyleContext context = StyleContext.getDefaultStyleContext();
    Stack<Integer> stackInt = new Stack<Integer>();

    public ParenthesisMatcher() {

        document = getStyledDocument();
        mismatch = context.addAttribute(SimpleAttributeSet.EMPTY,
                StyleConstants.Foreground, Color.RED);
        Font fontM = new Font("隶书", Font.BOLD, 25);
        mismatch = context.addAttribute(mismatch, StyleConstants.Family,
                fontM.getFamily());
        mismatch = context.addAttribute(mismatch, StyleConstants.FontSize, 25);

    }

    public void validate(boolean flag,int k) {
        if (flag) {
            j = 0;
            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 == '[' && k==1) {
                    stack.push("" + c + i);
                    match = context.addAttribute(SimpleAttributeSet.EMPTY,
                            StyleConstants.Foreground, getColor(j));
                    Font font = new Font("隶书", Font.BOLD, 18);
                    match = context.addAttribute(match, StyleConstants.Family,
                            font.getFamily());
                    match = context.addAttribute(match,
                            StyleConstants.FontSize, 18);
                    document.setCharacterAttributes(i, 1, match, false);
                    
                    stackInt.push(j);
                    // System.out.println("push j: "+j);
                    j++;
                    if (j == 6) {
                        j = 0;
                    }

                }
                if (c == '(' && k==2) {
                    stack.push("" + c + i);
                    match = context.addAttribute(SimpleAttributeSet.EMPTY,
                            StyleConstants.Foreground, getColor(j));
                    Font font = new Font("隶书", Font.BOLD, 18);
                    match = context.addAttribute(match, StyleConstants.Family,
                            font.getFamily());
                    match = context.addAttribute(match,
                            StyleConstants.FontSize,18);
                    document.setCharacterAttributes(i, 1, match, false);
                    
                    stackInt.push(j);
                    // System.out.println("push j: "+j);
                    j++;
                    if (j == 6) {
                        j = 0;
                    }

                }
                if (c == ']'&&k==1) {
                    String peek = stack.empty() ? "." : (String) stack.peek();
                    if (match(peek.charAt(0), c,k)) {
                        stack.pop();

                        j = ((Integer) stackInt.pop()).intValue();
                        // System.out.println("pop j: "+j);
                        match = context.addAttribute(SimpleAttributeSet.EMPTY,
                                StyleConstants.Foreground, getColor(j));
                        Font font = new Font("隶书", Font.BOLD, 18);
                        match = context.addAttribute(match,
                                StyleConstants.Family, font.getFamily());
                        match = context.addAttribute(match,
                                StyleConstants.FontSize, 18);
                        document.setCharacterAttributes(i, 1, match, false);

                    } else {
                        document.setCharacterAttributes(i, 1, mismatch, false);

                    }
                }
                if (c == ')'&&k==2) {
                    String peek = stack.empty() ? "." : (String) stack.peek();
                    if (match(peek.charAt(0), c,k)) {
                        stack.pop();

                        j = ((Integer) stackInt.pop()).intValue();
                        // System.out.println("pop j: "+j);
                        match = context.addAttribute(SimpleAttributeSet.EMPTY,
                                StyleConstants.Foreground, getColor(j));
                        Font font = new Font("隶书", Font.BOLD, 18);
                        match = context.addAttribute(match,
                                StyleConstants.Family, font.getFamily());
                        match = context.addAttribute(match,
                                StyleConstants.FontSize, 18);
                        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,int k) {
        
         if ((left == '(') && (right == ')')&&k==2) { return true; }
         
        if ((left == '[') && (right == ']')&&k==1) {
            return true;
        }
        /*
         if ((left == '{') && (right == '}')) { return true; }
        */
        return false;
    }
}

file2

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.JOptionPane;
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("\u6D4B\u8BD5\u62EC\u53F7\u7684\u5339\u914D\u72B6\u6001");
        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");
        JButton btnCheck = new JButton("Check (");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //JOptionPane.showMessageDialog( null , "要显示的信息内容" ,"标题" , JOptionPane.ERROR_MESSAGE) ;
                do_button_actionPerformed(e);
            }
        });
        
        btnCheck.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //JOptionPane.showMessageDialog( null , "要显示的信息内容" ,"标题" , JOptionPane.ERROR_MESSAGE) ;
                do_btnCheck_actionPerformed(e);
            }
        });
        button.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        btnCheck.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        panel.add(button);
        panel.add(btnCheck);
        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(true,1);
    }
    protected void do_btnCheck_actionPerformed(ActionEvent e) {
        textPane.validate(true,2);
     }
    
}

 

posted on 2013-08-01 01:39  MaxNumber  阅读(183)  评论(0编辑  收藏  举报

导航

Loading...........