简体   繁体   中英

Restrict user to only 2 JButtons

I am making a matching game and want to only allow the user to select two cards (JButtons with images). I have 16 jButtons and was wondering on how I would restrict the user to only select 2 of those JButtons.

How the user plays:

They press the play button. Select 2 cards and then press the guess button to check if they are the same. (This is where i want to only allow the user to select 2 cards)

You can disable buttons like this

jButton.setEnabled(false);

So disable the ones you don't want the user to select, or disable all of them and then enable the ones the user can select.

I'm a beginner with events in java, but I would try this based on the explanation you gave: In your event listener for the JButton create a counter that starts at zero and counts up one each time the event listener is executed. As long as the counter is less than two, the rest of your event listener code should run (ie registering a card as selected). Once the counter reaches two, use Jim W's code jButton.setEnabled(false); on the rest of the buttons until the user clicks guess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM