1

在我有一个 JButton 之前,我的图像显示正确。现在我已经在我的代码中添加了一个 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);

}

}
4

1 回答 1

3

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

至于解决你的问题,你想达到什么目的?如果您希望组件彼此重叠显示,您可以使用OverlayLayout. 如果您不想要这个,请尝试其他一些布局管理器。

于 2013-07-28T08:52:44.213 回答