分配Image对象不会导致任何内容

时间:2014-07-17 05:14:42

标签: java image graphics drawing

我设置它所以它只是画一个浅灰色的背景和一些矩形来创建一个网格。我的下一个目标是分配两个图像,以便我可以默认网格加载为一个,然后最终添加一些监听器让我将它们更改为另一个。

但是,当我通过ImageIcon将图像(png格式)分配给Image对象(之前创建并分配并在现场创建一个新对象时)会导致显示默认背景颜色,并且不会绘制任何内容

无论我将作业移动到何处,都会发生这种情况,除非我将作业放入绘图方法本身。

我正在尝试使用的图像工作正常,我从以前工作的项目中直接拉出来,位置没有改变。但可以肯定的是,我复制了地址并再次放入。

以下是代码(导致问题的分配在Block中):

主:

package BLURGpackage;

import javax.swing.JFrame;

public class Main extends JFrame
{
private final int FRAME_WIDTH = 1200, FRAME_HEIGHT = 1034; // add 34 onto height  
//to show all of the panel

public Main()
{
    setSize(FRAME_WIDTH, FRAME_HEIGHT);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setResizable(false);
    setVisible(true);

    Panel panel = new Panel();

    add(panel);
}

public static void main(String[] args)
{
    Main m = new Main();
}
}

面板:

package BLURGpackage;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class Panel extends JPanel implements Runnable
{
public final static int PANEL_WIDTH = 1200, PANEL_HEIGHT = 1000;
private Dimension panelDimension = new Dimension(PANEL_WIDTH, PANEL_HEIGHT);

private Thread panelThread = null;
private boolean threadRunning = false;

private Image dbi = null;
private Graphics dbg = null;

Grid grid;  

private int mouseX = 0, mouseY = 0;
// ============ CHANGE THESE TO CHANGE THE LOCATION OF WHERE THE X AND Y COORDS ARE PRINTED ON THE SCREEN =============
private int printXCoordsX = 10; // X-Coordinate for where to print the current mouse X location
private int printXCoordsY = 855; // Y-Coordinate for where to print the current mouse X location
private int printYCoordsX = printXCoordsX; // X-Coordinate for where to print the current mouse Y location
private int printYCoordsY = printXCoordsY + 15; // Y-Coordinate for where to print the current mouse Y location
// ====================================================================================================================

public Panel()
{   
    grid = new Grid();

    setPreferredSize(panelDimension);
    setBackground(Color.LIGHT_GRAY);


    // ===== Listeners ==========
    addMouseMotionListener(new MouseMotionAdapter()
    {
        public void mouseMoved(MouseEvent e)
        {
            mouseX = e.getX();
            mouseY = e.getY();
        }
    });

    // ====== Start ============= (if startPanel is before listeners, dbi is null... dunno why)
    startPanel();
}

private void startPanel()
{
    if(panelThread == null || threadRunning == false)
    {
        panelThread = new Thread(this);
        threadRunning = true;
        panelThread.start();
    }
    else
        System.out.println("panelThread is NOT null on startup");
}

@Override
public void run() 
{
    while(threadRunning)
    {
        update();
        render();
        paintScreen();
    }
}

public void update()
{
    // Logic here
}

public void render()
{
    if(dbi == null)
    {
        dbi = createImage(PANEL_WIDTH, PANEL_HEIGHT);
        if(dbi == null)
            System.err.println("dbi is NULL");
        else
        {
            dbg = dbi.getGraphics();
        }
    }

    dbg.setColor(Color.LIGHT_GRAY);
    dbg.fillRect(0, 0, PANEL_WIDTH, PANEL_HEIGHT);
    draw(dbg);
}

public void paintScreen()
{
    Graphics g;

    try
    {
        g = this.getGraphics();
        if(dbi != null && g != null)
        {
            g.drawImage(dbi, 0, 0, null);
        }
        Toolkit.getDefaultToolkit().sync();
        g.dispose();
    }catch(Exception e)
    {
        e.printStackTrace();
    }
}

public void draw(Graphics g)
{
    g.setColor(Color.BLACK);
    g.drawString("X: "+mouseX, printXCoordsX, printXCoordsY);
    g.drawString("Y: "+mouseY, printYCoordsX, printYCoordsY);
    // Allow the Grid to draw
    grid.draw(g);
}
}

网格:

package BLURGpackage;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.ImageIcon;

