簡體   English   中英

java搖擺背景圖像

[英]java swing background image

我正在使用JFrame,我在我的框架上保留了背景圖像。 現在的問題是圖像的大小小於幀的大小,所以我必須在窗口的空白部分再次保持相同的圖像。 如果用戶單擊最大化按鈕,則可能必須在運行時將圖像放在幀的空白區域。 誰能告訴我如何實現這一目標?

這聽起來好像你在談論平鋪與拉伸,雖然不清楚你想要哪種行為。

該計划有兩個例子:

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

你想要像windows桌面的背景圖像,多次使用背景圖像而不是調整它的大小或只是顯示它居中?

您只需要保留圖像一次,然后在paintComponent方法中多次繪制它。

平鋪圖像的另一種方法是使用TexturePaint

public class TexturePanel extends JPanel {

    private TexturePaint paint;

    public TexturePanel(BufferedImage bi) {
        super();
        this.paint = new TexturePaint(bi, new Rectangle(0, 0, bi.getWidth(), bi.getHeight()));
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.setPaint(paint);
        g2.fill(new Rectangle(0, 0, getWidth(), getHeight()));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM