I am trying to find a way for my startTextFieldListener to gain access to some variables in my for loop. Is there a way to do this? I'm sorry if there is an easy solution to this but I am not quite sure how to work around this. I have seen some examples but I did not know how to apply it to my program. Any help would be greatly appreciated.
public class TextArea1{
JTextArea text;
JFrame frame;
JTextField textField;
public int k;
public ArrayList aList;
public String correctAnswer;
public static void main (String [] args) {
TextArea1 gui = new TextArea1();
gui.go();
}
private String textLine;
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
textField = new JTextField("");
textField.addActionListener(new startTextFieldListener(aList));
JButton startButton = new JButton ("Start!");
startButton.addActionListener(new startButtonListener(aList));
text = new JTextArea (30, 60);
text.setLineWrap(true);
JScrollPane scroller = new JScrollPane(text);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.getContentPane().add(BorderLayout.WEST, startButton);
frame.getContentPane().add(BorderLayout.SOUTH, textField);
frame.setSize(350, 300);
frame.setVisible(true);
}
class startButtonListener implements ActionListener {
ArrayList aList;
startButtonListener(ArrayList passedInList)
{
aList = passedInList;
}
@Override
public void actionPerformed(ActionEvent event) {
String fileName = "test.txt";
String line;
ArrayList aList = new ArrayList();
try {
try (BufferedReader input = new BufferedReader (new FileReader(fileName))) {
if (!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) !=null) {
aList.add(line);
}}
} catch (IOException e) {
System.out.println(e);
}
int sz = aList.size();
for (int k = 0; k< sz; k++) {
String correctAnswer = aList.get(k).toString();
text.append(aList.get(k).toString());
text.append("\n");
}
}
}
class startTextFieldListener implements ActionListener {
startTextFieldListener(ArrayList passedInList)
{
aList = passedInList;
}
@Override
public void actionPerformed(ActionEvent event) {
text.getText();
if (text.getText().equals(correctAnswer)) {
JOptionPane.showMessageDialog(null, "Hooray!");
}
else if (!text.getText().equals(correctAnswer)) {
JOptionPane.showMessageDialog(null, "Wrong!");
}
}
}
}
iin your listener, what value are you expecting it to be?