我在JButton
上制作了30 * 30 JPanel
,但是当我启动该应用程序时,直到将鼠标悬停在它们上方时,这些按钮才会显示。
我发现此问题主要是在layout设置为null的情况下发生的,我没有这个问题,也没有找到有关此问题的更多信息。
我已经尝试过repaint()
和validate()
,但没有一个起作用。
JPanel:
public class Board extends JPanel implements PropertyChangeListener{
private static final int SIZE_IN_PX = 600;
private GObject[][] field = new GObject[SIZE_IN_PX / 20][SIZE_IN_PX / 20];
private ArrayList<GObject> minesList = new ArrayList<>();
private GridLayout layout = new GridLayout(SIZE_IN_PX / 20, SIZE_IN_PX / 20);
public Board() {
setSize(SIZE_IN_PX, SIZE_IN_PX);
setLayout(layout);
initBoard();
initMines();
}
@Override
public void propertyChange(PropertyChangeEvent arg0) {
return;
}
private void initBoard() {
for (int y = 0; y < SIZE_IN_PX / 20; y++) {
for (int x = 0; x < SIZE_IN_PX / 20; x++) {
field[x][y] = new GObject(x, y, false);
add(field[x][y]);
}
}
}
private void initMines() {
int minesCount = 12;
for (int i = 0; i < minesCount; i++) {
int x = (int)(Math.random() * 30);
int y = (int)(Math.random() * 30);
field[x][y].setMine(true);
System.out.println("x:" + x + ", x:" + y);
}
}
}
JFrame:
public class Window extends javax.swing.JFrame {
public Window() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
board1 = new minesweeper.Board();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("MineSweeper");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(board1, javax.swing.GroupLayout.PREFERRED_SIZE, 600, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(board1, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>
// Variables declaration - do not modify
private minesweeper.Board board1;
// End of variables declaration
}
JButton:
public class GObject extends JButton{
// vlastnosti
private int y;
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
private boolean mine;
public boolean isMine() {
return mine;
}
public void setMine(boolean mine) {
this.mine = mine;
}
private int x;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
// konstruktor
public GObject(int x, int y, boolean mine) {
setY(y);
setMine(mine);
setX(x);
setActionListener();
}
当我启动应用程序并将鼠标从左上角放到中心位置时: