Fondo degradado predeterminado del componente Swing

Is there a way to change the default background painting of all instances of a swing component (a JPanel for example) to paint with a gradient background? Or would I need to create an extension of JPanel that paints with a gradient and then use that instead of JPanel everywhere in my app?

preguntado el 09 de marzo de 12 a las 14:03

Wouldn't you only need to do this for the background JPanel, and then make all other JPanels non-opaque? -

@HovercraftFullOfEels, that's another option too. If I wanted to extend it to other components though, I think I would still need to extend those components. -

@JeffStorey: perhaps, but not necessarily. You could create your JPanels via some simple factory method that sets the opaque to false, or you could recurse through the GUI setting all non-base JPanels to be non-opaque. -

Right, for JPanels (that's actually how I currently do it), but let's say I wanted to apply the gradient to a JButton. I'd have to do the same thing for buttons. I was hoping there was a way to just apply the gradient background to component X, but I'm not sure there is. -

You likely can do this by creating your own look and feel. I've never done this myself though. -

2 Respuestas

IMHO, it would be easier to just subclass the Swing component and override its paintComponent method to do the gradient painting. And then, as you said, use this custom component throughout the application.

It could be tricky using the UI properties since they may not be consistent across all LaFs.

respondido 09 mar '12, 14:03

that was my initial thought. wasn't sure if there was an easier way to do it. especially if I wanted to apply the gradient to multiple component types, I would need to subclass all of the components. - Jeff Storey

@JeffStorey, In that case, maybe it'd be better to subclass JComponent. - Rayo de luna

I'm not sure how that would help for multiple component types. Let's say I was changing the background of a button, how would subclassing JComponent help here? - Jeff Storey

It is not entirely clear what scope you intend. Did you mean by clase (so all JPanel instances follow the new painting scheme), or do you mean todos components in a Container (e.g. everything in Frame)?

There are possibilities to do this depending on component class, the places where you can hook into are the Look and Feel, and on a by component instance base, either the paintComponent() method, or if you need to replace the standard look of an existing component where you can not overwrite the method because you have no control over it, by providing your own UI class (look at Component.setUI) after the component has been created.

Except for the overwrite paintComponent approach neither is simple to implement. For most applications the simple approach is the best :)

respondido 09 mar '12, 15:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.