1

Below is the code I have to set all text within my text pane to bold but how can I get only the text that I have highlighted to be bold and achieve the following?

private void jButtonBoldActionPerformed(java.awt.event.ActionEvent evt) {                                              
    // TODO add your handling code here:
    jTextPaneBody.setFont(jTextPaneBody.getFont().deriveFont(Font.BOLD));
}
  • If the highlighted text is normal, change it to bold when I click the button

  • If the highlighted text is in bold, change it to normal when I click the same button

Kevin Reid
  • 37,492
  • 13
  • 80
  • 108
wbk727
  • 8,017
  • 12
  • 61
  • 125
  • 1
    Like [this](http://stackoverflow.com/a/8534162/230513) or [this](http://stackoverflow.com/a/15600689/230513)? – trashgod Jan 21 '15 at 21:34
  • Almost, but I also need an if statment to check whether or not the selected text is in bold. – wbk727 Jan 21 '15 at 21:36
  • 1
    You can traverse the `Document` like [this](http://stackoverflow.com/a/9561545/230513), but the `StyledEditorKit` actions may be enough. – trashgod Jan 21 '15 at 21:37

1 Answers1

1

Can't be done with a (J)TextField. If you need this functionality, you can use a JTextPane with a StyledEditorKit and a StyledDocument

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • Now you have the problem of the fact that JTextPane doesn't support ActionListener (Zhong know of that's important to the op, but it's a consideration) and the fact that JTextPane is multi-lined where as JTextField isn't...not saying what you've said is wrong, just that it creates a bunch of other issues – MadProgrammer Jan 21 '15 at 21:24
  • Totally agree. Thanks for adding this; should have done it myself, but it's getting close to quitting time over here :-) – ControlAltDel Jan 21 '15 at 21:27
  • Just changed the code to a text pane. What needs to change based on what I want to achieve? – wbk727 Jan 21 '15 at 21:31
  • @MacaronLover As MadProgrammer pointed out, there's a fair amount I'm afraid. First, you should play around with applying styles to your document, just to get comfortable with it - it's not something you can pick up in 30 minutes. Second, you'll probably want to add a DocumentListener to prevent new lines. Third, you'll need to either override JTextPane or use setPreferredSize to get it to size like a JTextField – ControlAltDel Jan 21 '15 at 21:39
  • Use the `StyledEditorKit` actions, for [example](http://stackoverflow.com/a/8534162/230513). – trashgod Jan 21 '15 at 21:41
  • @ControlAltDel I don't want to set the size of my text pane. I'm trying to replicate a function in gmail where I can highlight a word of two and then click a button to change the highlighted words to bold then I click the same button again to change the words back to normal. – wbk727 Jan 21 '15 at 21:44