问题
I am working on a project for detecting faces from an input image. I am using opencv with Java. The problem which I'm facing is as below
- The faces that are detected are to be placed on a
JLabel
ssetIcon
method. - First time it places the faces, but for the next image, the previous faces are not cleared.
Following code that I tried to add and remove faces
1) Adding faces:
jFaceLabel is JLabel array initialized to size 100 jpDetectedImage is a JPanel which contains the JLabels (faces)
jFaceLabel = new JLabel[100];
for(int index=0;index<ImageHandler.noOfDetections;index++){
jFaceLabel[index] = new JLabel();
jFaceLabel[index].setIcon(new ImageIcon("C://Users//Public//Pictures//Sample Pictures//TestPics//temp//"+index+".jpg"));
//jFaceLabel[index].setIcon(face);
int x = this.jpDetectedImage.getX() + (index%2) * 64 + 10 * ((index%2)+1);
int y = this.jpDetectedImage.getY() + (index/2) * 64 + 10 * ((index/2)+1);
jFaceLabel[index].setBounds(x, y, 64, 64);
this.jpDetectedImage.add(jFaceLabel[index]);
if(index>8 && (index%2==0)){
this.jpDetectedImage.setPreferredSize(new Dimension(
this.jpDetectedImage.getPreferredSize().width,
this.jpDetectedImage.getPreferredSize().height + 74
));
}
System.out.println("Placed : "+tempPath+"//"+index+".jpg");
}
jpDetectedImage.repaint();
2) Removing faces:
for(int j=0;j<ImageHandler.noOfDetections;j++){
jFaceLabel[j].getParent().remove(jFaceLabel[j]);
}
this.jpDetectedImage.repaint();
The problem is, the first time every faces gets displayed on the JLabels but successive detection of faces, result in overlapping of the old faces. The detected faces are stored at a physical path and are deleted when a image for detection is loaded.
I require, is the removal of the jFaceLabel array from jpDetectedImage panel and a new memory allocation for every successive detection phase.
How to remove the JLabels from JPanel dynamically and add them again with a new ImageIcon?
回答1:
The better way to do this is to update the label's icon in place using setIcon()
, as shown here.
A less flexible alternative is to remove the component and validate the container, as shown here.
来源:https://stackoverflow.com/questions/23978887/displaying-detected-faces-on-a-jpanel