I have a variable ("data") that comes through into the JFrame through the constructor. I also have a button with an ActionPerformed method attached to it. I need to be able to access the variable "newData" from inside the ActionPerformed:
public JFrame(int data) {
initComponents();
int newData = data 5;
}
private void ButtonActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(newData);
}
How can I achieve this?
CodePudding user response:
Move the declaration (the part with the type, int
here) outside of the method. This makes newData
an instance field rather than a local variable, and it is now accessible outside of the method (or in this case constructor).
public class MyJFrame extends JFrame {
private int newData;
public MyJFrame(int data) {
initComponents();
newData = data 5;
}
private void ButtonActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(newData);
}