java摇摆背景图像

Nil*_*esh 5 java swing background image

我正在使用JFrame,我在我的框架上保留了背景图像.现在的问题是图像的大小小于帧的大小,所以我必须在窗口的空白部分再次保持相同的图像.如果用户单击最大化按钮,则可能必须在运行时将图像放在帧的空白区域.谁能告诉我如何实现这一目标?

fin*_*nnw 12

这听起来好像你在谈论平铺与拉伸,虽然不清楚你想要哪种行为.

该计划有两个例子:

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
    public static void main(String[] args) throws IOException {
        final Image image = ImageIO.read(new URL("http://sstatic.net/so/img/logo.png"));
        final JFrame frame = new JFrame();
        frame.add(new ImagePanel(image));
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

@SuppressWarnings("serial")
class ImagePanel extends JPanel {
    private Image image;
    private boolean tile;

    ImagePanel(Image image) {
        this.image = image;
        this.tile = false;
        final JCheckBox checkBox = new JCheckBox();
        checkBox.setAction(new AbstractAction("Tile") {
            public void actionPerformed(ActionEvent e) {
                tile = checkBox.isSelected();
                repaint();
            }
        });
        add(checkBox, BorderLayout.SOUTH);
    };

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (tile) {
            int iw = image.getWidth(this);
            int ih = image.getHeight(this);
            if (iw > 0 && ih > 0) {
                for (int x = 0; x < getWidth(); x += iw) {
                    for (int y = 0; y < getHeight(); y += ih) {
                        g.drawImage(image, x, y, iw, ih, this);
                    }
                }
            }
        } else {
            g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Tob*_*lte 1

当多次使用背景图像而不是调整其大小或仅将其居中显示时,您想要类似 Windows 桌面的背景图像吗?

您只需保留图像一次,然后在 PaintComponent 方法中多次绘制它。