java Swing 背景图片

标签 java image swing background

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

最佳答案

听起来好像您在谈论平铺与拉伸(stretch),但不清楚您想要哪种行为。

这个程序有两个例子:

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);
        }
    }
}

关于java Swing 背景图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2227423/

相关文章:

java - 测试列表是否包含某些必填项和某些可选项

java - 有没有办法从异步方法绘制到 JPanel 上?

java - java 中的滑动通知栏(a la Firefox)

java - 使用 hibernate 和 java Swing 从 MySQL DB 恢复表

java - Spring 内置的调度器是持久的吗?

java - 如何在 DB2 中插入带有单撇号的值

java - Intellij 依赖问题 - java.lang.NoClassDefFoundError

Python PyQt 像素图更新崩溃

javascript - CSS 中不规则多边形的悬停效果

javascript - 旋转 Canvas 图像,同时保持纵横比