-1
我希望將圖像淡入到作爲卡布局一部分的面板中。當我在程序中的某個位置時,此面板將顯示在頂部,然後我希望圖像以淡入效果加載。 這是一個很大的項目,所以我只會粘貼相關的代碼。在jPanel頂部的圖像中淡入淡出
我有一個GUI類,其中包含JFrame中,所有的jPanels等。當被觸發某些事件,運行此代碼:
cardMain.show(pMain, "cLeprechaun");
FadeIn.run(pLeprechaun);
它加載了正確的面板,然後運行在一個靜態方法FadeIn類,它應該將圖像添加到面板pLeprechaun。
這裏是淡入類:
import java.awt.AlphaComposite;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class FadeIn extends JPanel implements ActionListener {
Image imagem;
Timer timer;
private float alpha = 0f;
public FadeIn() {
imagem = new ImageIcon("darkforest.jpg").getImage();
timer = new Timer(100, this);
timer.start();
}
// here you define alpha 0f to 1f
public FadeIn(float alpha) {
imagem = new ImageIcon("darkforest.jpg").getImage();
this.alpha = alpha;
}
@Override
public void paintComponent(Graphics g) {
System.out.println("paint");
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
alpha));
g2d.drawImage(imagem, 0, 0, null);
}
public static void run(JPanel jPanel) {
jPanel.add(new FadeIn());
}
public void actionPerformed(ActionEvent e) {
alpha += 0.05f;
if (alpha >1) {
alpha = 1;
timer.stop();
}
repaint();
}
}
什麼也沒有發生,沒有圖像顯示在面板上。只是嘗試一下,而不是jPanel.add(新的FadeIn());我也試圖創建一個新的jFrame並添加一個新的FadeIn,然後它就可以工作。當然,不是在jPanel上繪製圖像,而是在主圖像的頂部彈出一個新的jFrame,圖像很好地淡入。但這不是我想要發生的事情。
有沒有辦法解決這個問題?
*「'imagem = new ImageIcon(」darkforest。 jpg「)。getImage();'」* 1)應用程序資源在部署時將成爲嵌入式資源,所以現在開始訪問它們是明智的。 [tag:embedded-resource]必須通過URL而不是文件訪問。請參閱[信息。頁面爲嵌入式資源](http://stackoverflow.com/tags/embedded-resource/info)如何形成的URL。 2)獲取圖像的一種方法是通過[本問答](http://stackoverflow.com/q/19209650/418556)中的圖像進行熱鏈接。 –
一般提示:爲了儘快提供更好的幫助,請發佈[MCVE]或[簡短,獨立,正確的示例](http://www.sscce.org/)。 –