0

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:

enter image description here

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).

enter image description here

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!

Dante
  • 59
  • 2
  • 10

1 Answers1

0

You should be able to use a BoxLayout.

Box box = new Box.createVerticalBox();
box.add( Box.createVerticalGlue() );
box.add( button1 );
box.add( button2 );
...

The "glue" will expand as more space is available in the panel. Read the section from the Swing tutorial on How to Use BoxLayout for more information and examples.

Also, don't use a KeyListener. Swing was designed to be used with Key Bindings. See: https://stackoverflow.com/a/33809134/131872 for a working example using this approach.

Community
  • 1
  • 1
camickr
  • 321,443
  • 19
  • 166
  • 288