多个颜色和多个字体样式只在一个DefaultMutableTreeNode,JTextPane,JTree上

时间:2018-03-17 05:06:35

标签: colors jtree jtextpane defaultmutabletreenode

我正在审核这个问题: How to change style (color, font) of a single JTree node

但我的问题不同。

我有这个:

String grayPlain = "Snippet Gray Color and Plain Font Style";
String blackPlain = "Black Color and Plain Font Style";
String blackBold = "Snippet Black Color and Bold Font Style";
String SomeString = grayPlain + blackPlain + blackBold;

new DefaultMutableTreeNode(SomeString, false);

如何根据之前的描述更改字符串的字体样式和颜色只有一个DefaultMutableTreeNode

这方面的一个例子是搜索 notepad ++ 的结果。  同一行在同一结果中有两种颜色。

enter image description here

现在,我不仅要使用两种颜色,还要使用三种颜色,并将文本的某些部分更改为粗体。

也许像JTextPane这样的东西会使用多种风格......

但我不知道从哪里开始。

enter image description here

1 个答案:

答案 0 :(得分:0)

以此帖为基础:http://esus.com/jtextarea-node-jtree/

enter image description here

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;

import javax.swing.*;
import javax.swing.tree.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;

public class JTreeUsingJTextPane extends JFrame {

  public JTreeUsingJTextPane() {

    Font plain = new Font("Monospaced", Font.PLAIN, 10);
    Font bold = new Font("Monospaced", Font.BOLD, 10);
    Font italic = new Font("Monospaced", Font.ITALIC, 10);
    Font bold_italic = new Font("Lucida Sans Typewriter", Font.BOLD + Font.ITALIC, 14);

    DefaultMutableTreeNode defaultMutableTreeNode = 
        new DefaultMutableTreeNode("JTextPane on JTree");

    DecoratedText nonDecoratedText = new DecoratedText(
        " Single text without Decoration ");
    DecoratedText singleDecoratedText = new DecoratedText(
        " Lucida Sans Typewriter, Font.BOLD + Font.ITALIC, Size:14 ",
        bold_italic
    );
    DecoratedText[] arrayDecoratedText = new DecoratedText[] {
      new DecoratedText(Color.WHITE, " WHITE Background & Font.BOLD ", bold),
      new DecoratedText(" WHITE Foreground ", Color.WHITE),
      new DecoratedText(Color.LIGHT_GRAY, " LIGHT_GRAY Background & Font.PLAIN ", plain),
      new DecoratedText(" Font.ITALIC ", italic),
      new DecoratedText(Color.DARK_GRAY, " DARK_GRAY Background.")
    };
    DecoratedText[] arrayColoreText = new DecoratedText[] {
      new DecoratedText(Color.GRAY, " GRAY Background, RED Foreground ", Color.RED),
      new DecoratedText(Color.WHITE, " WHITE Background, BLUE Foreground ", Color.BLUE),
      new DecoratedText(Color.BLACK, " BLACK Background, GREEN Foreground ", Color.GREEN)
    };

    DefaultMutableTreeNode singleDecorated = new DefaultMutableTreeNode("Singles DecoratedText");
    singleDecorated.add(new DefaultMutableTreeNode(nonDecoratedText));
    singleDecorated.add(new DefaultMutableTreeNode(singleDecoratedText));

    DefaultMutableTreeNode arrayDecorated = new DefaultMutableTreeNode("DecoratedText's Arrays");
    arrayDecorated.add(new DefaultMutableTreeNode(arrayDecoratedText));
    arrayDecorated.add(new DefaultMutableTreeNode(arrayColoreText));

    defaultMutableTreeNode.add(new DefaultMutableTreeNode("opening String"));
    defaultMutableTreeNode.add(singleDecorated);
    defaultMutableTreeNode.add(arrayDecorated);
    defaultMutableTreeNode.add(new DefaultMutableTreeNode("closing String"));

    JTree tree = new JTree(defaultMutableTreeNode);
    tree.setCellRenderer(new TextPaneDefaultTreeCellRenderer());
    getContentPane().add(new JScrollPane(tree));
    addWindowListener(new WindowAdapter() {
       public void windowClosing(WindowEvent we) {
          System.exit(0);
       }
    });
  }

  public static void main(String []args) {
    JTreeUsingJTextPane app = new JTreeUsingJTextPane();
    app.setSize(840, 240);
    app.setVisible(true);
  }
}

class TextPaneDefaultTreeCellRenderer extends DefaultTreeCellRenderer {
  TextPaneScrollPane textPaneScrollPane = new TextPaneScrollPane();

  public TextPaneDefaultTreeCellRenderer() {
    textPaneScrollPane.setBackgroundNonSelectionColor(getBackgroundNonSelectionColor());
    textPaneScrollPane.setBackgroundSelectionColor(getBackgroundSelectionColor());
    textPaneScrollPane.setTextNonSelectionColor(getTextNonSelectionColor()); 
    textPaneScrollPane.setTextSelectionColor(getTextSelectionColor());
  }

  @Override public Component getTreeCellRendererComponent(JTree tree, Object value,
      boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
    if (leaf) {
      return textPaneScrollPane.getTreeCellRendererComponent(tree, value, 
          selected, expanded, leaf, row, hasFocus);
    } else {
      return super.getTreeCellRendererComponent(tree, value, selected, 
          expanded, leaf, row, hasFocus);
    }
  }
}

