gpt4 book ai didi

java - 如何在 JPanel 上显示图像作为背景

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:18:09 26 4
gpt4 key购买 nike

当我根据 JPanel 的大小重新缩放图像时,我在 JPanel 上显示图像时遇到问题。图像没有出现。

   public class createGUII extends JFrame{
String [] background = {"c1.jpg","c2.jpg","c3.jpg","c4.jpg"};
ArrayList<String> bgPicturesFiles = new ArrayList<String>(Arrays.asList(background));


JPanel panel;
ImagePanel imgBg;

public createGUII(){
GridBagLayout m = new GridBagLayout();
Container c = getContentPane();
c.setLayout (m);
GridBagConstraints con = new GridBagConstraints();

//Panel for background
panel = new JPanel();
panel.setSize(600, 600);
con = new GridBagConstraints();
con.anchor=GridBagConstraints.CENTER;
con.gridy = 1; con.gridx = 0;
con.gridwidth = 1; con.gridheight = 1;
m.setConstraints(panel, con);
c.add(panel);

//randomized the image files
Random r = new Random();
int random = r.nextInt(bgPicturesFiles.size());

//rescale the image according to the size of the JPanel
imgBg = new ImagePanel(new ImageIcon(bgPicturesFiles.get(random)).getImage().getScaledInstance(panel.getHeight(), panel.getWidth(),Image.SCALE_SMOOTH));
panel.add(imgBg);

setResizable(false);
setVisible(true);
setExtendedState(getExtendedState()|JFrame.MAXIMIZED_BOTH);

}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new createGUII();
}
});
}
}



class ImagePanel extends JPanel {
private Image img;

public ImagePanel(String img) {
this(new ImageIcon(img).getImage());
}

public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null);
}

public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}

最佳答案

看看这个:JPanel background image , JPanel with background image, with other panels overlayed

第二个链接提到您必须为缩放做一些自定义绘画。这是个问题。我不会在 paintComponent 方法中每次都缩放图像,但如果自上次调用以来宽度和高度已更改,则一次缩放图像,在这种情况下,重新创建包含图像的 BufferedImage在调用父类(super class) paintComponent 之前,你每次都将其 blit,按比例放大到合适的大小(使用类似 Image scaling does not work when original image height & width is smaller the scaling height & width 的东西)。我可以看到一个问题,当您调用父类(super class) paintComponent 方法时,它可能会尝试用一种颜色填充面板,但您必须进行试验。

关于java - 如何在 JPanel 上显示图像作为背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4170463/

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