JButton仅在PC上运行时悬停在其上方时才会出现,而在Mac上则完全不起作用

时间:2018-12-14 11:01:35

标签: java swing jframe jpanel jbutton

我正在为一个学校项目进行国际象棋游戏。我们有一个JFrame,其中只有两个面板,一个主面板,一个位于主面板内部的面板,可容纳所有棋子。我们用JButtons代表棋子。因此,基本上,我们有一个JButton矩阵来表示游戏板,并取决于棋盘中的正方形是否为空,JButton是否具有棋子图标或只是“空”图标。

问题是,当我们运行游戏时,所有按钮都放在彼此的顶部。但是,当我们将鼠标悬停在框架上时,按钮将按计划显示在网格布局中。但是,在每次互动(即移动棋子)之后,按钮消失了,我们必须将鼠标悬停在该区域上才能将其“重新绘制”为预期的样子。每次移动后,我们都认为我们的ActionPerformed女巫重新绘制了框架,认为效果很好。当我们在PC上运行时,所有这些都会发生。在Mac上,所有按钮都堆叠在一起,但是没有悬停效果,因此我们无法玩游戏。

下面的代码包含我们对面板的初始化以及如何为面板重新粉刷。

private ChessGame game;
private JButton[][] board;
private JPanel contentPanel;
private JLabel mess = new JLabel();
private JLabel titel;
private JPanel panel;
private int n;
private JFrame frame;
private GridBagConstraints c;


ViewControl(ChessGame gm, int size){
    this.game=gm;
    this.n = size;

    //MainFrame
    this.frame = new JFrame("Game");
    //this.frame.getContentPane().setLayout(new GridLayout());

    // Content
    this.titel = new JLabel(this.game.gameName);
    this.panel = new JPanel(new GridLayout(size,size));

    // Panel to Store Content
    this.contentPanel = new JPanel(new GridBagLayout());
    this.c = new GridBagConstraints();

    // Stores Btns
    this.board =  new JButton[size][size];
}


private void add_buttons(){
    for(int i=0; i<this.n; i++){
        for(int j=0; j<this.n; j++){
            Btn newBtn  = new Btn(i, j);
            newBtn.addActionListener(this);
            newBtn.setColor(this.game.colorPicker(i, j));
            newBtn.setBackground(newBtn.getColor());
            this.board[i][j] = newBtn;
            this.panel.add(this.board[i][j]);
        }
    }
}

private void populateBoard(){
    for(int i=0; i<this.n; i++){
        for(int j=0; j<this.n; j++){
                if(this.game.getStatus(i, j) != null){
                    this.board[i][j].setIcon(this.game.getStatus(i, j).getImg());
                }
                else{
                    this.board[i][j].setIcon(null);
                    this.board[i][j].setText("");
                }
            }
        }
}

private void rePaintFrame(){
    this.populateBoard();
}

public static void main(String[] arg){
    ChessGame game = new ChessGame();
    int size = game.board.getSize();

    ViewControl vc = new ViewControl(game, size);

    vc.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    vc.frame.setSize(new Dimension(700, 700));


    vc.add_buttons();

    // Add Titel
    vc.c.gridheight = 1;
    vc.c.gridwidth = 4;

    vc.c.gridx = 0;
    vc.c.gridy = 0;

    vc.contentPanel.add(vc.titel, vc.c);

    // Add Board
    vc.c.gridheight = 4;
    vc.c.gridwidth = 4;

    vc.c.gridx = 0;
    vc.c.gridy = 1;

    vc.contentPanel.add(vc.panel, vc.c);

    // Add all in main Frame
    vc.frame.add(vc.contentPanel);

    vc.frame.setVisible(true);

    vc.rePaintFrame();

}

我们一直认为存在某种Container错误。我们有将JPanels添加到Frames contentPane的线索,但没有任何区别。由于ActionPerformed可以正常工作,因此我们没有将其包含在上面的代码中。我们将感谢您的帮助! :)

0 个答案:

没有答案
相关问题