我目前正在尝试制作基本的Java Chess游戏,其中ChessBoard初始化并填充ChessSquares。每次我将窗口设置为可见时,除非盘旋,否则每个JButton都不会显示。我该如何阻止它?
器ChessBoard
public class ChessBoard extends JFrame implements ActionListener {
private JPanel p = new JPanel();
private ChessSquare[][] board = new ChessSquare[8][8];
public ChessBoard(){
//Specify frame window.
setSize(640,640);
setTitle("Chess");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add panel to frame window.
p.setLayout(new GridLayout(8,8));
setContentPane(p);
//Populate Chess Board with squares.
for(int y=0; y<8; y++){
for(int x=0; x<8; x++){
board[x][y] = new ChessSquare(x,y);
board[x][y].addActionListener(this);
p.add(board[x][y]);
}
}
//Show window.
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
ChessSquare s = (ChessSquare) e.getSource();
//...
}
}
ChessSquare
import javax.swing.*;
public class ChessSquare extends JButton{
private int x, y;
public ChessSquare(int x, int y){
this.x = x;
this.y = y;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
}
答案 0 :(得分:4)
向@Override
/ getX()
方法添加getY()
表示法,以 获取编译器错误消息。这反过来表明:
最终,我很少看到覆盖组件类的好理由,在这种情况下,它是一个(证明 - 给出结果)坏主意。
此MCVE通过用ChessSquare
类中的标准按钮替换它来支持问题在ChessBoard
组件中。尽管代码中存在一些其他问题(例如,没有调用pack()
并猜测GUI所需的大小,在这种情况下,会导致棋盘,它的工作正常。不是正方形) 1 。
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
public class ChessBoard extends JFrame implements ActionListener {
private JPanel p = new JPanel();
private JButton[][] board = new JButton[8][8];
public ChessBoard() {
//Specify frame window.
setSize(640, 640);
setTitle("Chess");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add panel to frame window.
p.setLayout(new GridLayout(8, 8));
setContentPane(p);
//Populate Chess Board with squares.
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 8; x++) {
board[x][y] = new JButton(x + "," + y);
board[x][y].addActionListener(this);
p.add(board[x][y]);
}
}
//Show window.
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ChessBoard();
}
});
}
public void actionPerformed(ActionEvent e) {
JButton s = (JButton) e.getSource();
//...
}
}