我创建了一个新类CellPanel,它扩展了JPanel(它使用了GridBagLayout())。 JFrame具有GridLayout()和大小640x480。在CellPanel中,我添加了扩展JPanel的类FadeIn。 FadeIn具有淡入和淡出效果,但在这种特殊情况下淡入/淡出的图像非常小,否则它可以正常工作。
Class FadeIn:
public FadeIn(Image image) {
imagem = image;
timer = new Timer(50, this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,alpha));
g.drawImage(imagem,0,0,getWidth(),getHeight(),this);
}
@Override
public void actionPerformed(ActionEvent e) {
if(fade == false)
{
alpha += 0.05f;
if (alpha >1) {
alpha = 1;
fade = true;
}
repaint();
}
else if(fade == true)
{
alpha -= 0.05f;
if (alpha <0) {
alpha = 0;
fade = false;
}
repaint();
}
}
我正在使用这些类的代码:
JFrame dialog = new JFrame();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setSize(640, 480);
dialog.setResizable(false);
dialog.setLocationRelativeTo(null);
dialog.setLayout(new GridLayout(5,5));
cell = new CellPanel(ground.getImage());
cell.setLayout(new GridBagLayout());
iconSolver = new ImageIcon("Resurse/fadingRight.png");
fade = new FadeIn(iconSolver.getImage());
fade.setSize(iconSolver.getIconWidth(), iconSolver.getIconHeight());
fade.setOpaque(false);
cell.add(fade);
cell.setSize(dialog.getWidth()/5,dialog.getWidth()/5);
dialog.getContentPane().add(cell);
dialog.setVisible(true);