简体   繁体   中英

Java - How to make the images disappear

Hi I want to make my JPanel disappear so I wrote these lines of code

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

That only made the JComponents and JButtons disappear. I would like to make the images that I have displayed with the paint method disappear also. If I do setVisible(false), then I cannot add another JPanel behind it.

This is my class:

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

Thanks in advance.

First, don't call updateUI , it's related to the Look and Feel and not (directly) to updating your components.

If you have provided a custom paint routine within in your panel, then you need away to stop it from painting the images (without preventing it from painting it's own content). removeXxx will remove child components that you have previously added to the container.

A little more code would be useful

UPDATE

Fisrt, the images your painting aren't components of you container, they are been "stamped", you need some way to tell the component not to the paint the images

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

Now, this will stop the images from been painted.

If, however, you no longer want to use the component (ie, you want to remove it from the screen so you can place a new component on the screen in its place), you need to remove this component from it's parent, which Code-Guru has suggested (so I won't steal his answer ;))

UPDATE

Okay, you had a kernel of an idea but either didn't quite know how to implement it or decided to discard it.

Basically, from the looks of your code, you were either trying to, or had, implement a CardLayout , unfortunately, you kind of got the wrong idea with it.

With CardLayout , you need to "controller", a component that is responsible for switching the screens...

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

Then you have your menu and game screens...

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...

菜单画面

And when you click start...the game screen...

在此处输入图片说明

Now this is an EXAMPLE. Please try and take the time to understand what it going on in the code before you march ahead and implement it. I used by own images, you'll need to get your own..

There are several ways to stop your JPanel from "appearing" depending on exactly what you want to accomplish. One was it to to call setOpaque(false); . I'm not entirely sure how this affects custom painting, though.

Another posibility is

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

A third posibility is to add a flag in your class which is set when you click on a JLabel (or better yet a JButton -- see comments below). Then in your paintComponent() method you can check the flag and draw accordingly.

Note:

You are incorrectly using a JLabel and mouse events to respond to user input. Typically in a Swing application, we use JButtons and ActionListeners to accomplish what you are trying to do here. One advantage of this is that you only have to implement one method called onActionPerformed() and don't need to worry about adding all the mouse event handlers that you don't want to even respond to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM