I am using eclipse
and windows builder --> Swing --> Jframe
. I have added textField
, lblNewLabel
and btnNewButton
. By clicking and dropping it on contentPane
. When trying to assign a value to a lblNewLabel
using methods lblNewLabel.setText(textField.getText());
.
I get the following error: Cannot refer to a non-final variable lblNewLabel inside an inner class defined in a different method
.
This is my source code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MultAppMed extends JFrame {
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MultAppMed frame = new MultAppMed();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MultAppMed() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(106, 14, 46, 14);
contentPane.add(lblNewLabel);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
lblNewLabel.setText(textField.getText());
}
});
btnNewButton.setBounds(335, 228, 89, 23);
contentPane.add(btnNewButton);
textField = new JTextField();
textField.setBounds(10, 11, 86, 20);
contentPane.add(textField);
textField.setColumns(10);
}
}
Why is this happening? I was reading some answers that say: "Java requires references to variables from inner classes to be final variables" but if needed why doesn't Jframe
insert it as such automatically. My textField
is working and I can get and set Its value using the same methods. I was meaning to ask why and how to solve this. I appreciate your help.
lblNewLabel
final or make it instance member. What you want to achieve? – Braj