java - JButtons 仅当我将鼠标悬停在它们上方时才会显示。当我调整窗口大小时也会消失

标签 java swing jframe jpanel jbutton

JButtons 仅当我将鼠标悬停在它们上方时才会显示。当我调整窗口大小时也会消失。错误就出在这里的构造函数上。我正在扩展 JFrame。删除 JPanel 并不能解决问题。请帮忙。

public GameBoard(String title, int width, int height)
{
    super();
    this.boardWidth = width;
    this.boardHeight = height;

    // Create game state
    this.board = new GameSquare[width][height];

    // Set up window
    setTitle(title);
    setSize(720,720);
    setContentPane(boardPanel);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    boardPanel.setLayout(new GridLayout(height,width));

    int decorator = 0;
    for (int y = 0; y<height; y++){
        decorator++;
        for (int x = 0; x<width; x++){
            if (decorator % 2 == 0)
                board[x][y] = new GameSquare(x, y, "BLACK");
            else
                board[x][y] = new GameSquare(x, y, "WHITE");

            board[x][y].addActionListener(this);
            boardPanel.add(board[x][y]);
            decorator++;
        }
    }
    // make our window visible
    setVisible(true);
}

MCV 示例。

package chess;

public class GameBoard extends JFrame implements ActionListener
{
private JPanel boardPanel = new JPanel();

private int boardHeight;
private int boardWidth;
private GameSquare[][] board; 

public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {

  @Override
  public void run() {
    GameBoard gameBoard = new GameBoard("The Revolutionary War",8,8);
  }
    });
}


/**
 * Create a new game board of the given size.
 * As soon as an instance of this class is created, it is visualised
 * on the screen.
 * 
 * @param title the name printed in the window bar.
 * @param width the width of the game area, in squares.
 * @param height the height of the game area, in squares.
 */
public GameBoard(String title, int width, int height)
{
    super();
    this.boardWidth = width;
    this.boardHeight = height;

    // Create game state
    this.board = new GameSquare[width][height];

    // Set up window
    setTitle(title);
    setSize(720,720);
    setContentPane(boardPanel);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    boardPanel.setLayout(new GridLayout(height,width));

    for (int y = 0; y<height; y++){
        for (int x = 0; x<width; x++){

            board[x][y] = new GameSquare(x, y, this);
            board[x][y].setEnabled(true);
            board[x][y].addActionListener(this);

            boardPanel.add(board[x][y]);
        }
    }
    // make our window visible
    setVisible(true);
}

/**
 * Returns the GameSquare instance at a given location. 
 * @param x the x co-ordinate of the square requested.
 * @param y the y co-ordinate of the square requested.
 * @return the GameSquare instance at a given location 
 * if the x and y co-ordinates are valid - null otherwise. 
 */
public GameSquare getSquareAt(int x, int y)
{
    if (x < 0 || x >= boardWidth || y < 0 || y >= boardHeight)
        return null;

    return (GameSquare) board[x][y];
}

public void actionPerformed(ActionEvent e)
{
    // The button that has been pressed.s
    GameSquare square = (GameSquare)e.getSource();

}

//BufferedImage background = ImageIO.read(new File("/path/to/image.jpg"));
}

另一个类在这里:

package chess;

public class GameSquare extends JButton {

/**
 * 
 */
private static final long serialVersionUID = 1L;
private int x;
private int y;
private ChessPiece chessPiece;
private boolean selected;
private ImageIcon icon;

GameSquare(int xPos, int yPos, GameBoard board){
    super();
    x = xPos;
    y = yPos;
    chessPiece = null; 
    selected = false;

    // Test to see colour of the base tile
    if ((xPos+yPos) % 2 == 1){
        icon = new ImageIcon(getClass().getResource("/pics/black.png"));
        this.setIcon(icon);
    }
    else if ((xPos+yPos) % 2 == 0) {
        icon = new ImageIcon(getClass().getResource("/pics/white.png"));
        this.setIcon(icon);
    }
}

public int getX(){
    return x;
}

public int getY(){
    return y;
}

public void setChessPiece(ChessPiece piece){
    chessPiece = piece;
}

public ChessPiece getChessPiece(){
    return chessPiece;
}

public void setImage(){
    setIcon(chessPiece.getIcon());
}

public void select(){
    selected = true;
    setIcon(new ImageIcon(getClass().getResource("pics/selected.png")));
}

public void deselect(){
    selected = false;
    if (chessPiece == null) setIcon(icon);
    else setImage();
}

}

最佳答案

您的问题是由于您覆盖 JPanel 的 getX()getY() 造成的。容器的布局管理器使用这些方法来帮助放置组件,并且通过重写这些关键方法,您会破坏布局执行此操作的能力。请将这些方法的名称更改为不会覆盖该类的关键方法的名称。如果这是一个国际象棋方格,我会将变量重命名为“rank”和“file”,并具有 getRank()getFile() 方法。

public class GameSquare extends JButton {
    private int file;
    private int rank;
    // ....

    GameSquare(int xPos, int yPos, GameBoard board){
        super();
        file = xPos;
        rank = yPos;
        chessPiece = null; 
        selected = false;

        // .....
    }

    public int getFile(){
        return file;
    }

    public int getRank(){
        return rank;
    }

    // .....
}

关于java - JButtons 仅当我将鼠标悬停在它们上方时才会显示。当我调整窗口大小时也会消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45107882/

相关文章:

java - 重构以将私有(private)字段从一个类移动到它的辅助类?

java - 当我们使用 lombok builder 有继承关系时,如何构建一个对象?

java - 将 byte[] 解析回 Protocol Buffer 消息实例时出现 RuntimeException! (反序列化)

java - 创建 JFileChooser 对象时出现空指针异常

java - 如何使 JTable 在 Java 中可编辑

java - 在从 JTextField 读取之前等待键

Java gui如何获取文本框的大小

Java 密码检查器

java - 当 KeyEvent.VK_ENTER 重新分配给它时,如何让 JTextField 触发它的 ActionEvent?

java - gridheight 不会影响我的按钮