class TextPaneScrollPane extends JScrollPane implements TreeCellRenderer {
  JTextPane textPane;
  Color backgroundNonSelectionColor;
  Color backgroundSelectionColor;
  Color textNonSelectionColor;
  Color textSelectionColor;

  public TextPaneScrollPane() {
    textPane = new JTextPane();
    getViewport().add(textPane);
  }

  public void setBackgroundNonSelectionColor(Color color) {
    this.backgroundNonSelectionColor = color;
  }

  public void setBackgroundSelectionColor(Color color) {
    this.backgroundSelectionColor = color;
  }

  public void setTextNonSelectionColor(Color color) {
    this.textNonSelectionColor = color;
  }

  public void setTextSelectionColor(Color color) {
    this.textSelectionColor = color;
  }

  @Override public Component getTreeCellRendererComponent(JTree tree, Object value,
      boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
    if (selected) {
      setForeground(textSelectionColor);
      setBackground(backgroundSelectionColor);
      textPane.setForeground(textSelectionColor);
      textPane.setBackground(backgroundSelectionColor);
    } else {
      setForeground(textNonSelectionColor);
      setBackground(backgroundNonSelectionColor);
      textPane.setForeground(textNonSelectionColor);
      textPane.setBackground(backgroundNonSelectionColor);
    }

    DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
    Object object = node.getUserObject();
    if (object != null && object instanceof DecoratedText) {
      textPane.setText("");
      Document doc = textPane.getStyledDocument();
      DecoratedText decText = (DecoratedText)object;
      try {
        doc.insertString(doc.getLength(), decText.getText(), getAttributeSet(decText));
      } catch (BadLocationException ex) {
        Logger.getLogger(TextPaneScrollPane.class.getName()).log(Level.SEVERE, null, ex);
      }
    } else if (object != null && object instanceof DecoratedText[]) {
      textPane.setText("");
      Document doc = textPane.getStyledDocument();
      DecoratedText[] arrayDecText = (DecoratedText[])object;
      for (DecoratedText decText:arrayDecText) {
        try {
          doc.insertString(doc.getLength(), decText.getText(), getAttributeSet(decText));
        } catch (BadLocationException ex) {
          Logger.getLogger(TextPaneScrollPane.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    } else {
      //textPane = new JTextPane(); // Needed because take the last StyleConstants used!
      //textPane.setText(""+object);
      //return new JLabel(object.toString());
      return new DefaultTreeCellRenderer().getTreeCellRendererComponent(tree, 
          value, leaf, expanded, leaf, row, hasFocus);
    }
    return textPane;
  }

  private SimpleAttributeSet getAttributeSet(DecoratedText decoratedText) {
    SimpleAttributeSet attributeSet = new SimpleAttributeSet();
    if (decoratedText != null) {
      if (decoratedText.getText() != null) {
      }
      if (decoratedText.getBackground() != null) {
        StyleConstants.setBackground(attributeSet, decoratedText.getBackground());
      }
      if (decoratedText.getForeground() != null) {
        StyleConstants.setForeground(attributeSet, decoratedText.getForeground());
      }
      if (decoratedText.getFont() != null) {
        StyleConstants.setFontFamily(attributeSet, decoratedText.getFont().getFamily());
        StyleConstants.setItalic(attributeSet, decoratedText.getFont().isItalic());
        StyleConstants.setBold(attributeSet, decoratedText.getFont().isBold());
        StyleConstants.setFontSize(attributeSet, decoratedText.getFont().getSize());
      }
    }
    return attributeSet;
  }
}

class DecoratedText {
  private String text;
  private Color background = new JLabel().getBackground();
  private Color foreground = new JLabel().getForeground();
  private Font font = new JLabel().getFont();

  public DecoratedText(String text) {
    this.text = text;
  }

  public DecoratedText(String text, Font font) {
    this.text = text;
    this.font = font;
  }

  public DecoratedText(String text, Color foreground) {
    this.text = text;
    this.foreground = foreground;
  }

  public DecoratedText(String text, Color foreground, Font font) {
    this.text = text;
    this.foreground = foreground;
    this.font = font;
  }

  public DecoratedText(Color background, String text) {
    this.background = background;
    this.text = text;
  }

  public DecoratedText(Color background, String text, Font font) {
    this.background = background;
    this.text = text;
    this.font = font;
  }

  public DecoratedText(Color background, String text, Color foreground) {
    this.background = background;
    this.text = text;
    this.foreground = foreground;
  }

  public DecoratedText(Color background, String text, Color foreground, Font font) {
    this.background = background;
    this.text = text;
    this.foreground = foreground;
    this.font = font;
  }

  public String getText() {
    return text;
  }

  public void setText(String text) {
    this.text = text;
  }

  public Color getBackground() {
    return background;
  }

  public void setBackground(Color background) {
    this.background = background;
  }

  public Color getForeground() {
    return foreground;
  }

  public void setForeground(Color foreground) {
    this.foreground = foreground;
  }

  public Font getFont() {
    return font;
  }

  public void setFont(Font font) {
    this.font = font;
  }

  @Override
  public String toString() {
    return "DecoratedText{" + "text=" + text + ", background=" + background 
        + ", foreground=" + foreground + ", font=" + font + '}';
  }

}