Java JPanel_Bg设置背景
[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 panel;
static JButton button;
int BgImageWidth;
int BgImageHeight;
public JPanelTest() {
// TODO Auto-generated constructor stub
Container c = getContentPane();
final Image img = Toolkit.getDefaultToolkit().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.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
System.out.println(panel.getSize());
System.out.println(panel.getPreferredSize());
}
}
补充:软件开发 , Java ,