如何从Java中的另一个按钮调用一个按钮中的实例

时间:2015-03-15 18:17:04

标签: java windowbuilder

我试图从RSA()

的另一个按钮调用btnNewButton中的btnNewButton_1个实例

我怎么能这样做,甚至可能呢?

这是代码。

//ENCRYPT BUTTON
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String num1;

                try{
                    RSA rsa = new RSA();
                    num1 =(textFieldToEncrypt.getText());
                    byte[] encrypted = rsa.encrypt(num1.getBytes());
                    byte[] decrypted = rsa.decrypt(encrypted);
                    textFieldEncStrByte.setText(bytesToString(encrypted));
                    textFieldDecrypted.setText(new String(decrypted));

                }//close try
                catch (Exception e){
                    JOptionPane.showMessageDialog(null, "Please Enter Valid Text");         
                }//close catch
            }//close public void
        });//close button

        //DECRYPT BUTTON
        btnNewButton_1.addActionListener(new ActionListener() { 
            public void actionPerformed(ActionEvent e) {
                String num1;

                try{
                    num1 =(textFieldEncStrByte.getText());
                    byte[] decrypted = decrypt(num1.getBytes());

                    textFieldDecrypted.setText(bytesToString(decrypted));

                }//close try
                catch (Exception e1){
                    JOptionPane.showMessageDialog(null, "Please Enter Valid Text");         
                }//close catch
            }//close public void
        });//close button

3 个答案:

答案 0 :(得分:1)

没有。不是这样的。这是因为Java有Scoping。您需要做的是增加变量的范围,以便可以从两种方法访问它。即,将其设为 global

private RSA rsa = new RSA();

btnNewButton.addActionListener(new ActionListener() {
    // use rsa.
}

btnNewButton_1.addActionListener(new ActionListener() { 
    // use rsa.
}

答案 1 :(得分:0)

您需要将其存储在类字段中,如此

class Foo {
  static RSA myRSA;

  public void buidGui() {
    //...
    ActionListener al = new ActionListener() {
       myRSA = ...;
    }
    ActionListener al2 = new ActionListener() {
       if (myRSA != null) // do something
    }
}

答案 2 :(得分:0)

这是一个范围问题 - 如果在您的方法中将RSA定义为局部变量,则无法共享您的RSA。

要分享,请将其移动为实例变量,例如:

public class MyClass {
    private RSA ras = new RSA();

    public void initGui(){
       btnNewButton.addActionListener(){
            .... // this code can use 'ras'
       }
       btnNewButton_1.addActionListener(){
            .... // this code can use 'ras'
       }

    }

}

更详细地说,你的actionListeners是Inner(和anonymouse)类,这意味着他们可以访问包含类的字段(MyClass)