2012-09-21 2 views
3

알파 값을 배경색 & 타이머에 추가하여 패널에서 페이드 아웃 할 수 있다는 것을 알고 있습니다. 하지만 하위 구성 요소 (예 : JLabel)가있는 패널을 페이드 인하려면 어떻게해야합니까?JPanel 및 하위 항목을 어떻게 페이드 인 할 수 있습니까?

편집

_fadeTimer = new Timer(40, new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      if (_alpha == 255) { 
       _fadeTimer.stop(); 
      } else { 
       pnl_hint.setBackground(new Color(
         bgColor.getRed(), 
         bgColor.getGreen(), 
         bgColor.getBlue(), 
         (_alpha += 1))); 

       pnl_hint.updateUI(); 
      } 
     } 
    }); 
    _fadeTimer.start(); 

답변

5

또 다른 옵션은 패널의 스크린 샷을 캡처 한 다음 증가하는 알파 합성물로 페인트 할 수있게하는 것입니다.

여기에 (내가 확실하지 오전하지만이 정말 깨끗합니다) 그 작은 데모입니다 :

import java.awt.AlphaComposite; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.image.BufferedImage; 
import java.net.MalformedURLException; 
import java.net.URL; 

import javax.swing.ImageIcon; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 
import javax.swing.SwingUtilities; 
import javax.swing.Timer; 

public class TestFading { 

    private static class FadingPanel extends JPanel { 
     private BufferedImage buffer; 
     private boolean isFading = false; 
     private long start; 
     private float alpha = 1.0f; 

     @Override 
     public void paint(Graphics g) { 
      if (isFading) {// During fading, we prevent child components from being painted 
       g.clearRect(0, 0, getWidth(), getHeight()); 
       ((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)); 
       g.drawImage(buffer, 0, 0, this);// We only draw an image of them with an alpha 
      } else { 
       super.paint(g); 
      } 
     } 

     public void fade(int time) { 
      start = System.currentTimeMillis(); 
      buffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB); 
      this.print(buffer.getGraphics());// Draw the current components on the buffer 
      isFading = true; 
      final int timeInMillis = time * 1000; 
      final Timer t = new Timer(50, null); 
      t.addActionListener(new ActionListener() { 

       @Override 
       public void actionPerformed(ActionEvent e) { 
        long elapsed = System.currentTimeMillis() - start; 
        if (elapsed > timeInMillis) { 
         start = 0; 
         isFading = false; 
         buffer = null; 
         repaint(); 
         t.stop(); 
        } else { 
         alpha = 1.0f - (float) elapsed/timeInMillis; 
         repaint(); 
        } 
       } 
      }); 
      t.start(); 
     } 
    } 

    protected void initUI() throws MalformedURLException { 
     JFrame frame = new JFrame(TestFading.class.getSimpleName()); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     final FadingPanel panel = new FadingPanel(); 
     JTextField textfield = new JTextField(60); 
     JLabel image = new JLabel(new ImageIcon(new URL("http://helios.gsfc.nasa.gov/image_mag_stamp.jpg"))); 
     JButton button = new JButton("Fade"); 
     button.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       // I use an invoke later to allow the button to release itself 
       SwingUtilities.invokeLater(new Runnable() { 

        @Override 
        public void run() { 
         panel.fade(5);// Fade the panel in 5s. 
        } 
       }); 
      } 
     }); 
     panel.add(textfield); 
     panel.add(image); 
     panel.add(button); 
     frame.add(panel); 
     frame.setSize(400, 300); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       try { 
        new TestFading().initUI(); 
       } catch (MalformedURLException e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 

} 
+0

내 JPanel은 불투명하지 않고 시안 색 배경색을 가졌지 만 '페이드'를 호출하면 다시 불투명 해졌습니다. 배경색을 잃어 버렸습니다. 마지막으로'얼굴 '이 끝나면 패널이 복원되었습니다. –

3

안된 의사 코드. 대신 배경 재정을 paintChildren 방법을 설정

public void fade(Container c) { 
    Component[] children = c.getComponents(); 
    for (Component component : components) { 
     // do fade thing with component 
     if (component instanceOf Container) { 
      fade((Container)component); 
     } 
    } 
} 
+0

이 참이 재귀 적 방법을 사용하는 논리 ...하지만 난 이미지 아이콘 내 패널에서의 JLabel을 가지고 ... 내가 panel.setBackground처럼 투명하게 만들 수 없습니다 (새로운 색상 (빨강, 녹색 , 푸른 색, 알파) –

+1

데이터 드리블에 대한 호의적 인 호소. 우리가 단편에서 단서를 얻을 수있는 '10 부분'문제입니까? 더 빨리 도움을 받으려면 [SSCCE] (http://sscce.org /). –

+0

예제 코드는 위에 게시했습니다! –

3

. super.paintChildren()으로 전화 한 다음 구성 요소의 rect를 반투명 색상으로 채 웁니다.

+0

반투명 색상으로 구성 요소의 rect를 채우는 방법에 대한 간단한 코드 예제를 제공 할 수 있습니까? pls : –

0

나는 이미지와 JLabel를 추가하고 false로 불투명 JPanel을 설정!

overriden paintComponent 메소드에서 super.paintComponent() 호출 전에 알파로 AlphaComposite를 설정했습니다.

How do I fade an image in swing?

관련 문제