JAVA 图片在方框中不平铺_Java JPanel平铺背景图像

我目前有创建JOptionPane的代码,无论我将其设置为:),它都会将图像平铺到背景中

package test;

import java.awt.*;

import java.awt.image.BufferedImage;

import java.io.*;

import javax.imageio.ImageIO;

import javax.swing.*;

public class TiledImage extends JPanel {

BufferedImage tileImage;

public TiledImage(BufferedImage image) {

tileImage = image;

}

protected void paintComponent(Graphics g) {

int width = getWidth();

int height = getHeight();

for (int x = 0; x < width; x += tileImage.getWidth()) {

for (int y = 0; y < height; y += tileImage.getHeight()) {

g.drawImage(tileImage, x, y, this);

}

}

}

public Dimension getPreferredSize() {

return new Dimension(240, 240);

}

public static void main(String[] args) throws IOException {

BufferedImage image = ImageIO.read(new File("./resource/patterngrey.png"));

TiledImage test = new TiledImage(image);

JOptionPane.showMessageDialog(null, test, "", JOptionPane.PLAIN_MESSAGE);

}

}

我遇到的问题是使用相同的代码将图像添加到JFrame中的JPanel背景

这就是我所拥有的:

package test;

import java.awt.*;

import java.awt.image.BufferedImage;

import java.io.*;

import javax.imageio.ImageIO;

import javax.swing.*;

public class TiledImage extends JPanel {

BufferedImage tileImage;

static JFrame mainFrame = new JFrame("Program Name");

static JPanel userDetailsPanel = new JPanel();

public TiledImage(BufferedImage image) {

tileImage = image;

}

protected void paintComponent(Graphics g) {

int width = getWidth();

int height = getHeight();

for (int x = 0; x < width; x += tileImage.getWidth()) {

for (int y = 0; y < height; y += tileImage.getHeight()) {

g.drawImage(tileImage, x, y, this);

}

}

}

public static void main(String[] args) throws IOException {

mainFrame.setSize(400,400);

mainFrame.setLayout(new BorderLayout());

mainFrame.add(userDetailsPanel, BorderLayout.CENTER);

BufferedImage image = ImageIO.read(new File("./resource/patterngrey.png"));

TiledImage backgroundImage = new TiledImage(image);

// userDetailsPanel.setComponent(backgroundImage); //i know this line is wrong

//but i dont know how to correct it

mainFrame.setVisible(true);

}

}

如果有更好的方法,那么任何和所有的帮助都会受到赞赏,这些代码也会很少.一旦我对背景进行了排序,我需要在背景上添加标签和按钮.

背景需要平铺,因为应用程序将在JFrame中具有几个不同的JPanel,具有不同的图案背景,我想使框架可调整大小

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值