How to simulate movement of specific JButtons in a JButtons array

I am trying to make a small game in java for a job.

We need to have a resizable grid in the JFrame with nxn (n = some reasonable numbers, like 5 or 7) fields (in this case, each field is a button), and in this field, these are the rules:

The middle button is the black hole and there are 2 players. Each player has N-1 number of ships at their disposal and they must transport them to the black hole. The first player to do so wins. The ships for both players are diagonally aligned towards and away from the middle (black hole).

The trick is that when you tell a ship to go in a direction, it will move in that direction until it hits a wall or another ship.

This is how the game looks at setting up and moving ships around:

enter image description here

My question: I have already successfully made a field with all ships and the black hole in the correct position. They are all buttons and clickable, so now how do I achieve the following:

After I select one button with a mouse click, the system should set focus to it (I tried requestFocus () via an ActionListener, but it doesn't do anything).

Then, after the focus is set, that same button (which already has an ActionListener) will have a KeyListener that waits for arrow keys to be entered. Then after you enter the direction that this button will move its color - mimicking movement - until it hits a ship, wall, or into a black hole when it clears the map.

My question is, how do I make Java know that the keyListener on a specific button should only listen for arrow keys after I have selected the button

and the other is how can I simulate movement?

Basically, both command ships are blue / red. The rest of the blocks are all white, except for the black hole in the middle, which is black.

How do I make it so that when the selected button receives a move command, it changes its setBackGroundColoring so that it moves block-wise until it hits a wall or another ship? I don't even know where to start, so I thought I'd ask for a little help here.

+3


source to share


1 answer


You should also add a KeyListener to the button with the KeyAdapter as an argument, and when the event fires, you can get the key code of the event and check for values:

KeyEvent.VK_UP
KeyEvent.VK_DOWN
KeyEvent.VK_LEFT
KeyEvent.VK_RIGHT

      



And then take the necessary action.

When it comes to motion simulation, do you want the triangle to just jump from button to button, or something more fluid?

+1


source







All Articles