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