Changing the graphics context in Java

I have a form that is trying to change the graphics context of a JComponent. I am using for example

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

      

Now, right after I set the value and close the form, this change is not visible. Am I not allowed to change the graphics context of the JComponent? How else could I change the stroke, color and transforms?

Thank,

Vlad

0


source to share


3 answers


There are several problems with this approach. First, most of the components ask these things themselves when asked to repaint. This means that your changes will be lost every time the component gets to the point where it actually uses it. But on an even more fundamental level, Graphics2D objects are not persisted. They are usually created each time the component is rebuilt, which means that the Graphics2D object you get will not be the same as the component would be used when re-rendering.

What you need to do to achieve this kind of thing is either override a specific component yourself, or implement a new look and feel that will affect the entire set of swing components. For more information on this see the following link:



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

+3


source


Can't anyone answer? I gave some time to see if there is a good answer before mine: I am not an expert on such a question ...

First, I don't quite understand your question: do you change the setting and then close the form?

Anyway, I'm not too sure, but somewhere in the process the graphics context might be recalculated or accepted as the default. Perhaps if you do this operation in the paint () method you can get some result, although I'm not sure.



For a number of changes, you usually use a decorator. I did a little research on this topic when answering a SO question: How do I add a separator to a JComboBox in Java? ... I had to draw my own border there (asymmetrically), but often you just take an existing one, so it's pretty straightforward.

Hopefully I've provided some information, if that didn't help, maybe you should give more details on what you want to do (and maybe a simple, minimal program to illustrate your problem).

+1


source


Ok, I was working on a problem like this one: the custom JComponent now contains a Stroke object that 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 a parameter to paint the one contained in the object.

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

0


source







All Articles