gpt4 book ai didi

Java JPanel 平铺背景图像

转载 作者:搜寻专家 更新时间:2023-11-01 04:05:53 25 4
gpt4 key购买 nike

我目前有创建 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,具有不同的图案背景,我想让框架可调整大小

最佳答案

java.awt.TexturePaint 的实例提供了一种方便的方法来平铺 BufferedImage。相关例子可见here .给定一个 TexturePaint,您可以很容易地填充组件的背景,如图所示 here .

    private TexturePaint paint;

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(paint);
g2d.fillRect(0, 0, getWidth(), getHeight());
}

image

关于Java JPanel 平铺背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24746354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com