How to properly use StyledEditorKit for aligning text

192 Views Asked by At

Basically, what I want to do is to center text that I've selected with my mouse (through normal left click, drag over the words, they turn blue. No special highlighting functions or anything like that.) and then allign it either to the left, center, or right. I already have buttons and actionListeners set up to handle this, I just need the code inside the actionListener.

To be clear, I don't want to use this:

setHorizontalAlignment(JTextField.CENTER);

This centers the entire text field, and that's not what I'm looking for. What I am looking for is very similar to what you see in word processors now where only the selected text is alligned. This way I can have one line of text that is left alligned, and then the one right below it can be center alligned.

I've fiddled with StyledEditorKit before, and I think that was what I need to use. I'm guessing I can use the StyledEditorKit.AlignmentAction, however, the method requires a string and an integer, and doesn't really specify what these are for.

Would a StyledEditorKit be the best way to do this? Or is there a more efficient way that I'm just not aware of?

1

There are 1 best solutions below

0
camickr On

I'm guessing I can use the StyledEditorKit.AlignmentAction,

Correct.

howevewr, the method requires a string and an integer, and doesn't really specify what these are for.

And you didn't think to search the forum using that class name to find examples that create the alignment Action?

One would be for the description to appear on the menu item / button. The other would be for the type of alignment right/center/left.

Would a StyledEditorKit be the best way to do this?

Yes. Swing was designed to be used with Actions.

Check out Key Bindings. It lists all the default Actions for a given Swing component.

You could get the existing Action from the ActionMap or you could create a new instance of the Action.