Question

I have this code to put the selected text in bold, and works fine, but how I can remove the style? I want to make a button, which when clicked the button, place and remove the style. I thought of make an if, but how I can compare?

    StyledDocument doc = texto.getStyledDocument();
    int start = texto.getSelectionStart();
    int end = texto.getSelectionEnd();
    if (start == end) { // No selection, cursor position.
    return;
        }
        if (start > end) { // Backwards selection?
    int life = start;
    start = end;
    end = life;
        }
    Style style = texto.addStyle("negra", null);
    StyleConstants.setBold(style, true);
    doc.setCharacterAttributes(start, end - start, style, false);
Was it helpful?

Solution

i used your code and got it to work this way. hope it helps.

    package main;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.text.*;

public class Main {

    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    JTextPane textPane = new JTextPane();

    JButton button = new JButton("Test");

    public Main() {
        frame.setTitle("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        panel.setLayout(new BorderLayout());
        panel.setPreferredSize(new Dimension(200, 200));

        panel.add(textPane, BorderLayout.CENTER);
        panel.add(button, BorderLayout.SOUTH);
        textPane.addStyle("negra", null);

        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                StyledDocument doc = textPane.getStyledDocument();
                int start = textPane.getSelectionStart();
                int end = textPane.getSelectionEnd();
                if (start == end) { // No selection, cursor position.
                    return;
                }
                if (start > end) { // Backwards selection?
                    int life = start;
                    start = end;
                    end = life;
                }
                Style style = textPane.getStyle("negra");

                // I think this is what you need
                if (StyleConstants.isBold(style)) {
                    StyleConstants.setBold(style, false);
                } else {
                    StyleConstants.setBold(style, true);
                }
                doc.setCharacterAttributes(start, end - start, style, false);
            }
        });

        frame.add(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Main();
            }
        });

    }
}

OTHER TIPS

I did a demo for you, note JTextPane related problem seemed a littile complex ,I haven't master it all sides.

The demo give you some possible way to do it,you need to improve it to meet your need.

Select the text and click the button to see the style change.

code as follow:

package com.learningjava;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.text.AttributeSet;
import javax.swing.*;
import javax.swing.text.*;

/**
 * Note: code is a possible way to do 
 * you need to improved it to meet your requirements
 * 
 * @author wangdq
 * 2013-1-3
 */
public class TextPaneStyleTest {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){

            @Override
            public void run() {
                // TODO Auto-generated method stub
                JFrame frame = new TextStyleTestFrame();
                frame.setSize(300, 300);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}
/**
 * TextPane style test frame
 * Select text and click the button to see style change
 */
class TextStyleTestFrame extends JFrame {

    public TextStyleTestFrame() {
        super("TextPaneStyle Test");
        textPane.setText("Smaple String");
        this.add(textPane,BorderLayout.CENTER);
        JPanel panel = new JPanel();
        panel.add(btnStyle);
        this.add(panel,BorderLayout.NORTH);
        btnStyle.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                changeStyle();
            }
        });
    }
    /**
     * change style according to your rule
     */
    private void changeStyle() {

        //get selected text style
        StyledDocument doc=(StyledDocument)textPane.getDocument();
        int selectionEnd=textPane.getSelectionEnd();
        int selectionStart=textPane.getSelectionStart();
        if(selectionStart ==  selectionEnd)  {
            return;
        }
        Element element=doc.getCharacterElement(selectionStart);
        AttributeSet as = element.getAttributes();
        //apply a new style based on previous 
        MutableAttributeSet asNew = new SimpleAttributeSet(as.copyAttributes());
        StyleConstants.setBold(asNew, !StyleConstants.isBold(as));
        doc.setCharacterAttributes(selectionStart,textPane.getSelectedText().length(), asNew, true);
        String text = (StyleConstants.isBold(as) ? "Cancel Bold":"Bold");
        btnStyle.setText(text);
    }
    private static final long serialVersionUID = 1L;
    private JButton btnStyle = new JButton("Bold");
    private JTextPane textPane =new JTextPane();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top