我想创建一个扩展JPanel
的面板,当它可见时,它开始变得更透明,更透明,最终消失。我的代码有什么问题?
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();
}
}
答案 0 :(得分:3)
因为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();
}
}
}