2010-08-13 78 views
0

我真的需要你們的幫助。我必須在3×3的圖像網格上進行動畫。繪圖和動畫的圖像網格

我的問題是:

1) 我如何構建3×3格與圖像?

這是我做的,但不是因爲工作,因爲我在這行得到NullPointerException異常:rail[x][y] = new JLabel(icon);

import java.awt.Component; 
import java.awt.GridLayout; 
import java.awt.Image; 
import java.awt.Toolkit; 

import javax.swing.ImageIcon; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 

public class ButtonGrid { 

    JFrame frame=new JFrame(); //creates frame 

    JButton[][] grid; //names the grid of buttons 
    JLabel[][] rail = null; 

    public ButtonGrid(int width, int length){ //constructor with 2 parameters 
      frame.setLayout(new GridLayout(width,length)); //set layout of frame 
      grid=new JButton[width][length]; //allocate the size of grid 
      for(int y=0; y<length; y++){ 
        for(int x=0; x<width; x++){ 
          //grid[x][y]=new JButton("("+x+","+y+")"); 
          //frame.add(grid[x][y]); //adds button to grid 
         ImageIcon icon = createImageIcon("images/crossingsHorizontal.JPG", ""); 
         //JLabel lab = new JLabel(icon); 
         rail[x][y] = new JLabel(icon); 
         frame. add(rail[x][y]); 
        } 
      } 
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      frame.pack(); 
      frame.setVisible(true); 
    } 

    public static ImageIcon createImageIcon(String path,String description) { 
      java.net.URL imgURL = ButtonGrid.class.getResource(path); 
      if (imgURL != null) { 
       return new ImageIcon(imgURL, description); 
      } else { 

       return null; 
      } 
    } 


    public static void main(String[] args) { 
     new ButtonGrid(3,3);//makes new ButtonGrid with 2 parameters 
} 


} 

2) 如何使用此網格爲我的動畫背景?

3) 我必須旋轉網格[2] [2]中的圖像,我怎樣才能訪問這個圖像和旋轉它?我知道如何做旋轉,所以告訴我如何獲得元素[2] [2],以便我可以旋轉它。

感謝您的幫助

+0

參見http://stackoverflow.com/questions/3420651 – trashgod 2010-08-13 16:43:41

回答

0

這條線是錯的鞦韆:

frame.setLayout(new GridLayout(width,length)) 

我記得,我們應該運用佈局,面板,即

frame.getContentPane().setLayout (new GridLayout(width,length)); 

此行是錯誤的,因爲井:

frame.add(rail[x][y]); 

解決方案是一樣的:使用contentPane

一些基本知識可以在JFrame javadocs page找到。

0

既然你正在試圖建立一個網格,那麼,我建議你看看GridLAyout。這將照顧你的組件,因爲它會將給定的區域分割成網格。請使用rotate方法。

+0

他已經在使用GridLayout,但方式不對。 – Roman 2010-08-13 12:21:45

+0

@羅曼,是我的壞...我誤解了我自己,這就是爲什麼我發佈了一個鏈接到GridLayout教程。 @Kap:當你問一個問題,並且人們回答時,你可以選擇什麼問題是正確的答案。這樣做,正確回答問題的人將獲得積分。如果你不回答你的問題,用戶將不願意回答你的問題。 – npinti 2010-08-13 12:27:10

+0

好的,謝謝你。我會從現在開始。我如何評價答案? – 2010-08-13 12:30:38

0

答:1)

你得到的NPE,因爲你不初始化命名'rail'喜歡你的陣列做'grid':

public ButtonGrid(int width, int length){ //constructor with 2 parameters 
     frame.setLayout(new GridLayout(width,length)); //set layout of frame 
     grid=new JButton[width][length]; //allocate the size of grid 
-->  rail=new JLabel[width][length]; //allocate the size of rail 
     for(int y=0; y<length; y++){ 

這是一般更好地工作在JPanel,就像建議的那樣,但JFrame上的'add(...)'和'setLayout(...)'是委託給內容窗格的便利方法,所以這會起作用。