Java - 如何使图像消失

时间:2012-09-05 23:45:36

标签: java swing awt visibility layout-manager

您好我想让我的JPanel消失所以我写了这些代码行

removeAll();
updateUI();
revalidate();

这只会使JComponents和JButtons消失。我想让我用paint方法显示的图像也消失了。如果我执行setVisible(false),那么我就无法在其后添加另一个JPanel。

这是我的班级:

package screens;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
public class menuScreen extends JPanel implements MouseListener{
    private static final long serialVersionUID = 1L;

//-------------VARIABLES---------------//
    Image wallpaper = (Image)Toolkit.getDefaultToolkit().getImage(getClass().getResource("images/wallpaper.jpg"));
    Image title_text = (Image)Toolkit.getDefaultToolkit().getImage(getClass().getResource("images/title-text.png"));
    ImageIcon startGameimg = new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("images/startGame.png")));
    ImageIcon optionsimg = new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("images/options.png")));
    //JButton start = new JButton(basketball);
    JLabel options = new JLabel(optionsimg);
    JLabel startGame =  new JLabel(startGameimg);
    gameScreen gS = new gameScreen();
    CardLayout scenechange = new CardLayout();
    JPanel scenechange1 = new JPanel (scenechange);

//-------------PAINT FUNCTION----------//
    public void paintComponent(Graphics g){
    g.drawImage(wallpaper,0,0,this);
    g.drawImage(title_text,0,0,this);
    //g.drawImage(basketball1,110,180,this);

    }

//-------------CONSTRUCTOR-------------//
    public menuScreen(){

    scenechange.addLayoutComponent(this,"menuScreen");
    scenechange.addLayoutComponent(gS,"gameScreen");
    //scenechange.show(this,"menuScreen");

    this.setLayout(null);
    this.add(options);
    this.add(startGame);
    startGame.setBounds(110,180,110,110);
    options.setBounds(110,300,110,110);
    startGame.addMouseListener(this);
    options.addMouseListener(this);


    }


    public void mouseClicked(MouseEvent e) {
    if(e.getSource() ==  (startGame)){

        removeAll();

        revalidate();
        add(gS);
    }

    if(e.getSource() == (options)){
        setVisible(false);
    }


    }


    public void mousePressed(MouseEvent e) {
    // TODO Auto-generated method stub

    }


    public void mouseReleased(MouseEvent e) {
    // TODO Auto-generated method stub

    }


    public void mouseEntered(MouseEvent e) {
    // TODO Auto-generated method stub

    }


    public void mouseExited(MouseEvent e) {
    // TODO Auto-generated method stub

    }


}//END OF CLASS startingScreen

提前致谢。

2 个答案:

答案 0 :(得分:2)

首先,不要致电updateUI,它与外观相关,而不是(直接)更新您的组件。

如果您在面板中提供了自定义绘图例程,则需要将其停止绘制图像(不会阻止它绘制自己的内容)。 removeXxx将删除您之前添加到容器中的子组件。

多一点代码会很有用

<强>更新

Fisrt,你的画作不是你容器的组成部分的图像,它们被“盖章”,你需要一些方法告诉组件不要画画像

public void paintComponent(Graphics g){
    super.paintComponent(g); // this is super important
    if (paintImages){ // you need to define and set this flag
        g.drawImage(wallpaper,0,0,this);
        g.drawImage(title_text,0,0,this);
    }
}

现在,这将停止绘制图像。

但是,如果您不再想要使用该组件(即,您希望将其从屏幕上移除,以便可以在屏幕上放置新组件),则需要从其父级中删除该组件Code-Guru建议的(所以我不会窃取他的答案;))

<强>更新

好的,你有一个想法的内核,但要么不知道如何实现它,要么决定丢弃它。

基本上,从您的代码的外观来看,您要么尝试还是已经实现了CardLayout,不幸的是,您对此有了错误的想法。

使用CardLayout,你需要“控制器”,一个负责切换屏幕的组件......

public class ScreenController extends JPanel {

