JTextPane中如何设置标文本?

问题描述 投票:0回答:2

我在JTextPane中键入文本(它会在MS / Word文档后转换),但我不知道如何设置标几句话。

到目前为止,我的测试代码工作得很好。我可以在粗体,斜体specfified也就是说,即使改变字型或大小。换做我首先选择的话,然后我点击一个JButton执行动作类,如:

动作的动作=新StyledEditorKit.ItalicAction(); action.actionPerformed(NULL);

但是我不知道如何为上标做。

package test;

import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;
import java.awt.Color;
import javax.swing.JComboBox;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import javax.swing.JLabel;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.JScrollPane;
import java.awt.Font;

public class Test_HTMLKit extends JFrame 
{
    private static final long serialVersionUID = 1L;
    protected JTextPane  MyText; 
    protected JComboBox Fonts, Sizes;
    protected  JButton  See,
                Bold,
                Finish,
                SuperScript,
                Italic;

    public HTMLEditorKit    htmlKit             = new HTMLEditorKit();
    public HTMLDocument     htmlDoc             = null;
    public static Style mainStyle           =   null;
    protected String    fontList[];
    protected String    fontSizes[]         =   {"8","10","12","14","18","24","48"};

    public Test_HTMLKit() 
    {
        getContentPane().setLayout(null);
        this.setSize(753,490);

        Fonts = new JComboBox();
        Fonts.setBounds(25, 27, 187, 20);
        getContentPane().add(Fonts);

        See = new JButton("See HTML code ");
            See.setBounds(43, 253, 130, 23);


        Finish = new JButton("Exit");
            Finish.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) 
            {
                System.exit(0); 
            }
            });
            Finish.setBounds(43, 287, 130, 23);


        Sizes = new JComboBox();
        Sizes.setBounds(299, 27, 62, 20);

        JLabel lblFontFamlies = new JLabel("Font Families");
        lblFontFamlies.setBounds(74, 11, 99, 14);

        JLabel lblFontSizes = new JLabel("Font sizes");
        lblFontSizes.setBounds(299, 11, 99, 14);


        Bold = new JButton("Bold");
        Bold.setBounds(25, 58, 67, 23);

        Italic = new JButton("Italic");
        Italic.setBounds(25, 106, 67, 23);

        SuperScript = new JButton("SuperScript");
        SuperScript.setBounds(25, 144, 105, 23);

        MyText = new JTextPane();

        JScrollPane Scroll = new JScrollPane(MyText);
        Scroll.setBounds(269, 106, 310, 184);

        getContentPane().add(See);
        getContentPane().add(Finish);
        getContentPane().add(Sizes);
        getContentPane().add(lblFontFamlies);
        getContentPane().add(lblFontSizes);
        getContentPane().add(Bold);
        getContentPane().add(Italic);
        getContentPane().add(SuperScript);
        getContentPane().add(Scroll);

        JLabel lblNewLabel = new JLabel("????");
        lblNewLabel.setForeground(Color.RED);
        lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 14));
        lblNewLabel.setBounds(162, 148, 46, 14);
        getContentPane().add(lblNewLabel);

        this.setLocationRelativeTo(null);
        initialize();
        setVisible(true);
    }

    private void initialize()
    {
        // fill up the combo box

        fontList =  java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
        int pos = 0;   
        for (int i = 0; i < fontList.length; i++) 
        {
            String wk = fontList[i];
            Fonts.addItem(wk);
            if (wk.equals("Garamond"))    pos = i;
        }
        Fonts.setSelectedIndex(pos);
        for (int i = 0; i < fontSizes.length; i++)
        {
            String wk = fontSizes[i];
            Sizes.addItem(wk);
            if (wk == "12")    pos = i;
        }
        Sizes.setSelectedIndex(pos);
        MyText.setBorder( BorderFactory.createLineBorder(Color.RED) );
        initStyle() ;

        // MyText.setText("<html><head></head><body>Maître Corbeau sur un arbre, perché <br>Tenait en son bec un fromage.<br>" + 
        //               "Maître Renard par l'odeur, alléché,<br> lui tint à peu près ce langage.  ");

        MyText.setText("<html><head></head><body>I would love that my code works <br>but unfortunatly there is a case.<br>where it does not work<br>that means with  superscripts</body></html>");


        définirListeners();
    }

    private void définirListeners()
    {
        Fonts.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent arg0) { clickOnFonts();}
        }); 

        Sizes.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent arg0) {clickOnSIzes();}
        }); 

        Bold.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) 
            {
                 Action action = new StyledEditorKit.BoldAction();
                 action.actionPerformed(null);
            }
        });


        Italic.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) 
            {
                 Action action = new StyledEditorKit.ItalicAction();
                 action.actionPerformed(null);
            }
        });

        See.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) 
            {
                displayHTMLode(); 
            }
            });

        SuperScript.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent e) 
            {
                // I dont' know what I have to do ....!!!
            }
        });
    }

    public boolean testSelection() 
    { 
        if (MyText.getSelectedText() == null )  return false;
    //  int selStart = MyText.getSelectionStart();
    //  int selEnd = MyText.getSelectionEnd();
        return true; 
    }

    public void clickOnFonts() 
    {
        if(!testSelection()) return; 
        String curFontName = (String) Fonts.getSelectedItem();
        Action FontFamily =  new StyledEditorKit.FontFamilyAction(curFontName, curFontName);
        FontFamily.actionPerformed(null);
    //  restorerZoneSelectionnée();
    }

    public void clickOnSIzes() 
    {
        if(!testSelection()) return; 
        String wk = (String) Sizes.getSelectedItem();
        int curFontSize = Integer.parseInt(wk);
        Action FontSize = new StyledEditorKit.FontSizeAction("" + curFontSize, curFontSize);
        FontSize.actionPerformed(null);
        // restorerZoneSelectionnée();
    }

    private void displayHTMLode()
    {
        try 
        {
                    OutputStream writer = new ByteArrayOutputStream();
                    htmlDoc = (HTMLDocument)  MyText.getDocument();
                    int le = htmlDoc.getLength();
                    htmlKit.write(writer, htmlDoc, 0, le) ;
                    String texteFinal  = writer.toString();
                    System.out.println(texteFinal);
                    JOptionPane.showMessageDialog(this, texteFinal );
                    return;
        } 
        catch (Exception ex) {  System.out.println(ex.toString());}
        return;
    }

    public void initStyle() 
    {

        MutableAttributeSet attributes = new SimpleAttributeSet();
        StyleConstants.setBold(attributes , true);
        StyleConstants.setFontSize(attributes, 14);
        StyleConstants.setFontFamily(attributes, "Garamond");
        StyleConstants.setItalic(attributes, false); 
        StyleConstants.setAlignment(attributes,StyleConstants.ALIGN_RIGHT );
        StyleConstants.setUnderline(attributes, false);
        StyleConstants.setRightIndent(attributes, 0F); 
        StyleConstants.setLeftIndent(attributes, 0F); 
        StyleConstants.setForeground(attributes, Color.RED);
        StyleConstants.setSubscript(attributes, false);
        StyleConstants.setSuperscript(attributes, false);
        StyleConstants.setLineSpacing(attributes, 1);
        StyleConstants.setSpaceBelow(attributes, 1F);
        StyleConstants.setSpaceAbove(attributes, 1F); 

        MyText.setEditorKit(new StyledEditorKit());
        MyText.setContentType("text/html"); 
        htmlDoc = (HTMLDocument) MyText.getStyledDocument();
        htmlDoc.setCharacterAttributes(0, htmlDoc.getLength(),  attributes, true);
        MyText.setDocument(htmlDoc);


    }

    public static void  main (String[] arg)
    {
        new Test_HTMLKit();
    }
}
html jtextpane superscript
2个回答
0
投票

