【问题标题】:Why won't the color class work on JButton? [closed]为什么颜色类不能在 JButton 上工作? [关闭]
【发布时间】:2021-04-01 18:42:27
【问题描述】:

我正在尝试创建一个棋盘,但由于某种原因它不起作用。

final int HEIGHT = 600;
final int WIDTH = 800;
final int ROW = 8;
final int COL = 8;

String COLS = "ABCDEFGH";
JFrame frame = new JFrame();
JPanel chessBoard = new JPanel();
JButton[][] chessSquares = new JButton[ROW+1][COL+1];

public void initializeGUI() {
    
    
    frame.setSize(WIDTH, HEIGHT);
    frame.setTitle("Chess");
    chessBoard.setLayout(new GridLayout(ROW, COL));
    
    //Creating the chessboard without the pieces
    JButton temp;
    for(int row=1; row<=8; row++) {
        for(int col=1; col<=8; col++) {
            chessSquares[row][col] = new JButton("row: " + row + "col : " + col);
            if ((row+col) % 2 !=  0) {
                temp = chessSquares[row][col];
                temp.setBackground(Color.black);
                chessBoard.add(temp);
            }
            else {
            temp = chessSquares[row][col];
            temp.setBackground(Color.white);
            chessBoard.add(temp);
            }
        }
    }
    
    
    frame.add(chessBoard);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    
}

这是它的样子:

不起作用的事情列表:

  • 有些方块不是黑色的。
  • 棋盘占据了 GUI 的整个空间。 (我希望棋盘占用更少的空间。我尝试使用 BorderLayout.South 但它没有显示整个边框,因为它不可调整大小。)

注意 * row 和 cols 的打印只是为了以后帮助我。不是董事会的一部分。不影响棋盘的颜色(我试过了)

编辑:将 setOpaque 设置为 true 后,我明白了。

有没有办法让整个按钮变黑?

【问题讨论】:

  • 发布的代码对我有用。在线运行here。如果它不适合您,您将不得不提供更多信息。旁注: 1. new JButton[ROW+1][COL+1] 太大。使用new JButton[ROW][COL] 2. 将循环从 `for(int row=1; row
  • @c0der 我需要将它保留在 ROW+1 和 COL+1 以便更轻松地处理事件。我正在制作一个棋盘,其中行和列从 1 开始。另外,我正在使用 MAC。

标签: java swing user-interface jpanel jbutton


【解决方案1】:

有些方块不是黑色的。

我认为这是 Mac LAF 的问题。

查看:How to Set the Background Color of a JButton on the Mac OS

棋盘占据了 GUI 的整个空间。

这就是 BorderLayout 的工作方式。任何添加到 CENTER 的组件都会占用框架的所有未使用空间。

如果您想固定棋盘大小,则需要使用“包装”面板。

类似:

//frame.add(chessBoard);
JPanel wrapper = new JPanel();
wrapper.add( chessBoard );
frame.add(wrapper, BorderLayout.CENTER);

JPanel 的默认布局是 FlowLayout,它将尊重添加到其中的任何组件的首选大小,因此现在按钮将以其首选大小显示。

【讨论】:

  • @RandomKingRD 在此添加此答案是我不久前为任何 OP 可能会发现有用的东西创建的国际象棋游戏示例 stackoverflow.com/a/14626413/1133011 正如您可能看到的那样,我使用了 JLabels 而不是 @987654327 @s 因为它更有意义,您不需要单击一个块,您宁愿单击一个棋子,它将被放置在单击的块上,所以 JButton 是矫枉过正
猜你喜欢
  • 2015-11-14
  • 2021-09-08
  • 2022-07-11
  • 1970-01-01
  • 2019-12-25
  • 2015-03-19
  • 2016-12-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多