簡體   English   中英

如何將背景圖像添加到JPanel?

[英]How do I add a background image to a JPanel?

我有一個JFrame,JPanel在其中。 我的游戲背景完全是黑色的,因為實體位於其頂部。 我只是想以“最簡單”的方式將背景從計算機上更改為圖像,而無需進行太多更改。

public Game() {
    // Frame
    JFrame container = new JFrame("Space Invaders");

    // Resolution
    JPanel panel = (JPanel) container.getContentPane();
    panel.setPreferredSize(new Dimension(800,600));
    panel.setLayout(null);

    // Canvas Size
    panel.setBounds(0,0,800,600);
    panel.add(this);

    // Window Visible
    container.pack();
    container.setResizable(false);
    container.setVisible(true);

    container.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
}

你可以...

使用JLabel作為背景組件...

JFrame container = new JFrame("Space Invaders");
JLabel label = new JLabel(new ImageIcon(ImageIO.read(...)));
label.setLayout(new BorderLayout());
container.setContentPane(label);

// Resolution
// There are simply so many different ways to achieve this
// that are better it's not funny
//JPanel panel = (JPanel) container.getContentPane();
//panel.setPreferredSize(new Dimension(800, 600));
//panel.setLayout(null);

// Canvas Size
//setBounds(0, 0, 800, 600);
//panel.add(this);

// Window Visible
container.pack();
container.setResizable(false);
container.setVisible(true);

container.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Pointless
//container.addWindowListener(new WindowAdapter() {
//    public void windowClosing(WindowEvent e) {
//          System.exit(0);
//      }
//});

問題是:

  1. 標簽將僅使用icontext屬性來計算標簽的preferredSize
  2. 如果您使用的是java.awt.Canvas ,則它將覆蓋此組件,因為java.awt.Canvas不能透明。

有關更多詳細信息,請參見讀取/加載圖像如何使用標簽

你可以...

在渲染器重置內容之前,使用Graphics#drawImage繪制背景圖像。

通常,這將是一個更好的解決方案,因為您可以完全控制圖像的大小和位置,並且在使用java.awt.CanvasBufferStrategy可以使用

有關更多詳細信息,請參見2D圖形使用圖像

暫無
暫無

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

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