因为它BallonPanel
是不透明的,所以重绘管理器不会费心在它下面进行绘制。这是对绘画过程的优化,为什么要画那些不需要画的东西。
您需要“说服”重绘管理器在组件下方进行绘制,同时仍绘制其背景。
将 设置BallonPanel
为透明 ( setOpaque(false)
) 并更新paint
方法以填充背景。
public class FadePane {
public static void main(String[] args) {
new FadePane();
}
public FadePane() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.BLUE);
frame.setBackground(Color.BLUE);
frame.add(new BaloonPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class BaloonPanel extends JPanel {
private float transparency = 1f;
Timer timer;
public BaloonPanel() {
setBackground(Color.white);
ActionListener action = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
transparency = transparency - 0.1f;
if (transparency < 0.1f) {
transparency = 0;
timer.stop();
}
invalidate();
repaint();
}
};
timer = new Timer(100, action);
timer.setRepeats(true);
setOpaque(false);
final JButton fade = new JButton("Fade");
fade.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
timer.start();
fade.setEnabled(false);
}
});
setLayout(new GridBagLayout());
add(fade);
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
System.out.println(transparency);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparency));
g2.setColor(getBackground());
g2.fillRect(0, 0, getWidth(), getHeight());
super.paint(g2);
g2.dispose();
}
}
}