绘制和动画图像网格

时间:2010-08-13 12:02:02

标签: java animation grid rotation

我真的需要你们的帮助。我必须在3×3网格图像上做动画。

我的问题是:

1) 如何使用图像构建3 X 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]以便我可以旋转它。

感谢您的帮助

3 个答案:

答案 0 :(得分:0)

Swing这行错误了:

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

我记得,我们应该将布局应用于面板,即

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

这一行也是错误的:

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

解决方案是相同的:使用contentPane

可以在JFrame javadocs page找到一些基础知识。

答案 1 :(得分:0)

由于您正在尝试构建网格,我建议您查看GridLAyout。这将照顾您的组件,因为它会将给定区域拆分为网格。

使用ragards旋转图像,请查看rotate方法。

答案 2 :(得分:0)

回答1)

你得到了NPE,因为你没有像'gerid'一样初始化名为'rail'的数组:

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(...)'是委派给内容窗格的便捷方法,所以这将有效