Reputation: 1706
I want to make a panel which extends JPanel
and when it's going to be visible, it starts to get more transparent and more transparent and finally gets disappeared. what is the problem of my code?
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.01f;
if (transparency < 0.0f)
{
timer.stop();
}
repaint();
}
};
timer = new Timer(100, action);
timer.start();
}
@Override
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g.create();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparency));
super.paint(g2);
g2.dispose();
}
}
Upvotes: 3
Views: 202
Reputation: 347184
Because the BallonPanel
is opaque, the repaint manager isn't bothering to paint underneath it. This is an optimization of the paint process, why paint that which doesn't need to be painted.
You need to "persuade" the repaint manger to paint underneath your component, while still painting its background.
Set the BallonPanel
to transparent (setOpaque(false)
) and update the paint
method to fill the background.
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();
}
}
}
Upvotes: 3