簡體   English   中英

使用JLabel拍攝背景圖像

[英]Using JLabel for a background image

當我運行代碼時,它只是打開一個空窗口,我也很重要

代碼的相關部分:

public class Game extends JFrame implements ActionListener,KeyListener{
    private JLabel background; 
....  
public Game(){
background=new JLabel(new ImageIcon("/graphics/board.gif"));
...
this.add(background);
this.setSize(800,600);
this.setVisible(true);...

我嘗試將JLabel添加到JPanel,然后將其添加到框架,但在窗口中仍然不顯示任何內容

最初的代碼是:

JLabel background = new JLabel("/graphics/board.gif");

這不會將圖像設置在所描述的路徑上,建議使用以下方法(可以簡化為僅使用其他JLabel構造函數,但為清楚起見顯示了步驟)

創建並加載圖像,然后為“標簽”設置圖標,如下所示

ImageIcon icon = new ImageIcon("/graphics/board.gif"); 
JLabel background = new JLabel();
background.setIcon(icon);

鏈接到ImageIcon Java文檔

在布局中設置元素顯示的順序很重要,也許您在標簽上顯示了一些內容。

我猜你有一個類似的目錄結構:

-c:\java  
  - source (for source and class files)  
    - graphic (for your images)
background=new JLabel(new ImageIcon("/graphics/board.gif"));

不要在文件名中指定前導“ /”。 這告訴Java查看C驅動器的根目錄,而不是查看您的類從其執行的目錄。

另外,請勿使用:

this.setSize(800,600);

圖像無法拉伸以填滿框架的尺寸。 您應該使用Intead:

this.pack();

因此框架將是圖像的大小。

暫無
暫無

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

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