Phil
Phil

Reputation: 36289

How can I change the color or bounds of a Java Component without subclassing it?

I am working with the Java timing framework to perform animations. What I would like is to be able to perform some animation on an AWT or Swing Component without subclassing it. Animations I am interested in include changing the bounds, color, or alpha. There are numerous examples online of how to subclass a Component, then override the paint(Graphics) method in order to perform such changes, however I would like to find a different approach.

I have tried obtaining the graphics for a Component by calling

Graphics2D g2d = (Graphics2D) component.getGraphics();

Then manipulating it - such as setting the alpha value:

AlphaComposite newComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, newVal);
g2d.setComposite(newComposite);
component.repaint();

However this did nothing. I have tried other approaches - such as using custom TimingTargets, or PropertySetters, but I have not had any luck. What is the correct approach?

To give more context to this question, this is for my javaQuery library, which is a port of jQuery to Java, and is modeled after my previous project (with working animations) droidQuery.

Upvotes: 0

Views: 132

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109597

Use swing (or JFX). AWT is old and less customizable as it uses native platform components: peers every Java AWT component with a native one.

With bounds I assume border You can set borders (even additive) and colors. setOpaque(false) allows transparency.

Getting the component's Graphics should never be done. A component receives a paint event, in a well defined context: single threaded on the event handling thread, clipped, positioned and more.

So use the component's setters, invalidate should that be needed. And possibly a repaint(50L)`.

Upvotes: 0

Related Questions