Search code examples
javaswingjtextpanecaret

JTextPane change the font of a certain starting point


How to change the font of a certain starting point?

I have a button, switch the font at certain point.

Example:

somtext |

Press the button

sometext boldedtext|

So I made the event key release but I can see the changing font a ever key released

This the key released event

         private void textoKeyReleased(javax.swing.event.CaretEvent evt)                  {                                  
          int end = texto.getSelectionEnd();
            StyledDocument doc = texto.getStyledDocument();

            Style style = texto.getStyle("negra");

        if (car==1) 
            {

            StyleConstants.setBold(style, true);
            doc.setCharacterAttributes(end-1,end, style, false);
            texto.requestFocus();
            texto.moveCaretPosition(doc.getLength());
            }
        if(car==0)
        {
            StyleConstants.setBold(style, false);
            doc.setCharacterAttributes(end-1 ,end, style, false);
            texto.requestFocus();
            texto.moveCaretPosition(doc.getLength());
        }  
    }

But I see

first a

finale a

the update isn't on real time there is another method:


Solution

  • The problem with the key release event in the KeyListener interface is that it is invoked only when the user let go of the key. In your code, if the user held onto a key to repeat it, only the last character will be modified according to the set style. Also, during typing, if the user press the second key before releasing the first one, again only the last character is updated.

    One alternate approach is to invoke your code within the keyTyped method in KeyListener interface.

    Also simplified the code a bit.

    private void textoKeyReleased(javax.swing.event.CaretEvent evt) {
        int end = textPane.getSelectionEnd();
        StyledDocument doc = textPane.getStyledDocument();
    
        Style style = textPane.getStyle("negra");
        StyleConstants.setBold(style, car == 1);
        doc.setCharacterAttributes(end - 1, 1, style, false);
        textPane.requestFocus();
    }
    
    @Override
    public void keyTyped(KeyEvent e) {
        SwingUtilities.invokeLater(new Runnable() {         
            @Override
            public void run() {
                textoKeyReleased(null);
            }
        });
    }