java - 使用 JTextPane 为选定文本应用颜色

标签 java swing jtextpane nimbus

我想用用户选择的文本颜色显示所选文本。我选择了一些文本并单击 settextcolor,它应用于 JTextPane 中存在的所有文本而不是所选文本。我只想将颜色应用于所选文本。请帮助我.. 这是我的代码:

public class SetTextColor extends javax.swing.JFrame {

    int i=0;
    JTextPane textPane;
    JScrollPane scrollPane;

    public SetTextColor() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        tabbedPane = new javax.swing.JTabbedPane();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        Create = new javax.swing.JMenuItem();
        SetTextColor = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jMenu1.setText("File");

        Create.setText("Create");
        Create.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CreateActionPerformed(evt);
            }
        });
        jMenu1.add(Create);

        SetTextColor.setText("SetTextColor");
        SetTextColor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SetTextColorActionPerformed(evt);
            }
        });
        jMenu1.add(SetTextColor);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 298, Short.MAX_VALUE)
        );

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

    private void CreateActionPerformed(java.awt.event.ActionEvent evt) {                                       
       final JInternalFrame internalFrame = new JInternalFrame("");
        i++;
        internalFrame.setName("Document"+i);
        internalFrame.setClosable(true);
        internalFrame.setAutoscrolls(true);
        textPane=new JTextPane();
        textPane.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
        scrollPane=new JScrollPane(textPane);
        internalFrame.add(scrollPane);
        tabbedPane.add(internalFrame);
        internalFrame.setSize(internalFrame.getMaximumSize());
        internalFrame.pack();
        internalFrame.setVisible(true);
    }                                      

    private void SetTextColorActionPerformed(java.awt.event.ActionEvent evt) {                                             
       Color color = JColorChooser.showDialog(this, "Colors",Color.BLUE);
        StyledDocument doc = textPane.getStyledDocument();
        String text=textPane.getSelectedText();
        Style style = textPane.addStyle("I'm a Style", null);
        StyleConstants.setForeground(style, color);
        textPane.setForeground(color);
    }                                            
    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(SetTextColor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SetTextColor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SetTextColor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SetTextColor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SetTextColor().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JMenuItem Create;
    private javax.swing.JMenuItem SetTextColor;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JTabbedPane tabbedPane;
    // End of variables declaration                   
}

最佳答案

那是因为您设置 TextPane 的文本颜色

textPane.setForeground(color);

如果您只想为段落或某些必须使用的字符设置样式:

StyledDocument.setParagraphAttributes(offset, length, s, replace);

StyledDocument.setCharacterAttributes(offset, length, s, replace);

像这样:

private void SetTextColorActionPerformed(java.awt.event.ActionEvent evt) {                                             
    Color color = JColorChooser.showDialog(this, "Colors",Color.BLUE);
    StyledDocument doc = textPane.getStyledDocument();
    int from = textPane.getSelectionStart();
    int to = textPane.getSelectionEnd();
    Style style = textPane.addStyle("I'm a Style", null);
    StyleConstants.setForeground(style, color);
    doc.setCharacterAttributes(from, to-from, style, true);
} 

关于java - 使用 JTextPane 为选定文本应用颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24163071/

相关文章:

java - JScrollBar + JTextPane 与 HTML 未正确滚动到最大值

java - 将 html 文档加载到 JTextPane 使我的编辑器在粘贴时表现非常糟糕

java - gradle在不相关的不同项目之间共享属性

java - JLabel 定位到 JPanel 中

java - 如何使图像链接在 JtextPane 中工作?

java - 我可以在关机时进行 Swing 操作吗?

java - 如何突出显示替换所选单词的单词?

java - 如何在 Spring 将@Scheduled(cron) 与SpEL 一起使用?

java - 为什么 Tomcat 7 内存使用情况看起来像锯? (图片)

java - 如何调用父类(super class)的重写方法?