2013-03-21 85 views
1

我有一個圖像,必須組成一個8x8的網格,所以它是一個董事會的背景。JLabel背景圖像......怪異的行爲?

我被告知可以使用ImageIcon和JLabel來做到這一點,我試過了,它似乎沒有工作。

  • 它不允許我添加組件(它也是JLabel)。
  • 另外,當程序運行時,我點擊一個方塊 - 它會消失,這不是理想的,因爲它應該是背景。

下面是代碼:

 for (int i = 0; i < 8; i++) 
     { 
     for (int j = 0; j < 8; j++) 
     { 
      square=new JLabel(); 
      square.setIcon(icon); 
      chessBoard.add(square); 
     } 
     } 

的完整代碼:http://pastebin.com/YdavUmGz

我做得可怕的錯誤在這樣的背景圖片?

任何幫助將不勝感激,在此先感謝。

+0

你是如何加載圖像?圖像沒有出現?您只能將一個IconImage設置爲一個JLabel,因此如果您需要64(8 X 8)圖像,則需要64個JLabel。只有一個大的圖像是一個網格(8×8)會更簡單。只是一個想法。 – John 2013-03-21 02:51:20

+0

圖像看起來不錯,我需要它,但我覺得運動代碼正在影響它,因爲我可以拖動方塊。但它應該是作品的背景。 – user1902535 2013-03-21 02:53:48

+1

我會擺脫'JLayeredPane'。只需簡單地使用'GridLayout'即可。您可以將其他組件添加到'JLabel',所以您應該開始將網格標籤的佈局設置爲像'BorderLayout'。然後當你點擊時,你可以簡單地添加你的'JLabel'作品。 – MadProgrammer 2013-03-21 02:54:06

回答

3

你在找這樣的事嗎?

import java.awt.*; 
import javax.swing.*; 

public class ChessBoard extends JFrame { 

    private JPanel panel; 

    public ChessBoard() { 
     panel = new JPanel(); 
     panel.setLayout(new GridLayout(8, 8, 0, 0)); //Create the board 
     //Add JLabels 
     for (int i = 0; i < 64; i++) { 
      JLabel label = new JLabel(); 
      label.setIcon(
        new ImageIcon(getClass().getResource("images/face.png"))); 
      panel.add(label); 
     } 
     //Add the panel to the JFrame 
     this.add(panel); 
     this.pack(); 
     this.setVisible(true); 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 

    public static void main(String[] args) { 
     try { 
      UIManager.setLookAndFeel(
        UIManager.getSystemLookAndFeelClassName()); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     java.awt.EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       new ChessBoard(); 
      } 
     }); 
    } 
} 

enter image description here