简体   繁体   English

使用Swing设置选定的文本颜色

[英]Set a selected text color using Swing

I want to display a selected text with user selected color.My problem here is I had select some text and click on settextcolor it was applied to all the text not selected text.Please give me.. Here is my code: 我想用用户选择的颜色显示选择的文本。我的问题是我选择了一些文本,然后单击settextcolor,将其应用于所有未选择的文本。请给我。这是我的代码:

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                   

} }

This likely the default behaviour of the Caret , which will hide the selection when the text component loses focus. 这可能是Caret的默认行为,当文本组件失去焦点时,它将隐藏选择。

You can change this by creating a custom Caret and overriding the isSelectionVisible method to always return true 您可以通过创建自定义Caret并覆盖isSelectionVisible方法以始终返回true来更改此设置

For example... 例如...

DefaultCaret caret = new DefaultCaret() {

    @Override
    public boolean isSelectionVisible() {
        return true;
    }

};

文字选择颜色

...Runnable example... 可运行的示例

import java.awt.Color;
import javax.swing.JColorChooser;
import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.DefaultCaret;

public class SetTextColor extends javax.swing.JFrame {

    int i = 0;
    JTextArea textArea;
    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);
        textArea = new JTextArea();
        DefaultCaret caret = new DefaultCaret() {

            @Override
            public boolean isSelectionVisible() {
                return true;
            }

        };
        textArea.setCaret(caret);
        textArea.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
        scrollPane = new JScrollPane(textArea);
        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);
        // textArea.setBackground(color);
        textArea.setSelectedTextColor(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                   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM