|
50鱼币
求问:Java的GUI怎么让图片设置大小放在指定的位置
我在做GUI设计的时候,想让图片放到Jpanel中,在将这个Jpanel放到Jframe中,但是就是一直实现不了
要不是图片没加载,要不就是图片加载完,缩成一点点
直接放到Jframe又是全图的
代码如下:
LoginFrame 主类:
- package storeFrame;
- import java.awt.Color;
- import java.awt.Image;
- import java.net.URL;
- import javax.swing.ImageIcon;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JPanel;
- import StorePanel.BackgroundPanel;
- public class LoginFrame extends JFrame{
- private URL url = null;// 声明图片的URL
- private Image image=null;// 声明图像对象
- private BackgroundPanel bgPanel = null;
-
-
- public LoginFrame() {
- super("aaaa");
- JPanel pane = new JPanel();
- this.add(getPanel());
- this.setSize(700,500);
- this.setLocation(300, 200);
- // this.setUndecorated(true);
- this.setVisible(true);
- }
-
- private BackgroundPanel getPanel() {
- if(bgPanel==null) {
- url = LoginFrame.class.getResource("/img/flowerBook.jpg");
- image = new ImageIcon(url).getImage();
- bgPanel = new BackgroundPanel(image);
- }
- return bgPanel;
- }
- public static void main(String[] args) {
- new LoginFrame();
- }
- }
复制代码
BackgroundPanel 类
- package StorePanel;
- import java.awt.Graphics;
- import java.awt.Graphics2D;
- import java.awt.Image;
- import javax.swing.JPanel;
- /**
- * 可以添加背景图片的面板
- */
- public class BackgroundPanel extends JPanel {
- private static final long serialVersionUID = 1L;// 序列化编号
- private Image image; // 定义图像对象
- /**
- * 面板构造方法
- *
- * @param image
- * -背景图片对象
- */
- public BackgroundPanel(Image image) {
- super(); // 调用超类的构造方法
- this.image = image; // 为图像对象赋值
- initialize();
- }
- /**
- * 重写绘制组件方法
- */
- protected void paintComponent(Graphics g) {
- super.paintComponent(g); // 调用父类的方法
- Graphics2D g2 = (Graphics2D) g; // 创建Graphics2D对象
- if (image != null) {
- int width = getWidth(); // 获得面板的宽度
- int height = getHeight(); // 获得面板的高度
- // 绘制图像
- g2.drawImage(image, 0, 0, width, height, this);
- }
- }
- /**
- * 初始化面板大小
- */
- private void initialize() {
- this.setSize(300, 200);
- }
- }
复制代码
我想让Jpanel能像前端div一样设置大小位置,放到指定地方,不知道行不行
谢谢各位
加一段代码
- setLayout(null);//使用绝对布局
- JPanel p1 = getPanel();
- p1.setBounds(x,y,width,height);
- add(p1);
- //x和y是坐标,后面是尺寸
复制代码
|
|