java - JPanel on JWindow is not transparent if `set setOpaque(false);` - why? -
how make jpanel transparent in example? gradient background not visible:
package test; import java.awt.color; import java.awt.dimension; import java.awt.gradientpaint; import java.awt.graphics; import java.awt.graphics2d; import javax.swing.boxlayout; import javax.swing.jlabel; import javax.swing.jpanel; import javax.swing.jwindow; public class paintjpanelonjwindow extends jwindow { public paintjpanelonjwindow() { jpanel panel = new jpanel(); panel.setpreferredsize(new dimension(350, 120)); panel.setminimumsize(new dimension(350, 120)); panel.setmaximumsize(new dimension(350, 120)); panel.setlayout(new boxlayout(panel, boxlayout.y_axis)); panel.setopaque(false); jlabel sometext = new jlabel("i'm not transparent , jpanel :("); sometext.setopaque(false); panel.add(sometext); add(panel); pack(); setlocationrelativeto(null); setvisible(true); } @override public void paint(graphics g) { graphics2d g2d = (graphics2d) g.create(); try { int w = getwidth(), h = getheight(); g2d.setpaint(new gradientpaint(0, 0, color.red, 0, h, color.white)); g2d.fillrect(0, 0, w, h); } { g2d.dispose(); } super.paint(g); } }
the immediate problem
super.paint(g);
is being called after custom painting code in paint
method cause previous painting lost. calling panel.setopaque(false)
has no effect done in paint
method. calling setopaque
of components in question unnecessary - default backgrounds displayed when custom painting correctly implemented.
this should done overriding paintcomponent method. means creating new jpanel
, placing custom painting functionality there rather in top level container such jwindow
.
example:
public class paintjpanelapp { public static void main(string[] args) { swingutilities.invokelater(new runnable() { @override public void run() { jframe frame = new jframe("gradient app"); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setundecorated(true); frame.setlocationrelativeto(null); jlabel sometext = new jlabel("i transparent , jpanel :)"); gradientpanel gradientpanel = new gradientpanel(); gradientpanel.add(sometext); frame.add(gradientpanel); frame.pack(); frame.setvisible(true); } }); } static class gradientpanel extends jpanel { @override protected void paintcomponent(graphics g) { super.paintcomponent(g); int w = getwidth(); int h = getheight(); graphics2d g2d = (graphics2d) g; g2d.setpaint(new gradientpaint(0, 0, color.red, 0, h, color.white)); g2d.fillrect(0, 0, w, h); } } }
Comments
Post a Comment