我有一个JLayeredPane
和一个GridBagLayout
布局,其中另一个JPanel
在用户的键盘输入上移动。
一切正常,面板(称为圆点)移动正常,但是在Tile
(表示右下角)的最后Grid
处消失了。之后程序仍然运行,我可以正常将点面板移入和移出此Tile,但它不会出现在屏幕上。
这是我的GridPane
持有Tile
的代码:
public class GridPane extends JLayeredPane {
public int rows;
public int columns;
private List<List<Tile>> tileGrid;
private GridBagConstraints gbc = new GridBagConstraints();
private KeyListener kl = new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_RIGHT:
if(dotTile.column < columns-1)
dotTile = tileGrid.get(dotTile.row).get(dotTile.column+1);
break;
case KeyEvent.VK_LEFT:
if(dotTile.column != 0)
dotTile = tileGrid.get(dotTile.row).get(dotTile.column-1);
break;
case KeyEvent.VK_DOWN:
if(dotTile.row < rows-1)
dotTile = tileGrid.get(dotTile.row+1).get(dotTile.column);
break;
case KeyEvent.VK_UP:
if(dotTile.row != 0)
dotTile = tileGrid.get(dotTile.row-1).get(dotTile.column);
break;
}
//moving the dot
remove(dot);
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridx = dotTile.column;
gbc.gridy = dotTile.row;
add(dot, gbc, 1);
revalidate();
repaint();
}
};
private JPanel dot = new JPanel();
public Tile dotTile;
public GridPane(int rows, int columns) {
this.rows = rows;
this.columns = columns;
setLayout(new GridBagLayout());
addKeyListener(kl);
setFocusable(true);
//fill array and JPanel with Tile
tileGrid = new ArrayList<List<Tile>>(rows);
for (int i = 0; i < rows; i++) {
List<Tile> rowList = new ArrayList<Tile>(columns);
for(int j=0; j < columns; j++) {
Tile t = new Tile(randomColor(), i, j);
rowList.add(t);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = j;
gbc.gridy = i;
add(t, gbc, 0);
}
tileGrid.add(rowList);
}
dot.setPreferredSize(new Dimension(20, 20));
dot.setBackground(Color.BLACK);
//set initial position of dot
dotTile = tileGrid.get(rows/2+1/2).get(columns/2+1/2);
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridx = dotTile.column;
gbc.gridy = dotTile.row;
add(dot, gbc, 1);
repaint();
}
private Random r = new Random();
public Color randomColor() {
return new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
}
Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
private Color gradientColor() {
c = c.darker();
return c;
}
}