[英]Setting image background java swing
我正在嘗試將圖像設置為背景,但我不確定此代碼本身有什么問題。請您在這里提供幫助並指出可以更改的內容嗎? 當我運行它時,它像以前一樣給我一個空白背景,沒有預期的結果。
public
class MenuFrame extends JFrame {
public MenuFrame(){
generateMenuFrame();
}
public void generateMenuFrame()
{
JLabel background;
JFrame menuFrame = new JFrame("Koronawirus AntiPlague - Menu");
try {
menuFrame.setIconImage(ImageIO.read(MenuFrame.class.getResourceAsStream("resources/images/Icon.png")));
} catch (IOException ex) {
ex.printStackTrace();
}
ImageIcon backgroundImage = new ImageIcon("resources/images/MenuBackground.png");
background = new JLabel("",backgroundImage,JLabel.CENTER);
background.setBounds(0,0,getWidth(),getHeight());
menuFrame.add(background);
menuFrame.setSize(700,400);
menuFrame.setVisible(true);
menuFrame.setResizable(false);
menuFrame.setLocationRelativeTo(null);
menuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
更新:
謝謝你們的任何提示。 正如 Andrew 建議的那樣,我決定保留一個沒有擴展的實例,而且我使用了 paintComponent 方法的覆蓋:
public
class MenuFrame {
private JPanel contentPane;
public MenuFrame(){
generateMenuFrame();
}
public void generateMenuFrame()
{
JFrame menuFrame = new JFrame("Koronawirus AntiPlague - Menu");
try {
menuFrame.setIconImage(ImageIO.read(MenuFrame.class.getResourceAsStream("resources/images/Icon.png")));
} catch (IOException ex) {
ex.printStackTrace();
}
menuFrame.setSize(700,400);
menuFrame.setVisible(true);
menuFrame.setResizable(false);
menuFrame.setLocationRelativeTo(null);
menuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel() {
public void paintComponent(Graphics g) {
Image img = Toolkit.getDefaultToolkit().getImage(
MenuFrame.class.getResource("resources/images/MenuBackground.jpg"));
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
}
};
menuFrame.setContentPane(contentPane);
}
}
background.setBounds(0,0,getWidth(),getHeight());
上面的代碼會將 label 的大小設置為 (0, 0),因為您正在擴展 JFrame 並調用框架的 getWidth() 和 getHeight() 方法。 所有 Swing 組件的默認大小為 (0, 0),因此沒有什么可繪制的。
不要試圖玩弄 label 的邊界。
label 的大小將自動設置為圖像的大小。
然后你應該使用:
//menuFrame.setSize(700,400);
menuFrame.pack();
因此框架的大小可以正確顯示 label 及其圖像。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.