public class DrawPanel extends javax.swing.JPanel { private Image image; /** * Creates new form DrawPanel */ public DrawPanel() { initComponents(); } //定义setImage方法 public void setImage(URL imagePath){ image=Toolkit.getDefaultToolkit().getImage(imagePath); MediaTracker tracker=new MediaTracker(this); tracker.addImage(image,0); try{ tracker.waitForID(0); }catch(InterruptedException exception){ exception.printStackTrace(); } } //下面是重载!!!! public void paintComponent(Graphics g){ super.paintComponent(g);
if(image == null) return; //int imageWidth = image.getWidth(this); //int imageHeight = image.getHeight(this); g.drawImage(image,0,0,null); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" 生成的代码 "> private void initComponents() { org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(0, 400, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(0, 300, Short.MAX_VALUE) ); } }
private Image image;
/**
* Creates new form DrawPanel
*/
public DrawPanel() {
initComponents();
}
//定义setImage方法
public void setImage(URL imagePath){
image=Toolkit.getDefaultToolkit().getImage(imagePath);
MediaTracker tracker=new MediaTracker(this);
tracker.addImage(image,0);
try{
tracker.waitForID(0);
}catch(InterruptedException exception){
exception.printStackTrace();
}
}
//下面是重载!!!!
public void paintComponent(Graphics g){
super.paintComponent(g);
if(image == null) return;
//int imageWidth = image.getWidth(this);
//int imageHeight = image.getHeight(this);
g.drawImage(image,0,0,null);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" 生成的代码 ">
private void initComponents() { org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 300, Short.MAX_VALUE)
);
}
}