Re: ActionListener question
Consider creating and posting a very small, simple compilable and runnable program that shows your problem, an SSCCE.
Re: ActionListener question
Ok, so here's a little app. Right now I have each text field hold the number of the index which I use to compare with the location of Waldo. I'd like to be able to reference the TextField's index (if that's possible). If not, is there a more elegant way that I could do this. I'd like to extend this out to a multi-dimentional array of TextFields.
Code:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class WhereIsWaldo extends JFrame implements FocusListener {
private JPanel contentPane;
private JPanel gridPane;
private JPanel messagePane;
int waldoIsHere = (int) (Math.random()*5); //generate a random number between 0-4
ASimpleClass dot;
JLabel msg;
public WhereIsWaldo() {
super("Where is Waldo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
gridPane = new JPanel();
JTextField[] loc = new JTextField[5];
for(int i=0; i<loc.length;i++){
loc[i] = new JTextField(""+i,3);
loc[i].addFocusListener(this);
gridPane.add(loc[i]);
}
messagePane = new JPanel();
msg = new JLabel("Where is Waldo?.");
messagePane.add(msg);
contentPane.add("North", gridPane);
contentPane.add("South", messagePane);
setVisible(true);
dot = new ASimpleClass();
dot.setLocation(waldoIsHere);
}
public void focusGained(FocusEvent e){
JTextField source = (JTextField)e.getComponent();
if (dot.getLocation()==Integer.parseInt(source.getText())){
msg.setText("You've found Waldo!");
} else{
msg.setText("Try Again!");
}
}
public void focusLost(FocusEvent e){
}
public static void main(String[] args) {
WhereIsWaldo frame = new WhereIsWaldo();
frame.setVisible(true);
}
}
class ASimpleClass{
int location;
public int getLocation() {
return location;
}
public void setLocation(int locs){
location = locs;
}
}
Re: ActionListener question
To do what you wish, all you need to do is make loc a class field, not a variable that is local to the constructor. Then in the actionPerformed use a for loop to iterate through loc[i] to see if the source == loc[i], and if so, check if i == whereiswaldo. That's it.
Re: ActionListener question
Re: ActionListener question
Good deal, and thanks for getting back to us with your success!