PaintIcon больше не позволяет мне рисовать изображения - PullRequest
0 голосов
/ 03 ноября 2018

Так что я просто исследую Java и пытаюсь сделать процедурную карту для развлечения, но когда я начал выбирать случайные точки в своем массиве, чтобы установить в качестве определенного изображения, оно больше не будет рисовать. Проблема возникает только в последнем цикле for и возникает на:

if(world[c][r] == 2)

или

mountain.paintIcon(this, g, r*Run2.distBetweenTiles, c*Run2.distBetweenTiles);

Я убрал исходную траву и воду, чтобы посмотреть, не подкрашена ли она, но дело не в этом, просто она никогда не красится. Если бы кто-нибудь мог просветить меня, это было бы здорово!

Используемые фотографии: enter image description here, enter image description here, enter image description here Постскриптум Run2.rowSize, Run2.colSize, Run2.distBetweenTiles = 20 (все статические)

import java.io.IOException;
import java.util.Properties;

import javax.swing.JFrame;

public class Run2
{
    public static final int rowSize = 20;
    public static final int colSize = 20;
    public static final int distBetweenTiles = 20;

    public static void main (String [] args) throws IOException
    {
        JFrame frame = new JFrame();

        WorldCreation2 panel = new WorldCreation2();
        frame.add(panel);

        frame.setTitle("RandomScape");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(1280, 720);
        frame.setVisible(true);
        frame.setResizable(false);

        Properties properties = new Properties();
        properties.setProperty("Health", "20");
        System.out.println(properties.getProperty("Health"));
    }
}

import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.ImageIcon;
import javax.swing.JComponent;

public class WorldCreation2 extends JComponent
{
    private static final long serialVersionUID = 1L;

    int rowAmount, colAmount;
    int[][] world;
    int islandAmount = 3;
    ArrayList<Point> islandStartingPositions = new ArrayList<Point>();
    protected void paintComponent(Graphics g) 
    {
        super.paintComponent(g);

        int width = getWidth(); 
        int height = getHeight();
        int rowAmount, colAmount;
        int randomRow, randomCol;

        ImageIcon water = new ImageIcon("C:\\Users\\CJ Petruzzelli\\Pictures\\Water 20x20.jpg");
        ImageIcon grass = new ImageIcon("C:\\Users\\CJ Petruzzelli\\Pictures\\Grass 20x20.jpg");
        ImageIcon mountain = new ImageIcon("C:\\Users\\CJ Petruzzelli\\Pictures\\Mountain 20x20.jpg");

        colAmount = height/Run2.colSize;
        rowAmount = width/Run2.rowSize;
        world = new int[colAmount][rowAmount];
        //System.out.println(rowAmount + " , " + colAmount);

        Random rand = new Random();

        //Initialize all values to default 0
        for(int r = 0; r < rowAmount; r++)
        {
            for(int c = 0; c < colAmount; c++)
            {
                //Sets tiles to 0 so full array is instantiated
                world[c][r] = 0;
                grass.paintIcon(this, g, r*Run2.distBetweenTiles, c*Run2.distBetweenTiles);
            }
        }
        ////Puts water on all edges of the map
        for(int r = 0; r < rowAmount; r++)
        {
            for(int c = 0; c < colAmount; c++)
            {
                //Left Side, Right Side, Top Side, Bottom Side
                if(r == 0 && c < colAmount || r == rowAmount-1 && c < colAmount || r < rowAmount && c == 0 || r < rowAmount && c == colAmount-1)
                {
                    world[c][r] = 1;
                    water.paintIcon(this, g, r*Run2.distBetweenTiles, c*Run2.distBetweenTiles);
                }
            }
        }

        //Pick starting points
        int islandStartingPointNum = 0;
        for(int t = islandAmount; t > 0; t--)
        {
            //Pick a random square (Cannot be an edge tile)
            randomRow = rand.nextInt(rowAmount-1)+1;
            randomCol = rand.nextInt(colAmount-1)+1;
            String rowString = String.valueOf(randomRow);
            String colString = String.valueOf(randomCol);
            if(world[randomCol][randomRow] == 1)
            {
                System.out.println(colString + " , " + rowString + " This is an edge tile");
                islandAmount++;
            }
            else
            {
                System.out.println(colString + " , " + rowString + " This is a grass tile, turning to mountain");
                world[randomCol][randomRow] = 2;
                islandAmount--;
                //Store it
                islandStartingPositions.add(new Point(randomCol, randomRow));
            }
            System.out.println(islandStartingPositions.get(islandStartingPointNum));
            islandStartingPointNum++;
        }

        //Turn starting points into something
        for(int r = 0; r < rowAmount; r++)
        {
            for(int c = 0; c < colAmount; c++)
            {
                if(world[c][r] == 2) // Checking number of location not current locations number?
                {
                    System.out.println("This is a mountain tile");
                    mountain.paintIcon(this, g, r*Run2.distBetweenTiles, c*Run2.distBetweenTiles);
                }
            }
        }
    }
}

1 Ответ

0 голосов
/ 03 ноября 2018

Вот краткий пример добавления плиток к JComponent.
Если вам нужна дополнительная помощь, опубликуйте MCVE вашей проблемы. Это должно быть примерно так:

import java.awt.Dimension;
import java.awt.GridLayout;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Run2
{

    public static void main (String [] args) throws IOException
    {
        JFrame frame = new JFrame();
        frame.add( new WorldCreation2());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}


class WorldCreation2 extends JComponent
{

    private int rows = 15, cols = 10;
    private URL[] urls = { //use embedded resources for posting question
            getUrl("http://static.coach.com/aapz_prd/on/demandware.static/-/Library-Sites-globalLibrary/default/dw1777ce46/201708/canada-wwcm/close_grey.png"),
            getUrl("https://s7d2.scene7.com/is/image/JCPenney/DP0423201517014421S.jpg?wid=20&hei=20&op_usm=.4,.8,0,0&resmode=sharp2"),
            getUrl("https://i2.wp.com/www.todaytells.com/wp-content/uploads/2018/07/new-and-ongoing-cinema-releases-uk-ire-from-thu-jul-12.jpg?fit=20%2C20&ssl=1")
    };

    public WorldCreation2() {

        setLayout(new GridLayout(rows, cols));
        for(int row = 0; row < rows; row++) {
            for(int col = 0; col < cols; col++) {
                if(row < 5)
                {
                    add(getTile(urls[0]));
                }else if (row < 10) {
                    add(getTile(urls[1]));
                }else {
                    add(getTile(urls[2]));
                }
            }
        }
    }

    private JLabel getTile(URL url){

        return new JLabel(new ImageIcon(url));
    }

    private URL getUrl(String path) {

        URL url = null;
        try {
            url =   new URL(path);
        } catch (MalformedURLException ex) {    ex.printStackTrace();   }

        return url;
    }
}
...