How to change image in JPanel without using new JFrame (Repaint () doesn't work!)

People on the Internet!

I am working on a food program for school.

// not relevant information, only for lulz: // The school offered a game, I did not;) this is a game // http://sotallytober.com/games/verbal/mexican/

Anyway, I drew the image in JPanel using the following code (this is a class that extends JPanel)

public class iconPanel extends JPanel {

ImageIcon image;
Image pic;
public iconPanel(String startScreenImage) {
      image = new ImageIcon(startScreenImage);
      pic = image.getImage();
      this.setBackground(new Color(0, true));
}

@Override

public void paintComponent(Graphics g) {
    //Paint background first
    g.drawImage (pic, 0, 0, getWidth (), getHeight (), this);
}

Now in my other class, where I have the layout and all the components, I declare my JPanels on top as follows:

private JPanel pnDrinkPlayerBW;

Then, in a method of the same class called MakeComponents, I installed JPanel for:

pnDrinkPlayerBW = new iconPanel("img/glass.jpg");
pnDrinkPlayerBW.setPreferredSize(new Dimension(183,61));

Panel, , makeLayout() ( , , , , )

, , glass.jpg , , beerGlass0.png, actionlistener actionEvents() :

pnDrinkPlayerBW = new iconPanel("img/beerGlass.png");
pnDrinkPlayerBW.setPreferredSize(new Dimension(183,61));
pnDrinkPlayerBW.repaint();

, :

public SpelScreen(){
    makeComponents();
    makeLayout();
    actionEvents();
} // note : this is'nt the full constructor, just the call for the methods I talked          about, SpelScreen extends JFrame..

, SpelScreen iconPanel , spelscreen.

Java, , :)

!

+4
1

-, super.paintComponent paintComponent. paintComponent protected not public

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(..);
} 

-, , iconPanel . , , .

setter pic, repaint(); .

public void setPic(Image pic) {
    this.pic = pic;
    repaint();
}

setPic , iconPanel.

iconPanel panel = new iconPanel("...");
... // then in some listener
public void actionPerformed(ActionEvent e) {
    Image pic = null;
    try {
        pic = ImageIO.read(...);
        panel.setPic(pic);
    } catch ...
}

- , iconPanel. , . -

Image[] images = new Image[5];
int imageIndex = 0;
// fill the array with images

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(images[imageIndex], ...);
}

imageIndex repaint()


Java. , .. iconPaneliconPanel


ImageIcon

public void setImage(ImageIcon img) {
    pic = img.getImage();
    repaint();
}
+7

Source: https://habr.com/ru/post/1530216/


All Articles