在这个例子中如何使 JPanel 透明?渐变背景不可见:
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 and my JPanel too :(");
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);
} finally {
g2d.dispose();
}
super.paint(g);
}
}