views:

279

answers:

2

I am trying to change the font of the text in a textarea in Swing. Which listener should I use on textarea to trigger an action that lets the program initiate the font code.

All the examples have all the swing in the same class which lets you access the textarea directly, but I have multiple classes; I know I can pass the textarea in and in and in, but this is sloppy.

I just cannot figure out which listener to initiate.

+1  A: 

If you're listening to the textarea, then it would depend on how many different ways you want the user to be able to change the font of what they are typing.

You could use MouseListener if you want them to be able to change the font on right click/etc... or a KeyListener if you want to listen for a series of keys.

jex
+2  A: 

I am trying to change the font of the text in a textarea in Swing.

Well a JTextArea can only have a single Font, so if you want to change the Font you would have some other component, maybe a "Change Font" button that you would click. In this case you would add an ActionListener to the button to change the actual Font of the text area.

If you actually need to change the Font on selected pieces of text, then you also can't do this with a JTextArea. You would need to use a JTextPane. Read the JTextPane API and follow the link to the Swing tutorial on "Text Component Features" for an example of changing attributes on selected text. In this cause you use Actions provided by the editor kit.

So basically you need to read the Swing tutorial to find out the basics of using Swing components.

camickr
I am trying to change all the font in a JTextArea, which I have working by passing the textArea to my actions. What I am trying to figure out is how to make it so I don't have to pass the textArea into my actions.
Kraagenskul
The Actions defined in the EditorKit all extend from TextAction. TextAction provides a method that returns the last focused text component. So assuming you want the Actions to be performed on that text area you can also write your Actions to extend from TextAction. If you want the Action to be performed on a specific text area, then you would need to pass that text area as a parameter when you create your custom Action.
camickr