Make button method if button clicked or not cliked - java

in here i had a lot of button that randomly turn to visible
bt1 = (Button)findViewById(R.id.yellow1);
bt2 = (Button)findViewById(R.id.yellow2);
bt3 = (Button)findViewById(R.id.yellow3);
bt4 = (Button)findViewById(R.id.yellow4);
bt5 = (Button)findViewById(R.id.yellow5);
bt6 = (Button)findViewById(R.id.yellow6);
bt7 = (Button)findViewById(R.id.yellow7);
bt8 = (Button)findViewById(R.id.yellow8);
bt9 = (Button)findViewById(R.id.yellow9);
bt10 = (Button)findViewById(R.id.yellow10);
bt11 = (Button)findViewById(R.id.yellow11);
bt12 = (Button)findViewById(R.id.yellow12);
bt13 = (Button)findViewById(R.id.yellow13);
bt14 = (Button)findViewById(R.id.yellow14);
bt15 = (Button)findViewById(R.id.yellow15);
bt16 = (Button)findViewById(R.id.yellow16);
Button[] buttons = new Button[]{ bt1, bt2, bt3, bt4, bt5, bt6, bt7, bt8,
bt9, bt10, bt11, bt12, bt13, bt14, bt15, bt16 };
Random generator = new Random();
number = generator.nextInt(16);
for( int i=0; i<buttons.length; i++ )
{
if( i == number )
buttons[i].setVisibility( View.VISIBLE );
else
buttons[i].setVisibility( View.INVISIBLE );
}
button is randomly visible, if one turn to visible another one will be invisible. and of course a method if button was "click" to that visible button
if(click==bt1|| click==bt2|| click==bt3|| click==bt4 || click==bt5|| click==bt6|| click==bt7 || click==bt8||
click==bt9|| click==bt10 || click==bt11|| click==bt12|| click==bt13 || click==bt14|| click==bt15|| click==bt16){
//will do something
}
}
but i want to make a method if button "not click" when it is visible, so when button not clicked he will do some code.
i mean is like this
//just example
if button not clicked(click==bt1|| click==bt2|| click==bt3|| click==bt4 || click==bt5|| click==bt6|| click==bt7 || click==bt8||
click==bt9|| click==bt10 || click==bt11|| click==bt12|| click==bt13 || click==bt14|| click==bt15|| click==bt16){
//so do something
}
}
Can anyone teach me how to do that with some code?
NOTE:
Sorry i forget to write some part of the code, it is left on my computer!
So i just can give example like this:
Every 1second the button is randomly set to visible, so every 1second there is randomly button set to visible and the button that visible 1second before will be invisible

Check out this
Handler visibilityToggler = new Handler();
Runnable visivilityRunnable = new Runnable() {
#Override
public void run() {
// isUserClickedButton is used to keep record if user has pressed button within 1 sec
// keep isUserClickedButton = true for first time as it will run
if (!isUserClickedButton) {
// user not pressed button
Toast.makeText(context,"You are not pressed the Button",Toast.LENGHT_LONG).show();
}
// toggle visibility
Random generator = new Random();
number = generator.nextInt(16);
for (int i = 0; i < buttons.length; i++) {
if (i == number)
buttons[i].setVisibility(View.VISIBLE);
else
buttons[i].setVisibility(View.INVISIBLE);
}
// again start the visibility
visibilityToggler.postDelayed(visivilityRunnable,1000);
// make it false as visibility is toggled and we want to track button pressed from start
isUserClickedButton = false;
}
};
visibilityToggler.postDelayed(visivilityRunnable,1000);
Onclick handling if user pressed button
if (click == bt1 || click == bt2 || click == bt3 || click == bt4 || click == bt5 || click == bt6 || click == bt7 || click == bt8 ||
click == bt9 || click == bt10 || click == bt11 || click == bt12 || click == bt13 || click == bt14 || click == bt15 || click == bt16) {
//will do something
// make it true as user is pressed button and we don't want to run condition of not pressed after 1 sec
isUserClickedButton = true;
}
}

b1.setOnClickListener(new View.OnClickListener()
{
Button[] s=new Button[]{bt1, bt2, bt3, bt4, bt5, bt6, bt7, bt8,
bt9, bt10, bt11, bt12, bt13, bt14, bt15, bt16};
Random generator = new Random();
int number = generator.nextInt(16);
#Override
public void onClick(View v) {
for( int i=0; i<s.length; i++ )
{
if( i == number )
s[i].setVisibility(View.VISIBLE);
else
s[i].setVisibility(View.INVISIBLE);
}
}
});

you can define a Boolean value and use onclicklistener for your button, then if user clicks the button the Boolean value will be false and he cannot write code. It's a flag.

Related

Memory Game Action Listener Debugging

After much time spent trying to get my actionlistener to do what I want, Ive come to a few issues debugging that Im just not comprehending.
After finding a correct pair in the game, the first correct pair works properly, disables the two selected buttons, and moves on. After this the comparisons stop working. I can't seem to find out why. After setting up System.out.print checks to see if the programming was progressing through the clicks again it was, but its not allowing another comparison to happen or button reset from the else statement.
Below I've listed my main actionlistener and my pause action listener. Thank you, and if you need more data id be happy to update.
ActionListener timerPause = new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < jToggleLength; i++) {
jToggleButtons[i].setEnabled(true);
tempIconThree = ((ImageIcon)
jToggleButtons[i].getSelectedIcon()).getDescription();
//flip the selected buttons back over
if(jToggleButtons[i].isSelected()){
jToggleButtons[i].doClick();
}
}
}
};
/**
* sets the pause timer period to 1.5 seconds
* sets it to the actionListener Timerpause
*/
pause = new Timer(1500, timerPause);
public void actionPerformed(ActionEvent ae) {
//starts timer
//increments click on each action
pause.stop();
timer.start();
click++;
//if jtogglelength = 0 the user has completed the game and the timer stops
if (jToggleLength == 0) {
timer.stop();
click = 0;
}
//on first click the jtoggle button source is set to temp and the temp icon gets description
if (click == 1) {
temp = (JToggleButton) ae.getSource();
tempIcon = ((ImageIcon) temp.getSelectedIcon()).getDescription();
}
// on click two the jtoggle button source is set to tempTwo and the tempTwo icon gets description
if (click == 2) {
tempTwo = (JToggleButton) ae.getSource();
tempIconTwo = ((ImageIcon) tempTwo.getSelectedIcon()).getDescription();
//if the button is the same button set click to zero and do nothing else
if (temp == tempTwo) {
click = 0;
//if the temp icon descriptions are equivalent move forward
} else if (tempIcon.equals(tempIconTwo)) {
click = 0;
//this for loop sets tempIconThree in every loop to compare to my first two icon descriptions
//if they match, disable that button and set the button to null
//if the button is not null add it to an arraylist
for (int j = 0; j < jToggleLength; j++) {
tempIconThree = ((ImageIcon) jToggleButtons[j].getSelectedIcon()).getDescription();
if (tempIcon.equals(tempIconThree) || tempTwo.equals(tempIconThree)) {
jToggleButtons[j].setEnabled(false);
jToggleButtons[j] = null;
if (jToggleButtons[j] != null) {
arrayEdit.add(jToggleButtons[j]);
}
}
}
//reduce the length of the array by 2
//make a new version of the main jtogglebutton array with reduced length
//add the non null elements from the arrayList to the array
jToggleLength = -2;
for (int k = 0; k < jToggleLength; k++) {
jToggleButtons = new JToggleButton[jToggleLength];
jToggleButtons[k] = arrayEdit.get(k);
}
click = 0;
//if the icon descriptions did not match
//disable all buttons, pause for 1.5 seconds, flip the
selected buttons back up
} else {
for (int i = 0; i < jToggleLength; i++) {
jToggleButtons[i].setEnabled(false);
}
pause.start();
click = 0;
}
}

How to set click limit of clicking a button? click limit is equal to score over 5

How can I set a limit of clicking a button? The number of click is equal to score % 5.Example score is equal to 15 the number of click limit is equal to 3 how can I do that? my codes is not working
int score = 0;
int help = score % 5;
if (score == help) {
helpbtn.setEnabled(false);
} else {
helpbtn.setEnabled(true);
}
I put it inside of
public void onClick(View v) { }
If in the example limit is 3, then :
if(help>0)
{
//logic;
help--;
}
you can add it in else block.
I think I understand what you need now. I've made some assumptions. I added a separate button to submit answers and I added a boolean that is always true for now. I did manage to use modulo in this version though. Hope this helps.
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private int score = 0;
private int help = 0;
private boolean answerCorrect = true; // dummy set always true for now
private Button answerButton = null;
private Button hlpbtn = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
answerButton = (Button)findViewById(R.id.button_answer);
answerButton.setOnClickListener(this);
hlpbtn = (Button)findViewById(R.id.button_help);
hlpbtn.setOnClickListener(this);
hlpbtn.setEnabled(false);
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.button_answer) {
if(answerCorrect) {
if((++score % 5) == 0) {
++help;
}
if((help > 0) && !hlpbtn.isEnabled()) {
hlpbtn.setEnabled(true);
}
}
Log.d("Quiz", "score = " + score + ", help = " + help);
} else if(view.getId() == R.id.button_help) {
if(--help <= 0) {
hlpbtn.setEnabled(false);
Log.d("Quiz", "help button disabled");
}
Log.d("Quiz", "help pressed, " + help + " remaining");
}
}
}
It sounds like you want 15 / 5 instead of 15 % 5.
15 / 5 == 3, whereas 15 % 5 == 0.
15/5 =3. Try this, this will help you to click a button 3 times.
%it gives remainder. Ie --->15%5=0

Selecting buttons at random in java

How can I randomly select a java button, I am trying to create a tic-tac-toe game where the user plays the cpu or another player. I have it working fine for 2 players but am stuck on 1 player game, I dont know if it can be done but my idea is that I just randomly select a button for the cpu check to see if its been selected previously and then assign the appropiate x or o to the selected square .
public void buttonSelected(ActionEvent click) {
Object source = click.getSource();
// loop through to see which button has been selected
if(onePlayer){
// User Vs CPU
/*if((turn % 2 == 0)){// CPU Turn
int selected;
do {
selected = new Random().nextInt(btnEmpty.length );
if (chosen[selected -1] == false){
chosen[selected -1] = true;
}
}while (chosen[selected -1] == true);
source = Integer.valueOf(selected);
for(int i=1; i<= btnNotSelected.length; i++) {
if(source == btnNotSelected[i] && turn < 10) {
btnClicked = true; // user has selected a button
// Check which user selected button and insert appropriate x or y
btnNotSelected[i].setText("X");
btnNotSelected[i].setEnabled(false); // disable selected button
pnlPlayingField.requestFocus(); // highlight selected panel
}
}
}
else{ //User Turn
for(int i=1; i<=9; i++) {
if(source == btnNotSelected[i] && turn < 10) {
btnClicked = true; // user has selected a button
// Check which user selected button and insert O
btnNotSelected[i].setText("O");
btnNotSelected[i].setEnabled(false);
chosen[i] = true;// disable selected button
pnlPlayingField.requestFocus(); // highlight selected panel
}
}
} */
turn++;
}
else if(twoPlayer){
for(int i=1; i<=9; i++) {
if(source == btnNotSelected[i] && turn < 10) {
btnClicked = true; // user has selected a button
// Check which user selected button and insert appropriate x or y
if(turn % 2 == 0){
btnNotSelected[i].setText("X");
}
else{
btnNotSelected[i].setText("O");
}
btnNotSelected[i].setEnabled(false); // disable selected button
pnlPlayingField.requestFocus(); // highlight selected panel
turn++;
}`
A one player tic-tac-toe game can certainly be done, and your strategy of selecting at random is fine. The first specific error in your commented out one player code is an infinite do-while loop. The condition on the loop always evaluates to true since chosen[selected - 1] is always true (if it is false, you set it to true right before the condition check), and therefore loops again.
Your do-while should look like this:
do {
selected = new Random().nextInt(btnEmpty.length);
} while (chosen[selected - 1] == true);
chosen[selected - 1] = true;
That way, you are setting the chosen flag after the while loop condition.
A couple of additional issues I see with the onePlayer block:
in the CPU turn block, the comparison between source (here an Integer) and btnNotSelected[i] (assuming a java button based on the working code in the twoPlayer block) will not work as you expect it to
this method is called in response to a user input, which is clicking one of the buttons. The computer will not provide any such input, so you should have another trigger that calls running the code for the computer's turn. The easiest one is just to run it after the user's turn
Without making any drastic changes to your overall coding style and strategy, I'll attempt to translate the onePlayer portion into something more functional:
public void buttonSelected(ActionEvent click) {
Object source = click.getSource();
if (onePlayer) {
// User's turn first
source.setText("O");
source.setEnabled(false);
pnlPlayingField.requestFocus();
// Mark that button as chosen
for (int i = 0; i < btnNotSelected.length; i++) {
if (source == btnNotSelected[i]) {
chosen[i] = true;
break;
}
}
// Increment turn counter
turn++;
// Check if game is over
if (turn > 9) return;
// CPU turn
int selected;
do {
selected = new Random().nextInt(btnNotSelected.length);
} while (chosen[selected]);
chosen[selected] = true;
btnNotSelected[selected].setText("X");
btnNotSelected[selected].setEnabled(false);
pnlPlayingField.requestFocus();
turn++;
} else if (twoPlayer) {
/* your preexisting twoPlayer code */
}
}
int selected;
do {
selected = new Random().nextInt(btnEmpty.length );
if (chosen[selected -1] == false){
chosen[selected -1] = true;
}
}while (chosen[selected -1] == true);
code above is an endless loop, change it to:
int selected;
do {
selected = new Random().nextInt(btnEmpty.length);
}while (chosen[selected] == true);
chosen[selected] == true;
remove -1, because nextInt(n) will give you a number "between 0 (inclusive) and n (exclusive)"
I, personally, would start out with a List of the buttons, removing each on as it become selected, this would make easier to determine what has being selected and what hasn't, but lets work with what we've got...
List<Integer> free = new ArrayList<Integer>(chosen.length);
for (int index = 0; index < chosen.length; index++) {
if (!chosen[index]) {
free.add(index);
}
}
if (!free.isEmpty()) {
Collections.shuffle(free);
int selected = free.get(0);
// Continue with game logic
}
Basically, this places an Integer in a List which represents the "free" slots. We then use Collections.shuffle to randomise the list, then we grab the first element (for want of something to grab) and continue with the game logic...
This eliminates the possibility of a infinite loop trying to find free slots that don't exist...

Adding values using checkbox?

I am trying to create an enrollment system. I have 6 checkboxes, what I want to happen is if I check one of the checkbox and press the button compute, it should give the label a value of 2640. When I click on another checkbox and press the button compute again the value of the label is 5280 and so on if I click all of the 6 checkboxes.
IF ONE OF THE CHECKBOX IS NOT CLICKED AND I PRESS THE COMPUTE BUTTON, IT SHOULD SUBTRACT 2640 from the current total. Here is my code:
if (chkPLF.isSelected() == true) {
tFee = 2640;
lblMis.setText(Double.toString(misFee));
lblT.setText(Double.toString(tFee + tFee));
if (chkPLF.isSelected() == false) {
tFee = tFee - 2640;
lblMis.setText(Double.toString(misFee));
lblT.setText(Double.toString(tFee));
}
}
if (chkSAD.isSelected() == true) {
tFee = 2640 * 3;
lblMis.setText(Double.toString(misFee));
lblT.setText(Double.toString(tFee));
if (chkSAD.isSelected() == false) {
tFee = tFee - 2640;
lblMis.setText(Double.toString(misFee));
lblT.setText(Double.toString(tFee));
}
}
it only displays the current value but doesn't subtract. PLEASE HELP!
Why not just count the number of checkboxs that are clicked an multiple the result by 2640. Right now, you seem to be overriding the result with each check box...
For example...
int checkCount = 0;
if (chk1.isSelected()) {
checkCount++;
}
if (chk2.isSelected()) {
checkCount++;
}
if (chk3.isSelected()) {
checkCount++;
}
if (chk4.isSelected()) {
checkCount++;
}
if (chk5.isSelected()) {
checkCount++;
}
if (chk6.isSelected()) {
checkCount++;
}
tFee = 2640 * checkCount;
lblMis.setText(Double.toString(misFee));
lblT.setText(Double.toString(tFee));
Right now, I'm going, this could be more easily done with a loop...
JCheckBox[] boxes = new JCheckBox[]{chk1, chk2, chk3, chk4, chk5, chk6};
tFee = 0;
for (JCheckBox box : boxes) {
if (box.isSelected()) {
tFee += 2640;
}
}
lblMis.setText(Double.toString(misFee));
lblT.setText(Double.toString(tFee));
But maybe that's because I'm crazy...
double amount = 0;
int sel = 0;
if(jCheckBox1.isSelected()) sel++;
if(jCheckBox2.isSelected()) sel++;
if(jCheckBox3.isSelected()) sel++;
if(jCheckBox4.isSelected()) sel++;
if(jCheckBox5.isSelected()) sel++;
if(jCheckBox6.isSelected()) sel++;
amount = 2640 * sel;
JOptionPane.showMessageDialog(rootPane, String.valueOf(amount));
Put this code in the "Compute" Click ActionListener

Counter is not counting correctly

I have 8 pairs of buttons (16 total), with some terms from sqlite database. I need when user connect 8 pair (correct or wrong, it does not matter) to end the game, with some popup on the end. When I place counter<7 in my code, i need to connect 8 pairs plus to click once more on some buttons (17 clicks). If I enter counter<6, then I get my popup after 7 pair and one more click(15 click). I don't get that logic. So here's the code:
final OnClickListener clickListener = new OnClickListener() {
private Button buttonClicked;
public void onClick(View v) {
if (counter < 7) {
Button button = (Button) v;
button.getBackground()
.setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0x003333));
if (buttonClicked == null) {
// first button is clicked
buttonClicked = button;
// only do stuff if buttons are in different layouts
} else {
if (!button.getParent().equals(buttonClicked.getParent())) {
// second button is clicked
if (buttonClicked.getTag().equals(button.getTag())) {
// second button is clicked and same tag but different button
Toast.makeText(Spojnice.this, "Correct", Toast.LENGTH_SHORT).show();
button.getBackground()
.setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0x66FF33));
buttonClicked.getBackground().setColorFilter(
new LightingColorFilter(0xFFFFFFFF, 0x66FF33));
buttonClicked.setEnabled(false);
button.setEnabled(false);
buttonClicked = null;
score.setText("Poeni: " + brojPoenaSpojnice);
counter++;
} else {
counter++;
//reset LightingColorFilter first
button.setEnabled(false);
Toast.makeText(Spojnice.this, "Wrong", Toast.LENGTH_SHORT).show();
buttonClicked = null;
}
} else {
//same button clicked show message or un toggle?
buttonClicked = button;
}
}
} else {
Intent i = new Intent(Spojnice.this, Popup_spojnice.class);
startActivity(i);
mHandler.postDelayed(mLaunchTask, 6500);
}
}
};
Since you first check for the counter, and just then increment it, after connecting 7 pairs your counter will be 6 (still <7). Next time you increment the counter it will be 7, and your first condition will be false, but it will only be checked again in the next round.
To solve it, you should check the condition (if (counter < 7)) after incrementing the counter, and not before.

Categories