public class LoginPanel extends JPanel {
protected ImageIcon icon;//protected的访问权限是同一个包的类即可访问它
public int width,height;
public LoginPanel(){
super();//调用父类的构造方法,此处可以不显示调用,系统会自动隐式调用
icon=new ImageIcon("res/login.jpg");
width=icon.getIconWidth();
height=icon.getIconHeight();
setSize(width,height);//调用继承自父类JPanel中 的setSize()方法设置面板的大小因为是继承来的是自己的了所以在类内可以不用实例对象去调用
//this.setSize(width,height);
}
//想要将这张图片作为背景图片,是不能直接使用add()方法添加该icon对象的;在LoginPanel类中重写paintComponent()方法,并在该方法中调用Graphics类的drawImage()方法绘制该图片
//重写paintComponent()方法
protected void paintComponent(Graphics g){
super.paintComponent(g);//调用父类的paintComponent()方法
Image img = icon.getImage();
g.drawImage(img,100,100,this);//在当前面板中绘制该Image文件 img;this参数表示图片绘制在哪里
System.out.println("执行了paintComponent()方法");
}
为什么在主类中使用new LoginPanel()实现一个实例对象时,函数会执行重写的paintComponent(Graphics g)方法(输出了执行了paintComponent()方法);原则上这个方法LoginPanel中的实例方法,,在实例化类的时候不应该会执行的啊? 请问为什么这里会被执行,或者说实例化 对象时类中的哪些部分会被执行哪些不被执行,求大神帮忙总结一下
附测试用的主函数代码
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame jf = new JFrame();
jf.add(new LoginPanel());
jf.setVisible(true);
jf.setSize(800,800);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}