gpt4 book ai didi

java - 如何让一个越来越透明最后消失的JPanel呢?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:53:58 25 4
gpt4 key购买 nike

我想制作一个扩展 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();
}

最佳答案

因为 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();
}
}
}

关于java - 如何让一个越来越透明最后消失的JPanel呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14447450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com