2

我需要能够在类中使用数组texture[](位于Textures类中)中的变量Board。但我不知道我将如何去做。

这只是我试图弄清楚如何Textures在 Java 中添加东西,我正在尝试学习如何制作游戏。所以我很菜哈哈。

这是我想在其中使用texture[]数组的类。

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class Board extends JPanel{
    
    public Board(){
        
    }
    
    public void paint(Graphics g){
        g.drawImage(texture[1], 0, 0, null);
        g.setFont(new Font("Verdana", 0, 50));
        g.setColor(Color.YELLOW);
        g.drawString(": FPS", 20, 50);
    }
    
    public void update(){
        repaint();
    }
}

这是创建texture[]数组的类。

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class Textures {

    BufferedImage img;
    private int w, h;
    public int id[];
    public Image texture[];
    
    public Textures() throws IOException {
        URL url = this.getClass().getResource("Resources/Textures.png");
        img = ImageIO.read(url);
        w = 0;
        h = 0;
        for(int i1 = 0; i1 < 16; i1++){
            texture[i1] = img.getSubimage(w, h, 16, 16);
            id[i1] = i1;
            w += 16;
            h += 16;
        }
    }
}
4

1 回答 1

2

由于您的texture变量是公开的,因此只需执行以下操作:

texturesClassInstance.texture;

用另一种方式:

public class Board extends JPanel{

    public void someMethod(){

        Textures texturesClassInstance = new Textures();

        Image image1 = texturesClassInstance.texture[0];
        Image image2 = texturesClassInstance.texture[1];

        //do something with image1 and image2
    }
}

Board类中,但最好将其声明为private并创建一个方法,如:

public class Textures {

    // more variables
    private Image texture[];

    // more code

    public Image[] getTextures(){
        return this.texture;
    }

}
于 2012-08-14T19:24:40.923 回答