我直接给你一个ImagePanel类,你自己改改。
publicclassImagePanelextendsJPanel{
privatestaticfinallongserialVersionUID=1L;
protectedBufferedImageimage;
protectedRectanglerectangle=newRectangle();
publicImagePanel(){
setLayout(null);
installListeners();
}
privatevoidinstallListeners(){
}
publicvoidpaintComponent(Graphicsg){
super.paintComponent(g);
if(image==null){
return;
}
g.drawImage(image,0,0,null);
if(rectangle.width>=0&&rectangle.height>=0){
Colorc=g.getColor();
g.setColor(Color.RED);
g.drawRect(rectangle.x,rectangle.y,rectangle.width,rectangle.height);
g.setColor(c);
}
}
publicBufferedImagegetImage(){
returnimage;
}
publicvoidsetImage(BufferedImageimage){
this.setImage(image,true);
}
publicvoidsetImage(BufferedImageimage,booleanrepaint){
this.image=image;
if(image!=null){
Dimensionsize=newDimension(image.getWidth(null),image.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
}else{
}
rectangle=newRectangle();
if(repaint)
this.repaint();
}
publicbooleanisDirty(){
returnimage!=null;
}
publicvoidupdateZooe(Rectangler){
this.rectangle=r;
repaint();
}
}
核心代码就是重写paintComponent。再者你的代码习惯不好,布局管理器用的不科学。