JPanel在绘制图像时显示奇怪的错误

我的棋盘游戏出了一个奇怪的错误。该面板由一个带有GameTiles的2D数组组成,GameTiles是JPanel的一个子类。当我有尺寸(600,500)时,一切都很好,但每当我更改它时,我都会在左上角得到一个奇怪的错误。

错误图片(见左上角)

更奇怪的是,当我创建了一个新项目,只是为了试一试,它工作得很完美。这幅画的代码是完全相同的,我没有遇到任何错误。会不会是其他原因导致了这个问题?

问题已修复

Anser:我不小心重写了JPanel的getX和Gty方法。我更改了它们的名称,现在它工作得很好。

Reversi.java

package org.reversi;

import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import org.reversi.gui.GameFrame;

public class Reversi {
public static void main(String[] args) {
    try {
                 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (UnsupportedLookAndFeelException e) {
        e.printStackTrace();
    }

    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            GameFrame frame = new GameFrame("Reversi");
            frame.setSize(600,500);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }
    });
}
}

GameBoard.java

package org.reversi.gui;

import java.awt.Graphics;
import java.awt.GridLayout;

import javax.swing.JPanel;

public class GameBoard extends JPanel{
private GameTile[][] gameBoard = new GameTile[8][8];

public GameBoard() {
    initiateLayout();
}

private void initiateLayout() {
    setLayout(new GridLayout(8, 8));

    for(int row = 0 ; row < 8 ; row++) {
        for(int col = 0 ; col < 8 ; col++) {
            gameBoard[row][col] = new GameTile(col,row);
            add(gameBoard[row][col]);
        }
    }
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    for(int row = 0 ; row < 8 ; row++) 
        for(int col = 0 ; col < 8 ; col++)              
            gameBoard[row][col].repaint();
}
}

GameFrame.java

package org.reversi.gui;

import javax.swing.JFrame;

public class GameFrame extends JFrame {
private GameBoard gameBoard;

/**
 * Creates a new frame.
 * @param gameTitle the title of the frame
 */
public GameFrame(String gameTitle) {
    setTitle(gameTitle);
    gameBoard = new GameBoard();
    add(gameBoard);
}
}

GameTile.java

package org.reversi.gui;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class GameTile extends JPanel {
private BufferedImage image;
private int x;
private int y;

public GameTile(int x, int y) {
    this.x = x;
    this.y = y;
    try {
        this.image = ImageIO.read(new File("tile.png"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}

public int getX() {
    return x;
}

public int getY() {
    return y;
}
}

图像链接(应命名为tile.png):http://i.imgur.com/ejmCtui.png


解决方案

根据您的评论:

这就是问题所在,谢谢你指出这一点。我 在棋盘上移动时使用坐标。如果有一些 这将是一个很好的答案

GameTile.java中:

public int getX() {
    return x;
}

public int getY() {
    return y;
}
使用此选项,您实际上覆盖了JPanelgetY,并返回将影响Layout的坐标。这可以通过添加@Override annotation(注意,不会抛出编译器错误,因此我们正确地重写了扩展类中的方法):

来实现
@Override
public int getX() {
    return x;
}

@Override
public int getY() {
    return y;
}

正如@xeon所说,您不应该设置坐标,LayoutManager会这样做。

解决方案:(外加)

  • 删除这些getter或相应地重命名它们。

  • 不要在JFrame上调用setSize,而是在将JPanel which is drawn to viaGraphics object and return the correctDimensions (in your case the image dimensions) and than call [pack()][4] onJFrame`设置为可见之前但在添加组件之后重写getPreferredSize

  • 您需要将调用重新定位到setLocationRelativeTo(...)pack()之后。

    /li>
  • 最好使用JFrame.DISPOSE_ON_CLOSE所以main(String[] args)方法即使在图形用户界面终止后也可以继续执行。

  • 也不要不必要地扩展JFrame

  • 不要在GameTile类中重复加载相同的图像,而是一次加载图像并为GameTile添加参数以接受BufferedImage(我是在使用Internet URL测试时发现这一点的,因为它为每个创建的GameTile读取一个新图像)

以下是进行了必要更改的类:

reversi.java:

public class Reversi {

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new GameFrame("Reversi");
            }
        });
    }
}

GameBoard.java:

public class GameBoard extends JPanel {

    private GameTile[][] gameBoard = new GameTile[8][8];

    public GameBoard() {
        initiateLayout();
    }

    private void initiateLayout() {
        setLayout(new GridLayout(8, 8));

        BufferedImage image = null;
        try {
            image = ImageIO.read(new URL("http://i.imgur.com/ejmCtui.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (int row = 0; row < 8; row++) {
            for (int col = 0; col < 8; col++) {
                gameBoard[row][col] = new GameTile(image, col, row);
                add(gameBoard[row][col]);
            }
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (int row = 0; row < 8; row++) {
            for (int col = 0; col < 8; col++) {
                gameBoard[row][col].repaint();
            }
        }
    }
}

GameTile.java:

public class GameTile extends JPanel {

    private BufferedImage image;
    private int x;
    private int y;

    public GameTile(BufferedImage image, int x, int y) {
        this.image = image;
        this.x = x;
        this.y = y;
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(image.getWidth(), image.getHeight());
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
    }
}

GameFrame.java:

public class GameFrame {

   private GameBoard gameBoard;

    /**
     * Creates a new frame.
     *
     * @param gameTitle the title of the frame
     */
    public GameFrame(String gameTitle) {
        JFrame frame = new JFrame(gameTitle);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        gameBoard = new GameBoard();
        frame.add(gameBoard);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

这将产生:

相关文章