gpt4 book ai didi

java - 如何在不使用 main 方法或调用其他方法的情况下设置 contentPane?

转载 作者:行者123 更新时间:2023-12-01 13:52:44 24 4
gpt4 key购买 nike

据我了解,以下内容设置了 contentPane 的背景颜色。如何将图片设置为背景?

我已经尝试过这些:

但它们都不起作用。

JLabel lblbackground = new JLabel();
lblbackground.setBounds(20, 20, 160, 160);
lblbackground.setBorder(new LineBorder(new Color(0, 0, 0), 2));
lblbackground.setIcon (new ImageIcon (this.getClass().getResource("/boundary/background.jpg")));
lblbackground.setHorizontalAlignment (SwingConstants.CENTER);
BufferedImage img = new BufferedImage(lblbackground.getIcon().getIconWidth(), lblbackground.getIcon().getIconHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = img.createGraphics();
lblbackground.getIcon().paintIcon(null, g, 0, 0);
g.dispose();
Image newing = img.getScaledInstance(150, 150, java.awt.Image.SCALE_SMOOTH);
lblbackground.setIcon(new ImageIcon(newing));

//getContentPane().setLayout(new GridBagLayout());
contentPane = new JPanel();
//contentPane.setBackground(Color.LIGHT_GRAY);
contentPane.setBorder(null);
contentPane.setLayout(null);
contentPane.add(lblbackground);
setContentPane (contentPane);

最佳答案

(...)
// 1) Create your image;
final ImageIcon image = new ImageIcon("../folder/myImage.gif");

//2) Create a JPanel with a background image;
JPanel myPanel = new JPanel(){
@Override
public void paintComponent(Graphics g)
{
g.drawImage(image.getImage(), 0, 0, null);
}
};

//3) Add panel
getContentPane().add(myPanel);

(...)

关于java - 如何在不使用 main 方法或调用其他方法的情况下设置 contentPane?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19844666/

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