没有内置功能来做到这一点。但是,您可以创建它。您可以尝试下列条件之一:

  • 使用库创建的数学内容,如jeuclid
  • 使用setAlignmentY的内组件上设置的常规基线以上每个字母
  • 创建您自己的组件,将吸引上标字母,并更新文档的view factory创建扩展当前行为。

0
投票

我想我已经通过查看StyledEditorKit源代码中发现了更简单的解决方案。我创建了这个类的一个扩展,等基于它的代码,我公司开发的实施标,我会为下标以后做。这工作得很好。不管怎样,谢谢您的回答。这里是我的代码

     import java.awt.event.ActionEvent;
     import javax.swing.Action;
     import javax.swing.JEditorPane;
     import javax.swing.text.MutableAttributeSet;
     import javax.swing.text.SimpleAttributeSet;
     import javax.swing.text.StyleConstants;
     import javax.swing.text.StyledEditorKit;
     import javax.swing.text.TextAction;

     public class MCB_StyleEditorKit extends StyledEditorKit
     {

        private static final long serialVersionUID = 1L;
        private static final Action[] defaultActions = 
            {
             new FontFamilyAction("font-family-SansSerif", "SansSerif"),
             new FontFamilyAction("font-family-Monospaced", "Monospaced"),
             new FontFamilyAction("font-family-Serif", "Serif"),
             new FontSizeAction("font-size-8", 8),
             new FontSizeAction("font-size-10", 10),
             new FontSizeAction("font-size-12", 12),
             new FontSizeAction("font-size-14", 14),
             new FontSizeAction("font-size-16", 16),
             new FontSizeAction("font-size-18", 18),
             new FontSizeAction("font-size-24", 24),
             new FontSizeAction("font-size-36", 36),
             new FontSizeAction("font-size-48", 48),
             new AlignmentAction("left-justify", StyleConstants.ALIGN_LEFT),
             new AlignmentAction("center-justify", StyleConstants.ALIGN_CENTER),
             new AlignmentAction("right-justify", StyleConstants.ALIGN_RIGHT),
             new BoldAction(),
             new ItalicAction(),
             new SuperscriptAction(),
            // new StyledInsertBreakAction(),
             new UnderlineAction()
         };

         public Action[] getActions() {
                return TextAction.augmentList(super.getActions(), this.defaultActions);
            }
         public static class SuperscriptAction extends StyledTextAction 
         {

             private static final long serialVersionUID = 1L;
                public SuperscriptAction() 
                {
                    super("font-superscript");
                }

                /**
                 * Toggles the bold attribute.
                 *
                 * @param e the action event
                 */
                public void actionPerformed(ActionEvent e) {
                    JEditorPane editor = getEditor(e);
                    if (editor != null) {
                        StyledEditorKit kit = getStyledEditorKit(editor);
                  MutableAttributeSet attr = kit.getInputAttributes();
                  boolean superscript = (StyleConstants.isSuperscript(attr)) ? false : true;
                  SimpleAttributeSet sas = new SimpleAttributeSet();
                  StyleConstants.setSuperscript(sas, superscript);
                  setCharacterAttributes(editor, sas, false);
              }
          }
      }
      }
© www.soinside.com 2019 - 2024. All rights reserved.