简体   繁体   中英

How to access the variable in the method of other class in java

1st class

public class component {
public static void setComponents(JPanel panel) {
    panel.setLayout(null);
    JLabel userLabel = new JLabel("User ID");
    userLabel.setBounds(10,20,80,25);
    panel.add(userLabel);
    JLabel passwordLabel = new JLabel("Password");
    passwordLabel.setBounds(10,50,80,25);
    panel.add(passwordLabel);
    JTextField textfield = new JTextField(20);
    textfield.setBounds(100,20,180,25);
    panel.add(textfield);
    JPasswordField password = new JPasswordField();
    password.setBounds(100,50,180,25);
    panel.add(password);
    JButton loginButton = new JButton("Login");
    loginButton.setBounds(100,100,100,25);
    panel.add(loginButton);
    loginButton.addActionListener(new ButtonListener());
    panel.add(loginButton);

}

2nd Class

public class ButtonListener extends component  implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
    if(e.getSource()==loginButton)
}

}

The problem is in loginButton at 2nd class. ERROR: can't resolve symbol 'loginButton' appears. I am unable to access the loginButton in the method of first class. I have tried different methods but couldn't resolve it.

For a quick prototyping you can define JButton loginButton as a class field, in this way you can access it from your other classes. For example:

public class component {
    public static JButton loginButton = new JButton("Login");
    public static void setComponents(JPanel panel) {
    ...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM