Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 图像未显示在JFrame中_Java_Swing_Jframe_Jbutton_Actionlistener - Fatal编程技术网

Java 图像未显示在JFrame中

Java 图像未显示在JFrame中,java,swing,jframe,jbutton,actionlistener,Java,Swing,Jframe,Jbutton,Actionlistener,在我有一个按钮在上面之前,我的图像已经正确显示了。现在我已经在代码中添加了一个JButton,我的图像就不会显示了。在ActionPerformed方法中,我告诉按钮setVisbible(false)。当我点击按钮时,它消失了,它后面的就是背景 public class Main extends JFrame implements ActionListener { public static void main(String[] args) { Main main = new Mai

在我有一个按钮在上面之前,我的图像已经正确显示了。现在我已经在代码中添加了一个JButton,我的图像就不会显示了。在ActionPerformed方法中,我告诉按钮
setVisbible(false)
。当我点击按钮时,它消失了,它后面的就是背景

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

}

}

您的问题是您有一个
BorderLayout
(默认为
JFrame
s),并且在同一位置添加了两个组件。默认设置为
BorderLayout.CENTER
,通过添加两个仅具有默认约束的组件,第一个组件将被删除,第二个组件将被放置到位


至于解决您的问题,您希望实现什么目标?如果希望组件显示在彼此的顶部,可以使用
OverlayLayout
。如果您不想这样做,请尝试其他布局管理器。

是否尝试设置
不透明(false)
?对于button@MaximShoustin我试过了,不幸的是仍然不会显示我的图像,只显示背景。你不能在BorderLayout的中心位置有两个不同的组件。阅读@jbnize,谢谢!我发现了哪里出了问题,现在我已经开始工作了:)鼓励回答你自己的问题。