Blacklands

JTextPane Problem

Sep 8th, 2015
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.77 KB | None | 0 0
  1. import java.awt.EventQueue;
  2. import java.awt.Graphics2D;
  3. import javax.imageio.ImageIO;
  4. import javax.swing.ImageIcon;
  5. import javax.swing.JFrame;
  6. import javax.swing.JLabel;
  7. import javax.swing.JPanel;
  8. import javax.swing.border.EmptyBorder;
  9. import javax.swing.text.BadLocationException;
  10. import javax.swing.text.SimpleAttributeSet;
  11. import javax.swing.text.Style;
  12. import javax.swing.text.StyleConstants;
  13. import javax.swing.text.StyleContext;
  14. import javax.swing.text.StyledDocument;
  15. import javax.swing.text.html.HTMLEditorKit;
  16. import java.awt.GridLayout;
  17. import java.awt.image.BufferedImage;
  18. import java.io.File;
  19. import java.io.IOException;
  20. import java.util.HashMap;
  21. import java.util.regex.Matcher;
  22. import java.util.regex.Pattern;
  23. import javax.swing.JScrollPane;
  24. import javax.swing.ScrollPaneConstants;
  25. import javax.swing.JTextPane;
  26.  
  27. public class MinimalExample extends JFrame {
  28.  
  29.     private JPanel contentPane;
  30.     private JScrollPane scrollPane;
  31.     private JTextPane textPane;
  32.  
  33.     // Setup some data for an example card:
  34.     String name = "Absorb Vis";
  35.     String set = "CON";
  36.     String manaCost = "{6}{B}";
  37.     String printedType = "Sorcery";
  38.     String artist = "Brandon Kitkouski";
  39.    
  40.     String rulesText = "Target player loses 4 life and you gain 4 life.\n" +
  41.                    "Basic landcycling {1}{B} ({1}{B}, Discard this card: " +
  42.                    "Search your library for a basic land card, reveal it, and put " +
  43.                    "it into your hand. Then shuffle your library.)";
  44.    
  45.     HashMap<String, BufferedImage> manaSymbolImages;    
  46.    
  47.     public static void main(String[] args) {
  48.  
  49.     EventQueue.invokeLater(new Runnable() {
  50.         public void run() {
  51.  
  52.         try {
  53.             MinimalExample frame = new MinimalExample();
  54.             frame.setVisible(true);
  55.         }
  56.         catch (Exception e) {
  57.             e.printStackTrace();
  58.         }
  59.         }
  60.     });
  61.     }
  62.  
  63.     public MinimalExample() {
  64.    
  65.     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  66.     setBounds(100, 100, 230, 400);
  67.     contentPane = new JPanel();
  68.     contentPane.setBorder(null);
  69.     setContentPane(contentPane);
  70.     contentPane.setLayout(new GridLayout(1, 0, 0, 0));
  71.    
  72.     scrollPane = new JScrollPane();
  73.     scrollPane.setViewportBorder(new EmptyBorder(0, 3, 0, 3));
  74.     scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
  75.     contentPane.add(scrollPane);
  76.    
  77.     textPane = new JTextPane();
  78.     textPane.setEditable(false);
  79.    
  80.     scrollPane.setViewportView(textPane);
  81.    
  82.     // You can comment this out to see how it looks in non-html mode:
  83.     textPane.setEditorKit(new HTMLEditorKit());
  84.    
  85.     loadManaCostIcons();
  86.     setPaneText();
  87.     }
  88.    
  89.     /* This part inserts the text into the document of the text pane. Read below for details.  */
  90.     public void setPaneText() {
  91.    
  92.     String[] contents = new String[] { name,           // name
  93.                        "ignored" + "\n",       // manaCost
  94.                        printedType,        // printedType
  95.                        set + "\n\n",       // set
  96.                        rulesText + "\n",       // rulesText
  97.                        "Illus. " + artist };   // artist
  98.    
  99.     StyledDocument textPaneDoc = textPane.getStyledDocument();
  100.    
  101.     // I tried it this was first, but that didn't work at all. Maybe you'll have more luck.
  102.     /*
  103.     String[] styles = new String[] { "nameStyle", "manaCostStyle","printedTypeStyle",
  104.                      "setStyle", "rulesTextStyle", "artistStyle" };
  105.    
  106.     addStylesToDocument(textPaneDoc);
  107.      */
  108.    
  109.     SimpleAttributeSet[] styleAttributes = new SimpleAttributeSet[contents.length];
  110.     getStyleAttributes(styleAttributes);
  111.    
  112.     for (int i = 0; i < contents.length; i++) {
  113.        
  114.         try {
  115.        
  116.         if (i == 4) {          
  117.             addTextWithSymbols(contents[i], styleAttributes[i]);
  118.             continue;
  119.         }  
  120.         textPaneDoc.insertString(textPaneDoc.getLength(),
  121.                              contents[i],
  122.                              //textPaneDoc.getStyle(styles[i])); // see above.
  123.                              styleAttributes[i]);
  124.         }
  125.         catch (BadLocationException e) {
  126.  
  127.         e.printStackTrace();
  128.         }
  129.     }
  130.    
  131.     textPane.revalidate();
  132.     textPane.repaint();
  133.     }
  134.    
  135.     /* This adds the rest of the text to the pane. The codes for the symbols get replaced by the
  136.      * actual symbols and the text gets inserted piece by piece. */
  137.     public void addTextWithSymbols(String text, SimpleAttributeSet style) {
  138.    
  139.     StyledDocument textPaneDoc = textPane.getStyledDocument();
  140.    
  141.     Pattern symbolPattern = Pattern.compile("\\{(.*?)\\}");
  142.    
  143.     try {
  144.        
  145.         Matcher symbolMatcher = symbolPattern.matcher(text);       
  146.         int previousMatch = 0;
  147.        
  148.         while (symbolMatcher.find()) {
  149.        
  150.         int start = symbolMatcher.start();
  151.         int end = symbolMatcher.end();     
  152.         String subStringText = text.substring(previousMatch, start);
  153.         String currentMatch = text.substring(start, end);
  154.        
  155.         if (subStringText.isEmpty() == false) {
  156.            
  157.             textPaneDoc.insertString(textPaneDoc.getLength(), subStringText, style);
  158.            
  159.             /* I tried with adding to the text pane's styled document and to the text
  160.              * pane directly, but the second way doesn't seem to work at all. */
  161.             //textPane.replaceSelection(subStringText);
  162.         }
  163.        
  164.         ImageIcon currentIcon = new ImageIcon(manaSymbolImages.get(currentMatch));
  165.        
  166.         SimpleAttributeSet iconAtts = new SimpleAttributeSet();
  167.         JLabel iconLabel = new JLabel();
  168.         // None of those seem to change anything visible:
  169.         //iconLabel.setVerticalAlignment(JLabel.CENTER);
  170.         //iconLabel.setHorizontalAlignment(JLabel.RIGHT);
  171.         iconLabel.setIcon(currentIcon);
  172.         StyleConstants.setComponent(iconAtts, iconLabel);
  173.         //StyleConstants.setAlignment(iconAtts, StyleConstants.ALIGN_LEFT);
  174.  
  175.         textPaneDoc.insertString(textPaneDoc.getLength(), "ignored", iconAtts);
  176.         //textPane.insertIcon(currentIcon);
  177.        
  178.         previousMatch = end;
  179.         }
  180.        
  181.         String subStringText = text.substring(previousMatch);
  182.        
  183.         if (subStringText.isEmpty() == false) {    
  184.             textPaneDoc.insertString(textPaneDoc.getLength(), subStringText, style);
  185.         //textPane.replaceSelection(subStringText);
  186.         }
  187.        
  188.     }
  189.     catch (Exception e) {
  190.  
  191.         e.printStackTrace();
  192.     }
  193.     }
  194.    
  195.     public void getStyleAttributes(SimpleAttributeSet[] styleAttributes) {
  196.    
  197.     SimpleAttributeSet defaultAtts = new SimpleAttributeSet();
  198.     StyleConstants.setFontFamily(defaultAtts, "SansSerif");
  199.    
  200.     SimpleAttributeSet nameAtts = new SimpleAttributeSet(defaultAtts);
  201.     StyleConstants.setBold(nameAtts, true);
  202.     StyleConstants.setAlignment(nameAtts, StyleConstants.ALIGN_LEFT);
  203.    
  204.     SimpleAttributeSet manaCostAtts = new SimpleAttributeSet(defaultAtts);
  205.     ImageIcon manaCostIcon = combineSymbols(manaCost);
  206.     JLabel manaCostLabel = new JLabel(manaCostIcon);
  207.     manaCostLabel.setVerticalAlignment(JLabel.CENTER);
  208.     manaCostLabel.setHorizontalAlignment(JLabel.RIGHT);
  209.     StyleConstants.setComponent(manaCostAtts, manaCostLabel);
  210.     StyleConstants.setAlignment(manaCostAtts, StyleConstants.ALIGN_RIGHT);
  211.    
  212.     SimpleAttributeSet printedTypeAtts = new SimpleAttributeSet(defaultAtts);
  213.     StyleConstants.setAlignment(printedTypeAtts, StyleConstants.ALIGN_LEFT);
  214.    
  215.     SimpleAttributeSet setAtts = new SimpleAttributeSet(nameAtts);
  216.     StyleConstants.setAlignment(setAtts, StyleConstants.ALIGN_RIGHT);
  217.    
  218.     SimpleAttributeSet rulesAtts = new SimpleAttributeSet(defaultAtts);
  219.     StyleConstants.setAlignment(rulesAtts, StyleConstants.ALIGN_LEFT);
  220.    
  221.     SimpleAttributeSet artistAtts = new SimpleAttributeSet(defaultAtts);
  222.     StyleConstants.setFontSize(artistAtts, 10);
  223.    
  224.     styleAttributes[0] = nameAtts;
  225.     styleAttributes[1] = manaCostAtts;
  226.     styleAttributes[2] = printedTypeAtts;
  227.     styleAttributes[3] = setAtts;
  228.     styleAttributes[4] = rulesAtts;
  229.     styleAttributes[5] = artistAtts;
  230.     }
  231.    
  232.     /* This was my first way to try it, see my post. With this, I can't even get the right-
  233.      * alignment to work. */
  234.    
  235.     public void addStylesToDocument(StyledDocument document) {
  236.    
  237.     Style defaultStyle = StyleContext.getDefaultStyleContext().
  238.                       getStyle(StyleContext.DEFAULT_STYLE);
  239.    
  240.     Style normalStyle = document.addStyle("normalStyle", defaultStyle);
  241.     StyleConstants.setFontFamily(normalStyle, "SansSerif");
  242.    
  243.     Style nameStyle = document.addStyle("nameStyle", normalStyle);
  244.     StyleConstants.setBold(nameStyle, true);
  245.     StyleConstants.setAlignment(nameStyle, StyleConstants.ALIGN_LEFT);
  246.    
  247.     Style manaCostStyle = document.addStyle("manaCostStyle", normalStyle); 
  248.     ImageIcon manaCostIcon = combineSymbols(manaCost);
  249.     JLabel manaCostLabel = new JLabel(manaCostIcon);
  250.     manaCostLabel.setVerticalAlignment(JLabel.CENTER);
  251.     manaCostLabel.setHorizontalAlignment(JLabel.RIGHT);
  252.     StyleConstants.setComponent(manaCostStyle, manaCostLabel);
  253.     StyleConstants.setAlignment(manaCostStyle, StyleConstants.ALIGN_RIGHT);
  254.    
  255.     Style printedTypeStyle = document.addStyle("printedTypeStyle", normalStyle);
  256.     StyleConstants.setAlignment(printedTypeStyle, StyleConstants.ALIGN_LEFT);
  257.    
  258.     Style setStyle = document.addStyle("setStyle", nameStyle);
  259.     StyleConstants.setAlignment(setStyle, StyleConstants.ALIGN_RIGHT);
  260.    
  261.     Style rulesTextStyle = document.addStyle("rulesTextStyle", normalStyle);
  262.    
  263.     Style artistStyle = document.addStyle("artistStyle", normalStyle);
  264.     StyleConstants.setFontSize(artistStyle, 10);
  265.     }
  266.    
  267.     /* Everything below is more or less irrelevant. However, you might need to adjust the image
  268.      * image file paths. */
  269.    
  270.     public void loadManaCostIcons() {
  271.    
  272.     manaSymbolImages = new HashMap<String, BufferedImage>();   
  273.     try {
  274.        
  275.         // Most likely, those paths won't work for you!
  276.         File bFile = new File("resource/B.png");
  277.         File c1File = new File("resource/1.png");
  278.         File c6File = new File("resource/6.png");
  279.        
  280.         manaSymbolImages.put("{B}", ImageIO.read(bFile));
  281.         manaSymbolImages.put("{1}", ImageIO.read(c1File));
  282.         manaSymbolImages.put("{6}", ImageIO.read(c6File));
  283.     }
  284.     catch (IOException e) {
  285.        
  286.         e.printStackTrace();
  287.     }
  288.     }
  289.    
  290.     public ImageIcon combineSymbols(String symbols) {
  291.    
  292.     String[] manaSymbols = symbols.split("(?<=})");
  293.     int combinedWidth = 0;
  294.     int maxHeight = 0;
  295.    
  296.     for (int i = 0; i < manaSymbols.length; i++) {
  297.        
  298.         BufferedImage currentSymbolImage = manaSymbolImages.get(manaSymbols[i]);       
  299.         combinedWidth += currentSymbolImage.getWidth();
  300.        
  301.         if (maxHeight < currentSymbolImage.getWidth()) {       
  302.         maxHeight = currentSymbolImage.getWidth();
  303.         }
  304.     }
  305.    
  306.         BufferedImage combinedManaCostImage = new BufferedImage(combinedWidth,
  307.                                         maxHeight,
  308.                                         BufferedImage.TYPE_INT_ARGB);      
  309.     Graphics2D graphics = combinedManaCostImage.createGraphics();
  310.  
  311.     int currentPosition = 0;
  312.    
  313.     for (int i = 0; i < manaSymbols.length; i++) {
  314.        
  315.         BufferedImage tempCurrentImage = manaSymbolImages.get(manaSymbols[i].trim());      
  316.         graphics.drawImage(tempCurrentImage, null, currentPosition, 0);    
  317.         currentPosition += tempCurrentImage.getWidth();
  318.     }
  319.    
  320.     graphics.dispose();
  321.     return (new ImageIcon(combinedManaCostImage));
  322.     }
  323. }
Add Comment
Please, Sign In to add comment