Dynamically change JLabel icons based on x,y of mouse click - java

I am using NETBEANS and have several JLabels that need to display a specific icon/image based on a decision/boolean. I do not want to have to add a mouse listener for every JLabel and then copy and paste the code for each one. Rather I would prefer to use the x,y as the name of the JLabel and then set icon based on the x,y. I have no problems getting the x.y but cannot seem to figure out how to do something like this (xy.setIcon(new ImageIcon(Hit)); here is my code.
/**
* Mathematical coordinates of player1Fleet.
* Used to realign ships from Ship Class
* for use on game board.
*/
public void mouseClicked(MouseEvent e) {
Launch1();
}
public void FleetP1() {
for (Ship s : player1Fleet) {
int size = s.getSize();
for (int i = 0; i < size; i++) {
player1Ships.add((((s.getXCoordinate(i) + 1) * 45) + 90) + "" + (((s.getYCoordinate(i) + 1) * 45) + 180));
}
}
// Verification of Math
System.out.println(player1Ships);
}
/**
* Determine Hit or Miss based on location of Cross-hairs
* for player 1/West on game board.
* #return
*/
//public boolean setStrike1(){
public boolean Launch1() {
w93.setIcon(null);
player1Ships.clear();
FleetP1();
boolean strike1 = false;
boolean Launch = false;
for (int i = 0; i < this.player1Ships.size(); i++) {
if (this.player1Ships.get(i).equals(LblCrossHairs.getX() + "" + LblCrossHairs.getY())) {
strike1 = true;
//break;
}
if (strike1) {
strike1 = true;
(LblCrossHairs.getX() + "" + LblCrossHairs.getY()).setIcon(new ImageIcon(Hit));
//Launch = theAttack.Strike1(strike1);
//w93.setIcon(new ImageIcon(Hit));
URL url = this.getClass().getResource("MissleHit.au");
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("HIT");
break;
} else {
strike1 = false;
(LblCrossHairs.getX() + "" + LblCrossHairs.getY()).setIcon(new ImageIcon(Hit));
//w93.setIcon(new ImageIcon(Miss));
URL url = this.getClass().getResource("MissileMiss.au");
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("MISS");
}
}
TxtClick.setText(LblCrossHairs.getX() + "" + LblCrossHairs.getY() + ".setIcon");
return strike1;
}
Thank you in advance for all your help. This has been driving me crazy for the last two days

I do not want to have to add a mouse listener for every JLabel and then copy and paste the code for each one.
You don't have to create a separate listener. You can share the same listener with every JLabel. The basic code is:
public void mouseClicked(MouseEvent e)
{
JLabel label = (JLabel)e.getSource();
label.setIcon(...);
}

Related

Why does my JButton action listener execute double the amount of times before?

I'm currently setting up a quiz program right now, where the code will loop 20 times. There are 20 question, 80 answers (4 to each question) and the program will set JButtons and action listeners to listen for the user's answer for each question, then call the original quiz loop again from the correct or incorrect answer.
However, the program I'm having is that the program will display question 1, then question 2, but then question 4, 8, 16 and finally 20 since it cannot double anymore.
I've tried:
Breakpointing the value of the currentQuestion variable, as I believe this is the one which is doubling and causing the problem.
Creating a new method named updateQuestionAndAnswer to ensure that it's not a misclick.
Removing the other three action listeners, which helped me to find that it was whatever action listener that I clicked that was repeatedly being called. E.g if it was on Question 8 and I clicked listener 3, it would call listener 3 another 8 times.
I've enclosed the code below I think will be useful. All variables that you cannot see defined within here, are defined to 0 or "" in a static context outside of methods at the top of my program.
* Defines and places all of the content for the Game page.
* #throws IOException
*/
public void setupGamePanel() throws IOException {
// Game page card constructor
card2 = new JPanel() {
// Make the window the specified sizes
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width += extraWindowWidth;
size.height += extraWindowHeight;
return size;
}
};
// JAVA COMPONENT DEFINITIONS
String[] openingDialogue = new String[]{"<html><span style='font-size:20px;'>We need your help. After Junko Enoshima took over Hope’s Peak Academy, she trapped the entire of Class 78 inside a monstrous killing game! My creator, Chihiro Fujisaki, is one of them.", "<html><span style='font-size:20px;'>I managed to patch into the systems that the Ultimate ******** setup when he fell into despair, but we’ve been hit with a security system implemented by Jin Kirigiri before he…", "<html><span style='font-size:20px;'>Anyway, we need to get a good enough score out of twenty quiz questions in order to get inside the network, where my creator should be waiting for me.", "<html><span style='font-size:20px;'>Let’s do this. Answer the questions as best as you can. Good luck.", ""};
// Score counter
scoreCounter.setText("<html><span style='font-size:30px;'>Score: " + String.valueOf(score) + "</html>");
// Alter ego dialogue text
dialogueText = new JLabel("");
dialogueText.setText("<html><span style='font-size:20px;'>You’re...actually here? You survived. You're inside the first versions of the Neo World Program!</html>");
// Buttons
beginButton = new JButton("BEGIN THE GAME!");
continueButton = new JButton("Continue Dialogue");
// Images
alterEgoImage = ImageIO.read(new File("AlterEgo/alterego.png"));
BufferedImage alterEgoNeutral = ImageIO.read(new File("AlterEgo/neutral.jpeg"));
alterEgoImageLabel = new JLabel(new ImageIcon(alterEgoImage));
// X, Y. Width, Height
alterEgoImageLabel.setBounds(510, 150, 550, 300);
scoreCounter.setBounds(15, 15, 250, 40);
beginButton.setBounds(650, 480, 250, 40);
continueButton.setBounds(650, 480, 250, 40);
dialogueText.setBounds(500, 490, 750, 300);
// Allows for a more dynamic and fluid layout of the page where bounds are specified.
card2.setLayout(null);
// Add the components to the page
card2.add(beginButton);
card2.add(continueButton);
card2.add(dialogueText);
card2.add(scoreCounter);
card2.add(alterEgoImageLabel);
continueButton.setVisible(false);
dialogueText.setVisible(false);
// BEGIN THE QUIZ GAME
// Game begins when the button is clicked
beginButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
beginButton.setVisible(false);
continueButton.setVisible(true);
dialogueText.setVisible(true);
}
});
// Continue the opening dialogue with the continue button, and immediately begin the quiz after the dialogue has finished.
continueButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dialogueText.setText(openingDialogue[openDialoguePos]);
openDialoguePos++;
if(openDialoguePos == openingDialogue.length) {
continueButton.setVisible(false);
dialogueText.setVisible(false);
// SET THE ALTER EGO IMAGE TO THE NEUTRAL ONE TO BEGIN THE GAME
try {
quizProcess();
} catch(IOException excep) {
// Handle the error here
}
//quizProcess();
}
}
});
} // end setupGamePanel()
/**
* Defines and places all of the content for the leaderboard page.
* #throws IOException
*/
public void setupLeaderboardPanel() throws IOException {
// Leaderboard page card constructor
card3 = new JPanel();
card3.add(new JTextField("TextField", 20));
} // end setupLeaderboardPanel()
/**
* The top level method for the quiz game.
* #throws IOException
*/
public void quizProcess() throws IOException {
// TOP LEVEL METHOD BEGINS
setupQuizUI(answerButtons);
readData(questions, answers);
quizLoop(questions, answers, answerButtons);
}
public void quizLoop(String questions[], String[] answers, JButton[] answerButtons) {
System.out.println("A quiz loop is being initiated");
moveOntoNextQuestion(questions, answers, answerButtons);
//assignData();
checkCorrectQuestion(answerButtons);
}
/**
* Initialise and setup the answer buttons and question text.
*/
public void setupQuizUI(JButton[] answerButtons) {
// Alter ego dialogue text
questionText.setText("<html><span style='font-size:20px;'<</html>");
questionText.setBounds(550, 450, 350, 150);
card2.add(questionText);
//System.out.println("Fifth read: " + currentQuestion + 25);
for(int i = 0; i < answerButtons.length; i++) {
answerButtons[i] = new JButton("Test");
}
// Bound setting (X, Y, Width, Height)
answerButtons[0].setBounds(150, 580, 200, 100);
answerButtons[1].setBounds(550, 580, 200, 100);
answerButtons[2].setBounds(950, 580, 200, 100);
answerButtons[3].setBounds(1350, 580, 200, 100);
// Adding to the JFrame
card2.add(answerButtons[0]);
card2.add(answerButtons[1]);
card2.add(answerButtons[2]);
card2.add(answerButtons[3]);
}
/**
* Read in the data from the database to the arrays.
* #param
*/
public void readData(String[] questions, String[] answers) {
//System.out.println("First read: " + currentQuestion + 5);
questions[0] = "Question 1";
questions[1] = "Question 2";
for(int i = 0; i < questions.length; i++) {
questions[i] = "Question " + (i + 1);
}
for(int i = 0; i < answers.length; i++) {
answers[i] = "Answer" + (i + 1);
}
for(int i = 0; i < correctAnswers.length; i+= 4) {
correctAnswers[i] = 0;
correctAnswers[i + 1] = 1;
correctAnswers[i + 2] = 2;
correctAnswers[i + 3] = 3;
}
/*answers[0] = "Answer 1";
answers[1] = "Answer 2";
answers[2] = "Answer 3";
answers[3] = "Answer 4";
answers[4] = "Answer 5";
answers[5] = "Answer 6";
answers[6] = "Answer 7";
answers[7] = "Answer 8";*/
}
/**
*
* Moves onto the next question and prepares the data for read-in
* Assign the next question to the text field
* Assign the next answers to the buttons
*/
public void moveOntoNextQuestion(String questions[], String[] answers, JButton[] answerButtons) {
//System.out.println("-=-=-=-=-=-=-moveOntoNextQuestion-=-=-=-=-=-=-=-");
String nextQuestion = questions[currentQuestion];
questionText.setText(questions[currentQuestion]);
//System.out.println("The current question is " + questions[currentQuestion]);
//System.out.println("The current answer number is " + currentAnswer);
answerButtons[0].setText(answers[currentAnswer]);
answerButtons[1].setText(answers[currentAnswer + 1]);
answerButtons[2].setText(answers[currentAnswer + 2]);
answerButtons[3].setText(answers[currentAnswer + 3]);
//System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
}
/**
* #param answer
* Check if the clicked answer was correct.
*/
public void checkCorrectQuestion(JButton[] answerButtons) {
int correctAnswer = correctAnswers[currentQuestion];
//System.out.println("Current correct answer is " + correctAnswer);
answerButtons[0].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(correctAnswer == 0) {
System.out.println("Button 1 is correct!");
score += 10;
updateScore(scoreCounter);
try {
correctAnswerAlterEgo(alterEgoImage, alterEgoImageLabel);
} catch(IOException excep) {
// Handle the error here
}
} else {
System.out.println("Button 1 is wrong!");
score -= 5;
updateScore(scoreCounter);
}
updateQuestionAndAnswer();
//currentQuestion += 1;
//System.out.println("currentQuestion value is " + currentQuestion);
//currentAnswer += 4;
//System.out.println("This is the quizLoop for button 1");
quizLoop(questions, answers, answerButtons);
}
});
**WITHIN HERE ARE THE OTHER THREE ACTION LISTENERS FOR THE BUTTONS. THEY ARE THE EXACT SAME EXCEPT [1], [2] and [3].**
}
public void updateQuestionAndAnswer() {
currentQuestion = currentQuestion + 1;
currentAnswer = currentAnswer + 4;
}
public void updateScore(JLabel scoreCounter) {
scoreCounter.setText("<html><span style='font-size:30px;'>Score: " + String.valueOf(score) + "</html>");
}
public void correctAnswerAlterEgo(BufferedImage alterEgoImage, JLabel alterEgoImageLabel) throws IOException {
System.out.println("Correct answer alter ego method called!");
scoreCounter.setText("<html><span style='font-size:30px;'>TEST: </html>");
// Images
BufferedImage[] happyImages = new BufferedImage[]{ ImageIO.read(new File("AlterEgo/excited.jpeg")), ImageIO.read(new File("AlterEgo/happy.jpeg")), ImageIO.read(new File("AlterEgo/shocked.jpeg"))};
alterEgoImage = ImageIO.read(new File("AlterEgo/class78.jpg"));
alterEgoImageLabel = new JLabel(new ImageIcon(alterEgoImage));
card2.add(alterEgoImageLabel);
card2.remove(alterEgoImageLabel);
}
public void wrongAnswerAlterEgo() {
}```
Thank you for your help,

How to find an object on certain coordinates in java

I'm a beginner when it comes to Java and I'm trying to find a way to see if an object is located on certain coordinates. I've tried to search for similar questions, but I still haven't found an answer.
The program I'm working on is a map (image file) and the user should be able to create places and place them on the map (which will be displayed as triangles on the map). There is also this function where the user should be able to type in coordinates to see if there already is a place on those coordinates.
The object is an object of the class "Place" and consists a name, an x-coordinate and an y-coordinate.
Here is my code:
class CoordinatesListener implements ActionListener {
public void actionPerformed(ActionEvent ave) {
try {
CoordinatesForm c = new CoordinatesForm();
int answer = c.getAnswer();
if (answer != JOptionPane.OK_OPTION) {
return;
}
if (c.getPosition() == null) {
JOptionPane.showMessageDialog(null, "Invalid Input kkk", "Invalid Input", JOptionPane.ERROR_MESSAGE);
} else {
Position p = c.getPosition();
boolean flag = false;
for (Position key : positionList.keySet()) {
if (key.getXCoordinate() == p.getXCoordinate() && key.getYCoordinate() == p.getYCoordinate()) {
flag = true;
this.setAllMarkedPlacesUnMarked();
Place place = positionList.get(key);
if (place != null) {
System.out.println("the place " + place + "against position " + key);
place.setMarked(true);
if (!place.isVisible()) {
place.setVisible(true);
}
markedPlacesHashMap.put(place.getName(), place);
if (markedPlacesHashMap.containsKey(place.getName())) {
markedPlacesHashMap.get(place.getName()).add(place);
} else {
// ArrayList<Place> newMarkedPlaces = new ArrayList<>();
// newMarkedPlaces.add(place);
markedPlacesHashMap.put(place.getName(), place);
}
}
}
}
Also, when a place is created, the user shouldn't be able to place another place on the same coordinates. There should be an error message saying that a place already exists on those coordinates.
Here is the code where a place is created:
private void createNamedPlace(int x, int y, String answer) {
Position pos = new Position(x, y);
display.add(n = new NamedPlace(selectedCategory, pos, answer));
p = n;
places = new ArrayList<>();
placeByCategory = new ArrayList<>();
positionList.put(pos, n);
if (categoryMap.containsKey(selectedCategory)) {
categoryMap.get(selectedCategory).add(n);
if (nameList.containsKey(answer)) {
nameList.get(answer).add(n);
} else {
places.add(n);
nameList.put(answer, places);
}
} else {
placeByCategory.add(n);
categoryMap.put(selectedCategory, placeByCategory);
if (nameList.containsKey(answer)) {
nameList.get(answer).add(n);
System.out.println("The new Place have been added in the Name
List, the place name is :" + answer);
this.displayMap(nameList, " PlACES LIST BY NAME");
} else {
places.add(n);
nameList.put(answer, places);
this.displayMap(nameList, "PLACES LIST BY NAME");
}
this.displayMap(categoryMap, " PlACES LIST BY CATEGORY");
}
n.addMouseListener(new TriangleListener());
display.validate();
display.repaint();
display.removeMouseListener(mouseListener);
display.setCursor(Cursor.getDefaultCursor());
newButton.setEnabled(true);
categoryList.clearSelection();
isSaved = false;
}
All Swing components are ultimately derived from the Component class, which has a method getBounds(), returning a rectangle. So you can simply write something like
if (myComponent.getBounds().contains(x,y)) {
// do something
where x and y are the co-ordinates of the point you're trying to check.

Why does my firstCardClicked.setDisabledIcon(img) work, but my secondCardClicked.setDisabledIcon(img) not work?

I am building a Java Swing Memory Game. The idea is to click on the first card, it changes the image from a baseImage to another image. When the second card is clicked, it is supposed to do the same thing, wait for a few seconds, then reset everything back to base if they don't match or keep them flipped over if they do.
Right now, if they do not match, the second card never changes the image. Below is the relevant code. It should be noted that if they do match, the image shows and all is right and good in the world.
public void cardClickHandler(ActionEvent ae) {
JButton card = new JButton();
card = (JButton) ae.getSource();
// disable the card that was clicked
card.setEnabled(false);
// behavior for first card clicked
if (clickCounter == 0) {
firstCardClicked = card;
img = new ImageIcon("images2/img" + firstCardClicked.getName() + ".jpg");
firstCardClicked.setDisabledIcon(img);
System.out.println("Button " + firstCardClicked.getName() + " clicked!");
clickCounter++;
}
// behavior for second card clicked
else {
secondCardClicked = card;
img = new ImageIcon("images2/img" + secondCardClicked.getName() + ".jpg");
secondCardClicked.setDisabledIcon(img);
System.out.println("Button " + secondCardClicked.getName() + " clicked!");
clickCounter--;
}
// behavior if two cards have been clicked and they match
if (firstCardClicked.getName().equals(secondCardClicked.getName()) && clickCounter == 0) {
// player turn control and scoring
if (p1Turn) {
p1NumScore++;
p1Score.setText(Integer.toString(p1NumScore));
scorePanel.revalidate();
System.out.println("Good job Mike, got a pair!");
p1Turn = !p1Turn;
}
else {
p2NumScore++;
p2Score.setText(Integer.toString(p2NumScore));
scorePanel.revalidate();
System.out.println("Good job Peanut, got a pair!");
p1Turn = !p1Turn;
}
}
// behavior if two cards have been clicked and they do not match
else if (!(firstCardClicked.getName().equals(secondCardClicked.getName())) && clickCounter == 0) {
// keep cards flipped for a few seconds
try {
System.out.println("Before Sleep"); // testing
Thread.sleep(2000);
System.out.println("After Sleep"); // testing
}
catch (Exception e) {
e.printStackTrace();
}
// enable the cards and reset images
firstCardClicked.setEnabled(true);
firstCardClicked.setIcon(baseImage);
secondCardClicked.setEnabled(true);
secondCardClicked.setIcon(baseImage);
// change turns
p1Turn = !p1Turn;
System.out.println("Keep Playing");
}
}
It looks as though there were a few problems working at the same time. Thread.sleep() was causing havoc in conjunction with the .setEnabled(true) commands. The state of the objects were in question so I needed to clear them at the end of the code. There are some known issues with .setDisabledIcon() method that many posts here say require a .setIcon() to preceed it. Here is the fixed code that works with the javax.swing.Timer being used.
public void cardClickHandler(ActionEvent ae)
{
// method variables
JButton card = (JButton) ae.getSource();
boolean clearState = false;
// behavior for first card clicked
if (isFirstCard)
{
firstCardClicked = card;
// a known issue with "setDisabledIcon()" required the "setIcon()" method
firstCardClicked.setIcon(new ImageIcon("images2/img" + firstCardClicked.getName() + ".jpg"));
firstCardClicked.setDisabledIcon(new ImageIcon("images2/img" + firstCardClicked.getName() + ".jpg"));
// disable the flipped card
firstCardClicked.setEnabled(false);
// indicate the next card clicked is the second card
isFirstCard = false;
}
// behavior for second card clicked
else
{
secondCardClicked = card;
// a known issue with "setDisabledIcon()" required the "setIcon()" method
secondCardClicked.setIcon(new ImageIcon("images2/img" + secondCardClicked.getName() + ".jpg"));
secondCardClicked.setDisabledIcon(new ImageIcon("images2/img" + secondCardClicked.getName() + ".jpg"));
// disable the flipped card
secondCardClicked.setEnabled(false);
// indicate the next card clicked is the first card again
isFirstCard = true;
// indicate to the system both cards have been clicked and can clear objects
clearState = true;
}
// behavior if two cards have been clicked and they match
if (isFirstCard && firstCardClicked.getName().equals(secondCardClicked.getName()))
{
// player turn control and scoring
if (p1Turn)
{
p1NumScore++;
p1Score.setText(Integer.toString(p1NumScore));
scorePanel.revalidate();
p1Turn = !p1Turn;
}
else
{
p2NumScore++;
p2Score.setText(Integer.toString(p2NumScore));
scorePanel.revalidate();
p1Turn = !p1Turn;
}
}
// behavior if two cards have been clicked and they do not match
else if (isFirstCard && !(firstCardClicked.getName().equals(secondCardClicked.getName())) )
{
// enable the cards and reset images
firstCardClicked.setIcon(BASE_IMAGE);
secondCardClicked.setIcon(BASE_IMAGE);
// change turns
p1Turn = !p1Turn;
}
if (clearState)
{
javax.swing.Timer timer = new javax.swing.Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
firstCardClicked.setEnabled(true);
secondCardClicked.setEnabled(true);
isFirstCard = true;
firstCardClicked = null;
secondCardClicked = null;
}
});
// Normally the timer's actionPerformed method executes repeatedly. Tell it only to execute once.
timer.setRepeats(false);
// Start the timer.
timer.start();
}
}

Knight's Tour GUI in Processing

I am working on a knight's tour problem with basic gui,i want to take user input in the two text fields which make up the (x,y) from user and then in one text box i print if solution is posiible and in the other i write the path adopted by the knight.My algorithm works fine and i have problem in gui.i have given a few default values to (x,y) for that i get correct output .But when i change the value of (x,y) in the textfield,no change occurs.this is the main file ,there is another event handler file,which is below it.Your help will be sincerely appreciated.I am working on processing 2.2.1.This is how the output screen looks like
Main file/project.pde
// Need G4P library
import g4p_controls.*;
Maxim maxim;
AudioPlayer player;
int x=-1;
int y=-1;
String solution="";
PImage img;
int count=0;
public void setup(){
size(480, 320, JAVA2D);
maxim=new Maxim(this);
player=maxim.loadFile("song.wav");
player.setLooping(true);
img=loadImage("chess.jpg");
createGUI();
customGUI();
// Place your setup code here
}
int t[]=new int[25];
boolean visited[][]=new boolean[5][5];
int check[][]=new int[5][5];
boolean b;
int counter=-1;
boolean move(int x,int y , int m){
boolean result=false;
if (x<0 || x>=5 || y<0 || y>=5 || visited[x][y]==true)
{
return false;
}
visited[x][y]=true;
if (m==24)
{
visited[x][y]=true;
return true;
}
else
{
String xstring=String.valueOf(x);
String ystring=String.valueOf(y);
solution=solution+xstring+","+ystring+" ";
print (x);
print(",");
print(y);
check[x][y]=counter+1;
if (move(x+2,y+1,m+1) || move(x+2,y-1,m+1)
|| move(x-2,y+1,m+1) || move(x-2,y-1,m+1)
|| move(x+1,y+1,m+1) || move(x+1,y-1,m+1)
|| move(x-1,y+1,m+1) || move(x-1,y-1,m+1)){
print (x);
print(",");
print(y);
//check[x][y]=1;
return true;
}
return false;
}
}
public void draw(){
counter=counter+1;
background(0,128,128);
image(img,0,0,480,320);
player.play();
textarea2.setText(solution);
String txt1 = textfield1.getText();
x = Integer.parseInt(txt1);
String txt2 = textfield2.getText();
y= Integer.parseInt(txt2);
print(solution);
if(x>=0 && y>=0)
{
b=move(x,y,0);
if(b==false)
{
textarea1.setText("Solution is not possible,enter other coordinates");
}
if(b==true)
{
textarea1.setText("Congratulations solution is possible");
}
}
if(count%8==0)
{
delay(1000);
println(counter);
}
}
void keyPressed()
{
if (key==13)
{
solution="";
print(solution);
textarea2.setText(solution);
String txt1 = textfield1.getText();
x = Integer.parseInt(txt1);
String txt2 = textfield2.getText();
y= Integer.parseInt(txt2);
}
if(x>=0 && y>=0)
{
b=move(x,y,0);
if(b==false)
{
textarea1.setText("Solution is not possible,enter other coordinates");
}
if(b==true)
{
textarea1.setText("Congratulations solution is possible");
}
}
}
// Use this method to add additional statements
// to customise the GUI controls
public void customGUI(){
}
this is the event handlers file
/* =========================================================
* ==== WARNING ===
* =========================================================
* The code in this tab has been generated from the GUI form
* designer and care should be taken when editing this file.
* Only add/edit code inside the event handlers i.e. only
* use lines between the matching comment tags. e.g.
void myBtnEvents(GButton button) { //_CODE_:button1:12356:
// It is safe to enter your event code here
} //_CODE_:button1:12356:
* Do not rename this tab!
* =========================================================
*/
public void tf1(GTextField source, GEvent event) { //_CODE_:textfield1:418637:
println("textfield1 - GTextField >> GEvent." + event + " # " + millis());
} //_CODE_:textfield1:418637:
public void tf2(GTextField source, GEvent event) { //_CODE_:textfield2:859413:
println("textfield2 - GTextField >> GEvent." + event + " # " + millis());
} //_CODE_:textfield2:859413:
public void ta1(GTextArea source, GEvent event) { //_CODE_:textarea1:252891:
println("textarea1 - GTextArea >> GEvent." + event + " # " + millis());
} //_CODE_:textarea1:252891:
public void ta2(GTextArea source, GEvent event) { //_CODE_:textarea2:483845:
println("textarea2 - GTextArea >> GEvent." + event + " # " + millis());
} //_CODE_:textarea2:483845:
public void slider1_change1(GSlider source, GEvent event) { //_CODE_:slider1:280049:
println("slider1 - GSlider >> GEvent." + event + " # " + millis());
} //_CODE_:slider1:280049:
public void slider2_change1(GSlider source, GEvent event) { //_CODE_:slider2:362722:
println("slider2 - GSlider >> GEvent." + event + " # " + millis());
} //_CODE_:slider2:362722:
// Create all the GUI controls.
// autogenerated do not edit
public void createGUI(){
G4P.messagesEnabled(false);
G4P.setGlobalColorScheme(GCScheme.BLUE_SCHEME);
G4P.setCursor(ARROW);
if(frame != null)
frame.setTitle("Sketch Window");
textfield1 = new GTextField(this, 210, 32, 160, 30, G4P.SCROLLBARS_NONE);
textfield1.setText("1");
textfield1.setPromptText("Enter x-Cordinate");
textfield1.setOpaque(true);
textfield1.addEventHandler(this, "tf1");
textfield2 = new GTextField(this, 204, 96, 160, 30, G4P.SCROLLBARS_NONE);
textfield2.setText("1");
textfield2.setPromptText("Enter y Cordinate");
textfield2.setLocalColorScheme(GCScheme.PURPLE_SCHEME);
textfield2.setOpaque(true);
textfield2.addEventHandler(this, "tf2");
textarea1 = new GTextArea(this, 53, 196, 160, 80, G4P.SCROLLBARS_NONE);
textarea1.setLocalColorScheme(GCScheme.GREEN_SCHEME);
textarea1.setOpaque(true);
textarea1.addEventHandler(this, "ta1");
textarea2 = new GTextArea(this, 288, 192, 160, 80, G4P.SCROLLBARS_NONE);
textarea2.setLocalColorScheme(GCScheme.YELLOW_SCHEME);
textarea2.setOpaque(true);
textarea2.addEventHandler(this, "ta2");
slider1 = new GSlider(this, 96, 276, 264, 40, 10.0);
slider1.setLimits(0.5, 0.0, 1.0);
slider1.setNumberFormat(G4P.DECIMAL, 2);
slider1.setOpaque(false);
slider1.addEventHandler(this, "slider1_change1");
slider2 = new GSlider(this, 348, 240, 100, 36, 10.0);
slider2.setLimits(0.5, 0.0, 1.0);
slider2.setNumberFormat(G4P.DECIMAL, 2);
slider2.setOpaque(false);
slider2.addEventHandler(this, "slider2_change1");
}
// Variable declarations
// autogenerated do not edit
GTextField textfield1;
GTextField textfield2;
GTextArea textarea1;
GTextArea textarea2;
GSlider slider1;
GSlider slider2;
There are some problems with above constructions.
You do recursive move() method inside draw() method. But in Processing draw() is called many times in each second by animation thread.
Common desing for such cases is:
you should have variables that hold application state (logical state)
what your draw() method draws depends only on state
state may be modified by animation thread or by any other thread
I suggest changing your code a little:
First - state variables:
// 1 - display status, wait to enter values
// 2 - check if x and y are correct
// 3 - solve problem
int state=1;
boolean solutionExists=false;
public void setup() {
...
}
next draw() method:
void draw() {
counter=counter+1;
background(0,128,128);
String coords = "(" + x + "," + y + ")";
if (state == 1) {
if(solutionExists) {
textarea1.setText("Congratulations solution is possible " + coords);
} else {
textarea1.setText("Solution is not possible,enter other coordinates " +coords);
}
return;
}
if (state == 2) {
readXY();
return;
}
if (state == 3) {
println("find solution for: " + coords);
solutionExists = move(x,y,0);
state = 1;
return;
}
}
public void readXY() {
try {
x = Integer.parseInt(textfield1.getText().trim());
y = Integer.parseInt(textfield2.getText().trim());
state = 3;
} catch(Exception e) {
state = 1;
}
}
and finally textfields handlers:
public void tf1(GTextField source, GEvent event) {
if (event.getType().equals("LOST_FOCUS")) {
state=2;
}
}
public void tf2(GTextField source, GEvent event) {
if (event.getType().equals("LOST_FOCUS")) {
state=2;
}
}
As you can see:
if state==1 - draw() only updates message
if state==2 - draw() checks if x and y are valid, if valid -> change state to 3
if state==3 - draw() performs recursive algo, update solutionExists variable, change state to 1
Anytime when your textfield1 or textfield2 loose focus, it changes state to 2.
draw() is driven only by application state.
application state is modified by other events.
For best results, recursive algo should be performat in another thread, not in animation thread.
One fine note: when you edit textfield it may contains string such as "" (empty) or " 3" (leading space) or " 3 " etc - such text cannot be parsed with Integer.parseInt - you need to trim such text and be sure that NumberFormatException is not thrown - see readXY() method.

pattern when using Math.random

I am trying to have a mouse go through rooms to a target room. I am using a graph-like system with an x and y axis. I have a problem where the computer doesn't seem to want to add or subtract from an already existing variable.
Console:
The mouse is in room (5,4)
The mouse is in room (5,6)
The mouse is in room (6,5)
The mouse is in room (5,4)
The mouse is in room (5,6)
The mouse is in room (5,6)
Code for mouse:
package mouse_maze;
public class Mouse {
private int xCord = 5;
private int yCord = 5;
//position of the mouse when it starts
public int getXCord() {
return this.xCord;
}
public int getYCord() {
return this.yCord;
}
public void move() {
//method for the movement of the mouse
boolean verticalMove = Math.random() < .5;
boolean horizontalMove;
if (verticalMove == true)
horizontalMove = false;
else
horizontalMove = true;
int moveBy = 1;
if (Math.random() < .5)
moveBy = -1;
if (verticalMove) {
int test = this.yCord + moveBy;
if(test < 1 || test > 9) return;
this.yCord += moveBy;
}
if (horizontalMove) {
int test = this.xCord + moveBy;
if(test < 1 || test > 9) return;
this.xCord += moveBy;
}
System.out.println("The mouse is in room (" + xCord + "," + yCord + ")");
}
}
Code for maze:
package mouse_maze;
public class Maze {
private boolean onGoing = false;
private int tarX;
private int tarY;
//creates the target for the mouse.
public static void main(String[] args) {
new Maze(6, 8).init();
}
public Maze(int tarX, int tarY) {
this.tarX = tarX;
this.tarY = tarY;
}
public void init() {
this.onGoing = true;
while(this.onGoing)
this.iterate();
}
public void iterate() {
Mouse m = new Mouse();
m.move();
if (m.getXCord() == tarX && m.getYCord() == tarY) {
this.onGoing = false;
System.out.println("The mouse has beat the maze!");
//checks if the mouse has gotten to the target room.
}
}
}
First, learn to use a debugger, or at least learn to debug by whatever means. It is meaningless to always "assume" the problem without actually proving it.
Your whole problem has nothing to do with random etc.
In your iterate() method, you are creating a new mouse every time, instead of having the same mouse keep on moving.

Categories

Resources