0

I have a static method in which I would like to return a String from a JTextField. I would like it to act like Scanner's nextLong(), when the method is called, the rest of the program stalls until input. Here's my code, with my attempt on how to do this.

String y;

JTextField a = new JTextField(7);
a.setFont(silkScreen);
a.setForeground(Color.white);
a.setBackground(Color.black);
a.setAlignmentX(JTextField.CENTER_ALIGNMENT);
a.setBorder(javax.swing.BorderFactory.createEmptyBorder());
a.addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e) {
        if (a.getText().length() >= 9) { // limit textfield to 9 characters
            e.consume();
        }
    }
});
a.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent arg0) {
        y = a.getText();
    }
});

panel.add(a);
frame.add(panel);

frame.pack();
frame.setSize(640 / 2, 480 / 2);
frame.setVisible(true);
return y;

But, Java spits out this error:

Local variable y defined in an enclosing scope must be final or effectively final

Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50
  • 2
    *"Java spits out this error:"* As a programmer, you will see lots of compiler errors like that, and it is important to be able to figure out most of them on your own. So as a start to that, what did your search related to that error message reveal? – Andrew Thompson Sep 06 '17 at 17:14
  • Read this, it may give you the answer: https://stackoverflow.com/questions/7423028/java-local-variable-visibility-in-anonymous-inner-classes-why-is-final-keywo – Assafs Sep 06 '17 at 17:14
  • Possible duplicate of [Problems with local variable scope. How to solve it?](https://stackoverflow.com/questions/25894509/problems-with-local-variable-scope-how-to-solve-it) – Juan Carlos Mendoza Sep 06 '17 at 17:30
  • This should answer your question https://stackoverflow.com/questions/14909401/return-a-value-when-an-jbutton-actionperformed-event-is-called – isaace Sep 06 '17 at 19:17
  • 1
    Don't use a `KeyListener` for this, it won't be triggered by calling `setText` or pasting text into the field, use a `DocumentFilter` instead – MadProgrammer Sep 06 '17 at 21:49

0 Answers0