Search code examples
javaimageswinguser-interfacerepaint

Problems with repaint in gui


The first time a choose a image, it works just fine. But it does not work when I try to change it, the first image remains on the screen.

label = new JLabel("");
panel_1.add(label); 

btnAddImage = new JButton("Select Image");
btnAddImage.addMouseListener(new MouseAdapter() {
@Override
  public void mouseClicked(MouseEvent arg0) {
  File f = null ;
  fileChooser = new JFileChooser();
  fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
  int value = fileChooser.showOpenDialog(fileChooser);
  if (value == JFileChooser.APPROVE_OPTION)
  {
    f = fileChooser.getSelectedFile();
    if (f.exists())
    {
      inputImage_textField.setText(f.getName());        
      BufferedImage bi = getMyBuffImage();
      label = new JLabel(new ImageIcon(bi));
      label.setBounds(0, 68, 98, 92);
      panel_1.add(label);
      panel_1.repaint();
    }
   }
 }
});

Am I doing something wrong when I repaint or something else is the problem?

Thanks


Solution

  • If you want to replace the existing label, replace

    label = new JLabel(new ImageIcon(bi));
    label.setBounds(0, 68, 98, 92);
    panel_1.add(label);
    panel_1.repaint();
    

    with

    label.setIcon(new ImageIcon(bi));
    label.setBounds(0, 68, 98, 92);
    panel_1.revalidate();
    

    Or if you want to add a second label, just replace

    label = new JLabel(new ImageIcon(bi));
    label.setBounds(0, 68, 98, 92);
    panel_1.add(label);
    panel_1.repaint();
    

    with

    JLabel newLabel = new JLabel(new ImageIcon(bi));
    label.setBounds(0, 68, 98, 92);
    panel_1.add(newLabel);
    panel_1.revalidate();