简体   繁体   中英

eventHandler, defining & accessing params (java Swing Netbeans)

in short: How do I get access to a param passed into a GUI constructor within eventHandler?

more details: I am using NetBeans and Swing to write a Plugin in Java. I have created a Jframe with a GUI which includes a JTextField. The eventHandler for JTextField writes the value entered to a variable. Within the eventHandler I want next to call a method() which uses this variable and another, which was passed into the GUI's constructor.

?? How can I gain access to this variable? NetBeans wont let me change the auto-generated eventHandler signature to include the GUI variable I need. This eventHandler code below.

This is week 3 of Java for me so apologies if this is very basic question
thank you
B PS thank for site, it has already answered many other questions.

private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {  // *** no edit allowed to signature (greyed by NetBeans)                                          
    System.out.println( "textField2: " +  jTextField1.getText() );
    String s = jTextField2.getText();
    try {
        numIter = Integer.parseInt(s.trim());
        testMethod(numIter, paramPassedIntoGUIconstructor); 
// ?? how to get paramPassedIntoGUIconstructor?? <<-- key question
    } catch (NumberFormatException nfe) {
        JOptionPane.showMessageDialog(Cytoscape.getDesktop(),
                "That's not an integer!", "NumberFormatException",1);
    }
} // *** no edit allowed (greyed by NetBeans)  

I'm not sure I understand the problem, but you should be able to add a member variable:

private final Integer answer;
// Variables declaration - do not modify
...
// End of variables declaration

Initialize it in your constructor:

public MyClass(Integer iWantAccessToThis) {
    initComponents();
    answer = iWantAccessToThis;
}

Access it, ad lib :

private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {                                             
    ...
    System.out.println(this.answer);
    ...
}                                            

As @trashgod noted, it just works. However, if you attempt to use this to reference a variable, (eg. this.answer ) it will fail.

When the listener is executing, this refers to the instance of the listener. To reference your outer class, you need to qualify the access by prepending the class name like so: Myclass.this.answer .

The JLS refers to it as a Qualified this

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