简体   繁体   English

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

[英]JButtons only show up when I hover over them. Also disappear when I resize window

JButtons only show up when I hover over them. JButton仅在我将鼠标悬停在它们上方时才会显示。 Also disappear when I resize window. 调整窗口大小时也消失。 The error lies in the constructor here. 错误在于此处的构造函数中。 I am extending a JFrame. 我正在扩展一个JFrame。 Removing the JPanel doesn't fix it. 删除JPanel不能修复它。 Please help. 请帮忙。

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 Example. 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"));
}

The other class is here: 另一个类在这里:

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();
}

}

Your problem is due to your overriding JPanel's getX() and getY() . 您的问题是由于您重写了JPanel的getX()getY() These methods are used by the container's layout managers to help place components, and by overriding these key methods, you mess up the ability of the layouts to do this. 容器的布局管理器使用这些方法来帮助放置组件,并且通过覆盖这些关键方法,您可以弄乱布局的功能。 Please change the names of those methods to something that does not override a key method of the class. 请将那些方法的名称更改为不会覆盖该类的键方法的名称。 If this is a chess square, I'd rename the variables to rank and file, and have getRank() and getFile() methods. 如果这是一个国际象棋广场,则将变量重命名为等级和文件,并具有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;
    }

    // .....
}

add

pack();

in the GameBoard class, before setting visible. 在GameBoard类中,然后将其设置为可见。 This will ensure that the size is correct and make room for any buttons which are hanging off the edge... This will make the frame the size of the JPanel, exactly as it is rendered after all objects are added. 这将确保大小正确,并为悬于边缘的任何按钮留出空间...这将使框架的大小与JPanel的大小完全相同,即添加所有对象后呈现的大小。

also maybe 也可能

setResizable(false);

as it will stop you resizing your windows, and with images this can cause buttons to disappear as well as reappear if the user accidentally clicks the sides. 因为它会阻止您调整窗口的大小,如果使用图像,这可能会导致按钮消失以及用户意外单击侧面时重新出现。 I'd put this underneath: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 我将其放在下面: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我将鼠标悬停在它们上方后才显示 - jbuttons only showing after i hover over them 添加十几个 JButton 后,并不是所有的 JButton 都显示出来。 我究竟做错了什么? - Not all of my JButtons are showing up after I add a dozen of them. What am I doing wrong? JButton仅在鼠标悬停时起作用 - JButtons Only Working When Mouse Hovers Over 当我带来Firebase数据库时,它们正在复制数据。 当我发送消息时,它发送两个 - Firebase Database is duplicating the data when i bring them. When i send a message it sends two JPanel仅在调整窗口大小(JFrame)时显示 - JPanel only displaying when I resize Window (JFrame) 在我最小化并再次打开窗口之前,JButton不会显示 - JButtons don't show until I minimize and bring the window up again 对象在调整大小时以及窗口最小化时消失 - Objects disappear on resize and when the window is minimized 计算器:按钮仅在测试 JFrame 类中鼠标悬停在按钮上时显示 - Calculator: Buttons ONLY show up when mouse hovers over them in Test JFrame class 当对JFrame使用PaintComponent时,除非使用pack,否则必须调整窗口大小才能显示它。 我该如何补救? - When I use an PaintComponent to my JFrame, I have to resize my window to get it to show up unless I use pack. How can I remedy this? 调整大小或移动滚动条时,线条和椭圆形消失 - My lines and ovals disappear when I resize or move scrollbars
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM