Chris
Chris

Reputation: 9

Image is not displaying in JFrame

My image was displaying properly before I had a JButton on top of it. Now that I have added a JButton to my code, my image does not display. In the ActionPerformed method I am telling the button to setVisbible(false). When I click the button, it disapears and all that is behind it is the background.

public class Main extends JFrame implements ActionListener {

public static void main(String[] args) {
    Main main = new Main();

}

ImageIcon GIF = new ImageIcon("src/Zombie Steve gif.gif");
JButton button = new JButton("Click me!");
JLabel Label = new JLabel(GIF);

public Main() {

    button.addActionListener(this);

    Label.setHorizontalAlignment(0);

    JFrame Frame = new JFrame("zombieSteveGIF");
    Frame.setSize(650, 650);
    Frame.setVisible(true);
    Frame.add(Label);
    Frame.add(button);
    Frame.setDefaultCloseOperation(EXIT_ON_CLOSE);

    while (true) {
        Frame.getContentPane().setBackground(Color.BLUE);
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Frame.getContentPane().setBackground(Color.GREEN);
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Frame.getContentPane().setBackground(Color.RED);
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

public void actionPerformed(ActionEvent e) {
    button.setVisible(false);

}

}

Upvotes: 1

Views: 117

Answers (1)

tbodt
tbodt

Reputation: 16997

Your problem is that you have a BorderLayout (the default for JFrames), and you are adding two components in the same position. The default is BorderLayout.CENTER, and by adding two components with just the default constraints, the first one is removed and the second put in its place.

As for fixing your problem, what do you want to achieve? If you want the components to show on top of one another, you can use the OverlayLayout. If you don't want this, try some other layout manager.

Upvotes: 3

Related Questions