Learning java…why on earth is this image flickering/flashing?

廉价感情. 提交于 2019-12-11 09:41:56

问题


There seem to be a lot of similar problems, but they implement different code...this is just the base code, so I have a feeling I'm doing something very strange/wrong. This is what my code looks like. The gifs are transparent and animated, if that changes things.

import java.awt.*;
import javax.swing.*;
public class NewClass extends JFrame {
    private JLabel label;
    private JButton button;
    private JTextField textfield;
    private ImageIcon image;
    private JLabel label1;
    private ImageIcon imaged;
    private JLabel label2;

    public NewClass (){
        setLayout(new FlowLayout());

        label = new JLabel("Hi, I am a label!");
        add(label);
        image = new ImageIcon(getClass().getResource("sprite15_2_1.gif"));
        label1 = new JLabel(image);
        add(label1);
         imaged = new ImageIcon(getClass().getResource("sprite2_1_1.gif"));
        label2 = new JLabel(imaged);
        add(label2);
        label1.setDoubleBuffered(true);
        label2.setDoubleBuffered(true);
        textfield = new JTextField(15);
        add (textfield);

        button = new JButton("aight");
        add(button);
    }
    public static void main (String args[]){

    NewClass gui = new NewClass();
    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    gui.pack();
    gui.setVisible(true);
    gui.setTitle("Elan Vital");
    }
}

Edited to contain full code. It's just a simple program.

The Flashing GIF (sprite15_2_1.gif) :

sprite_2_1_1.gif shows up perfectly, but the bottom half of sprite15_2_1.gif flickers white. I have no idea what's different I: " . I have double-checked the gif to be sure it's not a problem with the file itself...


回答1:


There were problems with the gif file indeed.

Use any one of the following image instead of the one you posted. Double buffering is not necessary.

The image has been corrected in photoshop. There were some redundant frames which may have been causing the flickering but the surprising fact is the image shows correctly on all image viewers but not in Java. So possibility of a java bug.

The first image is a bit faster, the second one is slower by 0.2s. Use any one.




回答2:


Try enabling double buffering:

label1.setDoubleBuffered(true);
label2.setDoubleBuffered(true);

For more info see the javadoc on Component.setDoubleBuffered.



来源:https://stackoverflow.com/questions/16698821/learning-java-why-on-earth-is-this-image-flickering-flashing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!