1

I created a new class CellPanel which expands JPanel (it uses GridBagLayout()). The JFrame has GridLayout() and size 640x480. In CellPanel I add class FadeIn which expands JPanel. FadeIn has this fade in and out effect but the image that is fading in/out is very small in this particular case, otherwise it works fine.

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

The code where I'm using these classes:

    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); 
  • 2
    The layout manager will be responsible for determining the size of the components, so call `setSize` on them is pointless. What is `CellPanel`? Your `FadeIn` panel should be providing sizing hints via the `getPreferredSize` method. Consider providing a [runnable example](https://stackoverflow.com/help/mcve) which demonstrates your problem. This is not a code dump, but an example of what you are doing which highlights the problem you are having. This will result in less confusion and better responses – MadProgrammer Apr 04 '15 at 22:15
  • setPreferredSize() solved the issue! Thank you! –  Apr 04 '15 at 22:21
  • 2
    [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi) – MadProgrammer Apr 04 '15 at 22:37

0 Answers0