[Java]
Package com. han;
Import java. awt. BorderLayout;
Import java. awt. Container;
Import java. awt. Dimension;
Import java. awt. Graphics;
Import java. awt. Graphics2D;
Import java. awt. Image;
Import java. awt. Toolkit;
Import java. awt. event. ComponentAdapter;
Import java. awt. event. ComponentEvent;
Import javax. swing. JButton;
Import javax. swing. JFrame;
Import javax. swing. JPanel;
/**
* The result is:
* <P>
* If you use pack (), use the setPref () method when you want to resize
* Components; If you do not use the Layout Manager, employ the combined
* Methods: setLayout (null) + Components. setBounds ()
*
* @ Author HAN
*
*/
@ SuppressWarnings ("serial ")
Public class JPanelTest extends JFrame {
Static JPanel;
Static JButton button;
Int BgImageWidth;
Int BgImageHeight;
Public JPanelTest (){
// TODO Auto-generated constructor stub
Container c = getContentPane ();
Final Image img = Toolkit. getdefatooltoolkit (). getImage (
JPanelTest. class. getResource ("/images/Luxun.jpg "));
BgImageWidth = img. getWidth (this );
BgImageHeight = img. getHeight (this );
Panel = new JPanel (){
@ Override
Protected void paintComponent (Graphics g ){
Super. paintComponent (g); // paints the component's background, since this component is opaque
Graphics2D g2 = (Graphics2D) g;
G2.drawImage (img, 0, 0, BgImageWidth, BgImageHeight, this );
}
};
C. add (panel, BorderLayout. CENTER );
// Panel. setPreferredSize (new Dimension (200,250 ));
System. out. println (panel. getPreferredSize ());
System. out. println (panel. getSize ());
Button = new JButton ("Test ");
JButton button2 = new JButton ("Button 2 ");
Panel. add (button );
Panel. add (button2 );
AddComponentListener (new ComponentAdapter (){
Public void componentResized (ComponentEvent e ){
System. out. println ("here ");
System. out. println (panel. getSize ());
BgImageWidth = panel. getWidth ();
BgImageHeight = panel. getHeight ();
Panel. repaint ();
}
});
}
/**
* @ Param args
*/
Public static void main (String [] args ){
// TODO Auto-generated method stub
JPanelTest frame = new JPanelTest ();
Frame. pack ();
Frame. setSize (new Dimension (500,500 ));
Frame. setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE );
Frame. setVisible (true );
System. out. println (panel. getSize ());
System. out. println (panel. getPreferredSize ());
}
}