0

嘿,我有一些问题/问题。

我必须创建一个用于文本编辑的小程序。(选定的)文本应该是样式。粗体、斜体、下划线、左右对齐。它工作得很好。我使用了特定的 StyleEditorKit 动作。

我现在的问题是,这些操作是通过 jtoolbar 中的按钮和 jmenu / jmenubar 中的 jmenuitems 触发的。

所以有两个点击元素设置文本粗体,两个元素设置文本斜体等等。如果单击一个元素(例如工具栏中的按钮),则 jmenuitem 也应该被选中/激活。但我怎么能意识到这一点?

我的想法是检查选定的文本(实现了 CaretListener)。如果文本是粗体 => 将按钮和菜单项设置为活动状态。但是如果 selectedText 是粗体/斜体等,我怎么能得到?

我认为这些东西有一个带有叶子的 StyledDocument 树。但是我怎样才能得到这棵树呢?我怎样才能得到叶子?

这是我的第一步:

jTextPane1.addCaretListener(new CaretListener() {

    @Override
    public void caretUpdate(CaretEvent e) {
        Highlight[] h = jTextPane1.getHighlighter().getHighlights();
        for(int i = 0; i < h.length; i++) {
            System.out.println(h[i].getStartOffset());
            System.out.println(h[i].getEndOffset());
            String selectedText = jTextPane1.getSelectedText();


            StyledDocument styleddoc = (StyledDocument) jTextPane1.getDocument();

            System.out.println(styleddoc);

        }

    }
});

但我只得到 javax.swing.text.DefaultStyledDocument@5098cb76

我如何遍历树并获得叶子/粗体或斜体元素?

谢谢

4

4 回答 4

0

我的代码现在看起来像这样

public void jToolBarInitButtons() {

    jTextPane1.addCaretListener(new CaretListener() {

    @Override
    public void caretUpdate(CaretEvent e) {

        StyledDocument styleddoc = (StyledDocument) jTextPane1.getDocument();

            AttributeSet attributes = jTextPane1.getCharacterAttributes();
            System.out.println("bold " +  attributes.containsAttribute(StyleConstants.Bold, Boolean.TRUE));
            System.out.println("italic " + attributes.containsAttribute(StyleConstants.Italic, Boolean.TRUE));

    }
于 2016-05-11T16:14:35.653 回答
0

所以有两个点击元素设置文本粗体,两个元素设置文本斜体等等。如果单击一个元素(例如工具栏中的按钮),则 jmenuitem 也应该被选中/激活。但我怎么能意识到这一点?

通过将相同的Action传递给它们的构造函数来创建菜单项和按钮。

听起来您打算在按钮和菜单项中显示粗体状态,因此您可能需要创建一个 JCheckBoxMenuItem 和一个 JToggleButton。创建 Action 时,将其SELECTED_KEY设置为非空值,以便按钮使其保持最新:

action.putValue(Action.SELECTED_KEY, false);

从动作文档中:

SELECTED_KEY

支持此属性的组件仅在它是非时才使用该值null。例如,如果您为on a设置了Action一个 null 值,则不会以任何方式更新其选定状态。同样,只要 的选定状态发生变化,它只会将值设置回 ,如果具有非值。遵守此属性的组件保持其选定状态与此属性同步。当多个组件使用相同时,所有组件保持其选定状态与此属性同步。SELECTED_KEYJToggleButtonJToggleButtonJToggleButtonActionActionnullSELECTED_KEYAction

您的 CaretListener 应该与camickr 描述的一样。

于 2016-05-11T16:29:21.260 回答
0

对不起。这是整个代码:

更新 2:这是代码

public class TestFrame extends javax.swing.JFrame {

    /**
     * Creates new form TestFrame
     */
    public TestFrame() {
        initComponents();
        initButtons();
    }

    Action boldAction = new StyledEditorKit.BoldAction();    
    Action italicAction = new StyledEditorKit.ItalicAction();
    Action underlineAction = new StyledEditorKit.UnderlineAction();

    public void initButtons() {
        JButton boldButton = new JButton(boldAction);
        boldButton.setText("bold");

        JButton italicButton = new JButton(italicAction);
        boldButton.setText("italic");

        JButton underlineButton = new JButton(underlineAction);
        boldButton.setText("underline");

        jToolBar1.add(boldButton);
        jToolBar1.add(italicButton);
        jToolBar1.add(underlineButton);

        jTextPane1.addCaretListener(new CaretListener() {

        @Override
        public void caretUpdate(CaretEvent e) {
            Highlighter.Highlight[] h = jTextPane1.getHighlighter().getHighlights();
            for(int i = 0; i < h.length; i++) {
                System.out.println("length " +  h.length);
                System.out.println(h[i].getStartOffset());
                System.out.println(h[i].getEndOffset());
                String selectedText = jTextPane1.getSelectedText();


                StyledDocument styleddoc = (StyledDocument) jTextPane1.getDocument();

                AttributeSet attributes = jTextPane1.getCharacterAttributes();
                System.out.println("Bold " + attributes.containsAttribute(StyleConstants.Bold, Boolean.TRUE));
                System.out.println("Italic " + attributes.containsAttribute("Italic " + StyleConstants.Italic, Boolean.TRUE));
                System.out.println("Underline " + attributes.containsAttribute(StyleConstants.Underline, Boolean.TRUE));
            }

        }
    });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jToolBar1 = new javax.swing.JToolBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jScrollPane1.setViewportView(jTextPane1);

        jToolBar1.setRollover(true);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(116, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 269, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(75, 75, 75))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(14, 14, 14)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(89, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TestFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextPane jTextPane1;
    private javax.swing.JToolBar jToolBar1;
    // End of variables declaration                   
}
于 2016-05-11T16:24:14.153 回答
0

如果 selectedText 是粗体/斜体等,我怎么能得到?

在您的 CaretListener 中,您可以使用:

AttributeSet attributes = jTextPane1.getCharacterAttributes();
System.out.println( attributes.containsAttribute(StyleConstants.Bold, Boolean.TRUE) );

如果单击一个元素(例如工具栏中的按钮),则 jmenuitem 也应该被选中/激活。

您应该使用Action

Action bold = new StyledEditorKit.BoldAction();
JButton boldButton = new JButton( bold );
JCheckBoxMenuItem boldMenuItem = new JCheckBoxMenuItem( bold );

当您设置 的状态时Action,所有使用 的组件的状态都会Action更改。例如,您可以Action选择或启用。

于 2016-05-11T15:47:22.860 回答