    private static final long serialVersionUID = 1L;
//-------------VARIABLES---------------//
    MenuScreen ms = new MenuScreen();
    GameScreen gs = new GameScreen();
    CardLayout sceneChange;

//-------------CONSTRUCTOR-------------//
    public ScreenController() {

        sceneChange = new CardLayout();

        this.setLayout(sceneChange);
        add(ms, "menuScreen");
        add(gs, "gameScreen");

        sceneChange.show(this, "menuScreen");

        ms.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getActionCommand().equalsIgnoreCase("startgame")) {
                    sceneChange.show(ScreenController.this, "gameScreen");
                }
            }
        });
    }

}//END OF CLASS startingScreen

然后你有菜单和游戏画面......

public class MenuScreen extends JPanel implements MouseListener {

    private static final long serialVersionUID = 1L;
//-------------VARIABLES---------------//
    //JButton start = new JButton(basketball);
    JLabel options = new JLabel("Options");
    JLabel startGame = new JLabel(" >> Start << ");
//    gameScreen gS = new gameScreen();
    BufferedImage wallpaper;

//-------------PAINT FUNCTION----------//
    @Override
    public void paintComponent(Graphics g) {
        System.out.println("paint");
        super.paintComponent(g);
        if (wallpaper != null) {
            g.drawImage(wallpaper, 0, 0, this);
        }
    }

//-------------CONSTRUCTOR-------------//
    public MenuScreen() {

        // Please handle your exceptions better
        try {
            wallpaper = ImageIO.read(getClass().getResource("/Menu.png"));
            setPreferredSize(new Dimension(wallpaper.getWidth(), wallpaper.getHeight()));
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        setLayout(new GridBagLayout());

        Cursor cusor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
        options.setCursor(cusor);
        startGame.setCursor(cusor);

        Font font = UIManager.getFont("Label.font").deriveFont(Font.BOLD, 48);
        options.setFont(font);
        startGame.setFont(font);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;

        this.add(options, gbc);
        gbc.gridy++;
        this.add(startGame, gbc);
        startGame.addMouseListener(this);
        options.addMouseListener(this);
    }

    public void mouseClicked(MouseEvent e) {
        if (e.getSource() == (startGame)) {
            fireActionPerformed("startGame");
        }
        if (e.getSource() == (options)) {
            fireActionPerformed("gameOptions");
        }
    }

    public void mousePressed(MouseEvent e) {
    }

    public void mouseReleased(MouseEvent e) {
    }

    public void mouseEntered(MouseEvent e) {
    }

    public void mouseExited(MouseEvent e) {
    }

    public void addActionListener(ActionListener listener) {
        listenerList.add(ActionListener.class, listener);
    }

    public void removeActionListener(ActionListener listener) {
        listenerList.remove(ActionListener.class, listener);
    }

    protected void fireActionPerformed(String cmd) {
        ActionListener[] listeners = listenerList.getListeners(ActionListener.class);
        if (listeners != null && listeners.length > 0) {
            ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, cmd);
            for (ActionListener listener : listeners) {
                listener.actionPerformed(evt);
            }
        }
    }
}

菜单屏幕......

Menu Screen

当你点击开始......游戏画面......

enter image description here

现在这是一个例子。在您继续前进并实施它之前,请尝试花时间了解代码中的内容。我用自己的图像,你需要自己的..

答案 1 :(得分:1)

有几种方法可以阻止JPanel“出现”,具体取决于您想要完成的内容。一个是打电话给setOpaque(false);。不过,我不完全确定这会如何影响自定义绘画。

另一个可能性是

Container parent = getParent().remove(this);
parent.validate();

第三个可能性是在你的类中添加一个标志,当你点击一个JLabel(或者更好的JButton时看到它) - 见下面的评论。然后在paintComponent()方法中,您可以检查标记并相应地绘制。

注意:

您错误地使用JLabel和鼠标事件来响应用户输入。通常在Swing应用程序中,我们使用JButtons和ActionListeners来完成您在此处尝试执行的操作。这样做的一个优点是您只需要实现一个名为onActionPerformed()的方法,而不必担心添加您不想响应的所有鼠标事件处理程序。