I'm making a very simple game in Java where when you press a button on your keyboard, the corresponding button is removed, however I want the buttons to all be pushed to the bottom accordingly when one is removed. I'm not sure where I should do this in the code or what method to use. Is there a way to sort of pack the frame so that everything is anchored to the bottom?
Here is a picture of the program when it is ran:
And when I press the 3rd button, I want the blocks above it to fall down on top of the rest (similar to other falling block games).
public class Game implements Runnable, KeyListener {
JFrame _frame = new JFrame("Window");
JPanel _pan = new JPanel();
Character[] buttonsToAdd = { 'A', 'B', 'C', 'D' };
List<Character> shuffled = Arrays.asList(buttonsToAdd);
Map<Character, JButton> buttons = new HashMap<Character, JButton>();
@Override
public void run() {
_frame.add(_pan);
_frame.setVisible(true);
_pan.setLayout(new GridLayout(buttonsToAdd.length, 0));
for (char c : buttonsToAdd) {
JButton button = new JButton(c + "");
Collections.shuffle(shuffled);
_pan.add(button);
buttons.put(c, button);
button.addKeyListener(this);
}
_frame.pack();
_frame.setLocationRelativeTo(null);
_frame.setResizable(true);
}
@Override
public void keyTyped(KeyEvent e) { }
@Override
public void keyPressed(KeyEvent e) {
char key = e.getKeyChar();
System.out.println(key);
JButton button = null;
if ((button = buttons.get(Character.toUpperCase(key))) != null) {
_pan.remove(button);
_pan.invalidate();
_frame.repaint();
}
}
@Override
public void keyReleased(KeyEvent e) { }
}
Also, I set the buttons to randomize which letters are used (A-D) but if there are for example, two A buttons, I can only make one removed and pressing A again doesn't remove another. How can I remove both A buttons when A is pressed?
I've been struggling with this for a while, any help would be super appreciated.
Thank you!