tags:

views:

328

answers:

3

I have a form that tries to modify a JComponent's graphics context. I use, for example,

((Graphics2D) target.getGraphics()).setStroke(new BasicStroke(5));

Now, immediately after I set the value and close the form, the change is not visible. Am I not allowed to modify a JComponent's graphics context? How else would I modify the stroke, color and transformations?

Thanks,

Vlad

+2  A: 

There are several problems with that approach. The first is that most components will set these things themselves when ever they are asked to repaint themselves. This means that your change will be lost every time the component gets to the point where it would actually use it. But, on an even more fundamental level than that, Graphics2D objects are not persistant. They are typically instantiated every time the component is redrawn, meaning that the Graphics2D object you got won't be the same the component will be using when redrawing.

What you need to do, to achieve this kind of thing is either to reimplement the specific component yourself, or implement a new look and feel that will affect the entire set of swing components. Have a look at the following link for further details about this:

http://today.java.net/pub/a/today/2006/09/12/how-to-write-custom-look-and-feel.html

kasperjj
+1  A: 

Nobody to answer? I have let some time to see if there is any good answer before mine: I am not a specialist of such question...

First, I don't fully understand your question: you change a setting then close the form?

Anyway, I am not too sure, but somewhere in the process, the graphics context might be recomputed or taken from default. Perhaps if you do this operation in the paint() method, you can get some result, although I am not sure.

For a number of changes, you usually use a decorator. I explored a bit this topic when answering a question on SO: How do I add a separator to a JComboBox in Java?. I had to paint my own border there (asymmetrical), but often you just take an existing one, so it is quite simple.

I hope I provided some information, if it didn't helped, perhaps you should give more details on what you want to do (and perhaps a simple, minimal program illustrating your problem).

PhiLho
A: 

OK, I've worked around the problem like this: The custom JComponent now holds a Stroke object, which is set by the "Choose stroke" form when the user clicks OK. Then, in the paint method of the JComponent, I set the stroke of the graphics context passed as parameter to paint to the one contained in the object.

I have experimented and found out that, for some reason, JComponent.getGraphics().set* doesn't work.

ddvlad