如何在此示例中使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);
}
}
答案 0 :(得分:2)
来自JavaDocs:
create():创建一个新的Graphics对象,该对象是此Graphics对象的副本。
这意味着Graphics
对象g2d
未引用JWindow
Graphics
对象,它指的是副本 JWindow
Graphics
对象。
您需要更改
Graphics2D g2d = (Graphics2D) g.create(); //creates a copy, wrong object
要
Graphics2D g2d = (Graphics2D) g; //refers to the right Graphics object
<强>更新强>
但是,这不是正确的方法。您应该覆盖JPanel
的{{1}}方法,而不是破坏窗口的绘制过程。首先,从您的类中删除paintComponent
方法覆盖。然后,按如下方式初始化paint()
:
JPanel
答案 1 :(得分:2)
当前的问题是
super.paint(g);
在paint
方法中自定义绘制代码后,被称为,这会导致之前的绘画丢失。调用panel.setOpaque(false)
对paint
方法中的操作没有影响。不需要为问题中的任何组件调用setOpaque
- 默认情况下,正确实现自定义绘画时会显示背景。
这应该通过覆盖paintComponent方法来完成。这意味着创建一个新的JPanel
并将自定义绘画功能放在那里,而不是放在顶级容器中,例如JWindow
。
示例:
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 AM transparent and my JPanel too :)");
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);
}
}
}