简体   繁体   中英

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 TimingTarget s, or PropertySetter s, 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 .

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 . And possibly a repaint(50L)`.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM