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;
}
}
Related
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.
I have a program that takes an input file, pulls a color word + hexadecimal value from it (for exaple Red 0xFF0000). I had my code working perfectly except I tried to replace my 2 arrayLists with a HashMap... That is where things took a wrong turn. I have my code back to what I believe it was before except now it is NOT changing colors when the radio buttons are pushed. Anyone want to take a peek?
public HashMapTests() {
JPanel p1 = new JPanel();
this.getContentPane().setLayout(new GridLayout(5,4));
ButtonGroup group = new ButtonGroup();
for (int i = 0; i < colorCollection.size(); i++) {
jrbColor[i] = new JRadioButton(colorCollection.get(i));
jrbColor[i].setText(colorCollection.get(i));
group.add(jrbColor[i]);
p1.add(jrbColor[i]);
}
for(int i = 0; i < colorCollection.size(); i++){
jrbColor[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
for (int j = 0; j < colorCollection.size(); j++){
String hexColor = hexCollection.get(j);
if(hexCollection.get(j).equals(((JRadioButton)e.getSource()).getText())){
getContentPane().setBackground(Color.decode(hexColor));
repaint();
}
}
}
});
}
add(p1);
}
First investigation:
while (colorCollection.size() < 10)
shall be replaced with
if (colorCollection.size() < 10)
Second observation:
jrbColor[i] = new JRadioButton(colorCollection.get(i));
jrbColor[i].setText(colorCollection.get(i));
The second line is useless, see constructor's javadoc.
Third:
The second loop where you attach the listener is useless, you can put this code to the first loop where you create a button.
Finally:
if (hexCollection.get(j).equals(((JRadioButton) e.getSource()).getText())) {
You compare here content of hexCollection with radio button text, but the button has label from colorCollection. I cannot look to your file but I think that this will be the problem.
Map Solution:
Initialization
String name = fileInput.next();
String hexValue = fileInput.next();
colors.put(name, hexValue);
Buttons
int i = 0;
for (String s : colors.keySet()) {
jrbColor[i] = new JRadioButton(s);
group.add(jrbColor[i]);
p1.add(jrbColor[i]);
jrbColor[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String hexColor = colors.get(((JRadioButton) e.getSource()).getText());
getContentPane().setBackground(Color.decode(hexColor));
}
});
}
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...
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
How to get the selected index (from a number of jcheckbox added to the screen using for loop) of JCheckbox?.
// for some t values:
checkBoxes[t] = new JCheckBox("Approve");
checkBoxes[t].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean selected = checkBoxes[t].isSelected();
System.out.println("Approved"+selected);
}
});
When i click the check box, i want to get the selected check box's index.
You have an array of JCheckBox, and you can simply iterate through your array and find out which JCheckBox has been selected.
Regarding:
When i click the check box, i want to get the selected check box's index.
Edit: You would find out which checkbox was selected by using the getSource() method of the ActionEvent passed into the ActionListener. For example you could change your ActionListener to as follows:
checkBoxes[t].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean selected = checkBoxes[t].isSelected();
System.out.println("Approved"+selected);
int index = -1;
for (int i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i] == e.getSource()) {
index = i;
// do something with i here
}
}
}
});
As far as I understand, you want to get the index of a selected JCheckBox in order to respond appropriately on a user's action.
If this is the case, you might want to consider a different approach: you can register an ItemListener for each of your checkboxes.
JCheckBox check = new JCheckBox("Approve");
check.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (check.isSelected()){
System.out.println(check.getName() + " is selected");
}
}
});
(inspired by java2s.com tutorial)
In this case the event will be fired immediately and you will always know which checkbox was just clicked.
Iterate throuh the Checkboxes and check the isSelected flag
I would try something like:
for (int i=0; i < checkBoxes.length; i++) {
if (checkBoxes[i].isSelected() == true) {
index = i; }
return index; }
From your question, this is what I gather that you are looking for.
EDIT:
My above previous method is flawed because it makes the very naive approach that one and only one box will be selected and that no box will be deselected.
Where 'e' is the ActionEvent object,
for (int i=0; i < checkBoxes.length; i++) {
if (checkBoxes[i] == e.getSource()) {
index = i; } }
return index;
This way the most recent selection or deselection check box is identified.