JButton already selected when window loads - infinite loop - java

I have an array of JButtons which are displayed on a window when it is loaded up.
For some reason, when the window loads, the first button seems to be already selected and so puts my programme into an infinite loop.
I know that to stop this infinite loop I should change the condition in my while(true) loop, but am unsure what conditions to put in.
So I thought another way round would be to figure out why one of the buttons is already selected.
actionPerformed method - this gets the name of the button selected which I made to be a string to represent co-ordinates. It then turns the co-ordinates into integers which can be obtained by the HumanPlayer class with the getXInt and getYInt methods. The board and pieces are already set up in other classes, I know it all works because i've already created a text version, this is now the GUI version I am working on.
It's just a case of enabling the user to select a button without the while(true) loop getting stuck.
The Screen class:
public void actionPerformed(ActionEvent e) {
JButton piece = (JButton) e.getSource();
String xy = piece.getName();
String x = xy.substring(0,1);
String y = xy.substring(2,3);
xInt = Integer.parseInt(x);
yInt = Integer.parseInt(y);
}
public int getXInt() {
return xInt;
}
public int getYInt() {
return yInt;
}
HumanPlayer class which gets the information of the piece selected and checks whether it can be moved.
//Sets up new instance of Screen class which is where the window displaying the buttons is set up (this contains the getXInt and getYInt methods are- so the HumanPlayer class can retrieve the piece which has been selected.
Screen s = new Screen(board);
public boolean makeMove() {
int fromXCo , fromYCo, toXCo, toYCo;
Piece p;
ArrayList<Move> moves = null;
while (true){
//reads x and y co-ordinate
System.out.println("Click on a piece to move");
//takes information from which button is clicked from other class
fromXCo = s.getXInt();
fromYCo = s.getYInt();
p = board.getPiece(fromXCo, fromYCo);
System.out.println("Your selected piece is " + p.getChar());
//looks through available moves for piece
moves = p.availableMoves();
//if no moves available, asks for new co-ordinates.
if (moves == null)
{
System.out.println("No moves available for this piece \n");
continue;
}
break;
}
So the output is a continuous:
Click on a piece to move
Your selected piece is r
There are no available moves for this piece...

Related

The cards do not rotate correctly in my video game made in java (swing)

private class Listener implements ActionListener, MouseListener {
#Override
public void mousePressed(MouseEvent eventClick) {
// Recovery Card from JLabel //
JLabel labelCardClicked = (JLabel)eventClick.getSource();
ImageIcon imageCardClicked = (ImageIcon)labelCardClicked.getIcon();
Card clickedCard = getCardWithFileaname(imageCardClicked.getDescription());
// FLIP //
imageCardClicked = new ImageIcon(clickedCard.getLogo());
imageCardClicked.setDescription(clickedCard.getId());
labelCardClicked.setIcon(imageCardClicked);
sameCardPressed(labelCardClicked, clickedCard);
if(numberCardsClicked == 2) {
Boolean status = controller.sameCard(cardsInGame);
//timer.start();
validateGameUser(status); // Problem here
//To be continued ...
}
My program is the typical card game that when you click on a card, it flips over, and if you make a match, they are removed from the GUI.
Well, when you start the game and click on one card, it flips, but when you click on the second one you don't see that effect. I think it's because there's a one second timeout missing before you get to validateGameUser (status);
That's the only reason I see for it to fail me..., the first card flips and we see it, but the second one doesn't .... when I debug with "System.put.println()" I can see that the card flips, but it's not seen in the GUI as in the first card, that's why I think it reaches validateGameUser (state) very fast and you don't notice the change (since they are removed from the GUI). So I was thinking about a timer .... but I don't know how to link it to my program :/

one jbutton doing different actions when clicked again

I need the same JButton to perform a different actions once it's clicked again. Like the first time I click the button, a text will appear in the first row of my JTextField, then the second time I click it, a text will appear in the second row if text field. How should I do it?
Here is my code BTW:
private void addActionPerformed(java.awt.event.ActionEvent evt) {
String items1 =(String)list.getSelectedItem();
String qty1 = qty.getText();
String price1 = price.getText();
int qty2 = Integer.parseInt(qty1);
int price2 = Integer.parseInt(price1);
if(evt.getSource() == add){
order1.setText(Integer.toString(qty2));
order2.setText(Integer.toString(price2));
order3.setText(items1);
}
I literally have no idea what to do next.
Here is the pic for the design GUI: http://prntscr.com/pfh96z
Take a Boolean isClickedOnce and change its state upon clicking on your button
private Boolean isClickedOnce = false;
//..
private void addActionPerformed(java.awt.event.ActionEvent evt) {
if(!isClickedOnce) {
//first click
//..
} else {
//second click
//..
}
isClickedOnce = !isClickedOnce;
}
Note: it'll consider every odd number click as first click and every even number of click as second click. it will toggle through your first and second row.
If your case is different lets say you have n number of rows, above procedure won't work and you might wanna do something similar with a list.

How to keep this skip in memory GoTo Next Iteration in For Loop in java

I am wondering how can you keep this iteration in memory.
I forgot to say that player one can choose any of the five button
I was just using button 1 as a example for player 1.
this is where my problem is cause I can't figure out a way to keep this chosen button which can be any to stay disable(false) after player 2 as chosen is button.
It works if I don't disable all button after player 1 chose is, but the other 4 are enable and if player 1 press one of those button when its player 2 turns everything is mess up.
that's what I'm trying to fix. Help please.
I have 5 button for player 1 and 5 button for player 2.
Let's say button 1 is press for player 1, after its press all the other button is deactivated for player 1 and the others are activated for player 2
When player 2 press it chooses is button, all other of his is deactivated
Here is the tricky part, after player 2 press his button, player 1 button reactivate minus button 1 which was already chosen. This means only 2,3,4 and 5 are activated.
and so on. This must alternate until all 5 button was chosen.
I just can't seem to find, its the tricky part that I can't figure out.
Can anyone help me solve this or any suggestion.
Thanks.
here is the code
//The 2 first for loop are for just showing the 10 buttons
for(int i=0;i<5;i++)
{
x=100*i;
jbChoixJun[i]=new JButton(String.valueOf("Choisir"));
jbChoixJun[i].setBounds(x+30,160,80,30);
add(jbChoixJun[i]);
jbChoixJun[i].addActionListener(this);
jbChoixJun[i].setEnabled(false);
}
for(int i=0;i<5;i++)
{
x=100*i;
jbChoixJdeux[i]=new JButton(String.valueOf("Choisir"));
jbChoixJdeux[i].setBounds(x+30,390,80,30);
add(jbChoixJdeux[i]);
jbChoixJdeux[i].addActionListener(this);
jbChoixJdeux[i].setEnabled(false);
}
//The next 2 for loop, when the player its the button it becomes false and
// stay false until the end, this works ok
for(i=0;i<5;i++)
{
if(source==jbChoixJun[i])
{
mainJoueur1.getCarte(compteurI1);
jbChoixJun[i].setEnabled(false);
compteur1=1;
compteurI1=i;
comparaison1=true;
System.out.println("compteur des images");
System.out.println("compteurI1="+compteurI1);
comparaisonBataille1=true;
}
//This turn all button off after the player chose is
if(jbChoixJun[compteurI1].isEnabled()==false)
jbChoixJun[i].setEnabled(false);
}
for(int i=0;i<5;i++)
{
if(source==jbChoixJdeux[i])
{
mainJoueur2.getCarte(compteurI2);
jbChoixJdeux[i].setEnabled(false);
compteur2=1;
compteurI2=i;
comparaison2=true;
comparaisonBataille2=true;
jbChoixJun[compteurI1].setEnabled(false);
}
if(jbChoixJdeux[compteurI1].isEnabled()==false)
jbChoixJdeux[i].setEnabled(false);
if(i==compteurI1)
continue;
else
jbChoixJun[i].setEnabled(true);
The problem, is that the first button chosen by player comes active and only the second one that becomes disable.
Can of hard to explain
Hope you guys can help me
As asked by the OP here is how you can extend JButton and use it according to your needs by adding new properties, this gives you more flexibility
public class ExtendedJButton extends JButton{
private static final long serialVersionUID = 1L;
/**
* We use this boolean for some case and set it to true or false according to out need
*/
private boolean someCheck;
//Add more propterties according to your need and create conditions to enable and disable them accordingly
public boolean isSomeCheck() {
return someCheck;
}
public void setSomeCheck(boolean someCheck) {
this.someCheck = someCheck;
}
public static void main(String[] args) {
JFrame frameForExample = new JFrame();
ExtendedJButton button = new ExtendedJButton();
frameForExample.add(button);
//Now you can access properties of JButton class as well as new properties of your extended class
button.setEnabled(false);
////.........
//An example case
if(button.isSomeCheck()){
//Do what you want to
//if you want to disable the button when this case is true do it,
}
}
This is not an answer but more a guidance on how you can proceed.

Calling a two dimensional array

I am nowhere near complete with this code it is just a template and I have not finished formatting my code. I am having trouble calling the message part of the array in my other class. I basically have an if/else statement saying when roomId = some#, it will outprint the message the correlates to the # from the array. I am just having trouble understanding how to call the array. Eclipse is throwing me an error in the if/else statement under "grid" saying grid cannot be resolved to a variable. I also tried calling the array method inside the method that the statements are in.Thanks for the help guys.
public class location{
public int roomId;
public String name, message;
public location() {
roomId = 0;
}
public location(String name, int roomId, String message){
this.name = name;
this.roomId = roomId;
this.message = message;
}
public void LocArray() {
location[][] grid = new location[4][4];
grid [1][0] = new location("LABORATORY", 0, "You're in the lab.");
grid [2][0] = new location("DUNGEON", 1, "You entered the dungeon.");
grid [3][0] = new location("COURTYARD ENTRANCE",2,"You have left the dungeon out the backdoor. Either head east and search the courtyard maze, or travel north back to the dungeon");
grid [3][1] = new location("FIRST PATH", 3,"You have now entered the courtyard, either continue east or move north.");
grid [3][2] = new location("DEADEND", 4,"You have reached a deadend that has a Magic Shop. Go inside and explore it.");
grid [3][3] = new location ("MAGIC SHOP", 5, "Search around the Magic Shop and see what there is. When you're done searching continue through the maze.");
grid [2][1] = new location("SECOND PATH",6,"Search the surroundings for items that will help you get into the locked room, then keep moving.");
grid [2][2] = new location("END MAZE", 7, "You've made it to the end of the courtyard. There seems to be a cave in the distance; go check it out.");
grid [1][2] = new location("CAVE",8,"Explore the cave to find the remaining items that will lead to your freedom.");
grid [0][0] = new location("EXIT",9,"This room will lead to your freedom, but you need the three essential items that will open this door.");
}
}
//This is a different class called projectTwo.
while (stillPlaying) {
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine();
if (roomId == 0){
if (userInput.equals("n")) {
System.out.println(grid[2][0].message);
roomId = 1; // Moves user from location 0 to 1
}
grid variable is declared inside the locArray method.
You can't call it in another method or in an another method inside another class.

Mouse Events taking random number of clicks in java

The object of the code so far is the trade turns back and forth between player 1 and player 2 and allow the player whoose turn it is to turn one of their pieces invisible (Set icon to null). It works right now, turns trade back and forth and pieces turn invisible on click, but sometimes it is not the first click. It might take 3 or 4 clicks on a correct piece before it changes to null. Is there a reason this would be happening?
Robo2 is the icon for the first players pieces, robo1 is the icon for the second players pieces. The pieces are stored in an array of JButtons in the program with the icon set as the image of player 1 or player 2 piece.
public void mouseClicked(MouseEvent me) {
JButton clicked = (JButton)me.getSource();
if (player1) {
if (clicked.getIcon() == Robo2) {
clicked.setIcon(null);
player1 = false;
player2 = true;
}
else {
}
}
else if (player2) {
if (clicked.getIcon() == Robo1) {
clicked.setIcon(null);
player1 = true;
player2 = false;
}
else {
}
}
}
Figured out a solution, changing the mouse listener to an action listener solved the missing clicks problems. Using the events sent when the button gets clicked rather than detecting clicks themselves on the button. Thanks for the help.
when you double-click (or triple-click, or quadruple-click) something in Java you get this:
1st click: MouseEvent, clickCount = 1
2nd click: MouseEvent, clickCount = 2
3rd click: MouseEvent, clickCount = 3
etc.
so imagine you're double clicking the button by player1. The first event would change the player to player 2; the second event would change it right back to player1!
To remedy this situation - check clickCount (me.getClickCount()) and ignore the event if it isn't 1. Like
if (me.getClickCount() > 1) {
return;
}
// or else proceed as you do now

Categories