public class Grid 
{
// ======== CHANGE THESE VARIABLES TO CHANGE THE SIZE OF THE GRID =============
public final static int GRID_ROWS = 21, GRID_COLUMNS = 25;
private final int RECT_WIDTH = 48, RECT_HEIGHT = 40;
private final int NUM_BLOCKS = GRID_ROWS*GRID_COLUMNS;

/*public final static int GRID_ROWS = 25, GRID_COLUMNS = 25;
private final int RECT_WIDTH = Panel.PANEL_WIDTH / GRID_ROWS; // 1200 / 25 = 48 px width per rect
private final int RECT_HEIGHT = Panel.PANEL_HEIGHT / GRID_COLUMNS; // 1000 / 25 = 40 px height per rect
private final int NUM_BLOCKS = GRID_ROWS*GRID_COLUMNS;*/
// ============================================================================

private Block[] blockArray;
private int[] blockSelectArray; // numbers for which block is selected. Feed in through file reader

public Grid()
{
    // ===== FOR TESTING ONLY======
    blockArray = new Block[NUM_BLOCKS];
    blockSelectArray = new int[NUM_BLOCKS];

    for(int i=0; i < NUM_BLOCKS; i++)
        {
            blockSelectArray[i] = 0;
        }
    // ============================

    loadBlocks();
}

private void loadBlocks()
{
    int x, y;
    x = y = 0;

    for(int i = 0; i < NUM_BLOCKS; i++)
    {
        if(x >= Panel.PANEL_WIDTH) // if x hits right boundary, reset x and increment y by the px height of a single block
        {
            x = 0;
            y += RECT_HEIGHT;
        }

        blockArray[i] = new Block(blockSelectArray[i], x, y);

        x += RECT_WIDTH;
    }
}

public void draw(Graphics g)
{
    g.setColor(Color.BLACK);
    for(int i=0;i<NUM_BLOCKS;i++)
    {
        g.drawRect(blockArray[i].getBlockX(), blockArray[i].getBlockY(), RECT_WIDTH, RECT_HEIGHT);
        blockArray[i].draw(g);
    }
}


}

块:

package BLURGpackage;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;

import javax.swing.ImageIcon;

public class Block 
{
private Image blockImage = null;
private Image DIRT_IMG = new ImageIcon("C:/Users/Tyler/workspace/IntTut1/src/thejavahub/images/dirt.png").getImage();
// ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ Problem assignment
private Rectangle blockRect = null;
private boolean solid;

private final int RECT_WIDTH = Panel.PANEL_WIDTH / Grid.GRID_ROWS; // 1200 / 25 = 48 px width per rect
private final int RECT_HEIGHT = Panel.PANEL_HEIGHT / Grid.GRID_COLUMNS; // 1000 / 25 = 40 px height per rect

public Block(int blockNum, int x, int y)
{
    // switch statement on blockNum for what block
    switch(blockNum)
    {
    default:
        System.out.println("Default of switch in Block constrcutor hit");
        break;
    case 0: // background block

        solid = false;
        break;
    case 1: // dirt block 
        blockImage = DIRT_IMG; // <---- uses the assigned image --------
        solid = true;
        break;
    }
    // set the coordinates of the block
    blockRect = new Rectangle(x, y, RECT_WIDTH, RECT_HEIGHT);
}

public void draw(Graphics g)
{
    // draw the image here (.... g.drawImage(blockImage, blockRect.x, blockRect.y, null);   )
    g.drawImage(blockImage, blockRect.x, blockRect.y, null);
}



// ==== GETTERS AND SETTERS ===
public int getBlockX()
{
    return this.blockRect.x;
}

public void setBlockX(int x)
{
    this.blockRect.x = x;
}

public int getBlockY()
{
    return this.blockRect.y;
}

public void setBlockY(int y)
{
    this.blockRect.y = y;
}


public boolean isSolid() {
    return solid;
}


public void setSolid(boolean solid) {
    this.solid = solid;
}




}

1 个答案:

答案 0 :(得分:0)

一些要点:

  1. 在添加所有组件后,最后调用frame.setVisible(true)

  2. 根据组件的首选尺寸,使用符合组件的frame.pack()代替frame.setSize()

  3. 在自定义绘画的情况下,覆盖getPreferredSize()以设置JPanel的首选大小。

  4. 以两种方式使用Swing Timer代替最适合swing应用的Thread:

  5. 使用SwingUtilities.invokeLater()EventQueue.invokeLater()确保EDT已正确初始化。

    了解更多

  6. 示例代码:

    private Timer timer;
    ...
    
    // 1 second delay
    timer = new javax.swing.Timer(1000, new ActionListener() {
    
        @Override
        public void actionPerformed(ActionEvent arg0) {
            // next call
        }
    });
    timer.setRepeats(true);
    timer.start();
    
    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
    
            @Override
            public void run() {
                Main m = new Main();
            }
        });
    }
    
    class MyRoll extends JPanel {
        // override paintComponent in case of custom painting
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            ...
        }
    
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(..., ...);
        }
    }