Search code examples
javaimageswingjlabeljapplet

JLabel and Image within JApplet - image isn't show up


On the output label shows up, but image doesn't. It does when I remove the whole label section. I don't know if I have to use clearRect method also.

public class Applet1 extends JApplet{

Image img;
JLabel label;

public void init(){

    img = getImage(getDocumentBase(), getParameter("imagePath"));

    label = new JLabel(getParameter("labelText"));
    label.setFont(new Font(getParameter("labelFont"), Font.PLAIN, Integer.parseInt(getParameter("labelSize"))));

    add(label);
    setVisible(true);
}

public void paint(Graphics g){
    g.clearRect(0, 0, 300, 200);
    g.drawImage(img, 0, 0, 300, 200, this);
}

}

Solution

  • Don't override the paint() method of a JApplet.

    Custom painting is done by overriding the paintComponent() method of a JPanel. Don't forget to also invoke super.paintComponent(). Then you add the panel to the applet.

    Finally you would add the label to the panel.

    Also, see How to Make Applets for the proper way to create the applet. It shows how to use the EDT and a better way to load images.