简体   繁体   English

Java中另一种方法中的访问实例变量

[英]Access Instance Variables in Another Method in Java

I'm writing a GUI in Java. 我正在用Java编写GUI。 One method initializes and displays a form: 一种方法初始化并显示一个表单:

public class launchQMBPMN extends CytoscapeAction {
  private JComboBox termDB;

  public launchQMBPMN(QMBPMN SaddleSum) {
    super("SaddleSum");
    setPreferredMenu("Plugins");


  }

  public class buttonListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
      JFrame hello = new JFrame();
      JLabel test = new JLabel(termDB.getSelectedItem());
      test.add(hello);
      hello.show();
    }
  }
  public void actionPerformed(ActionEvent e) {
    CytoscapeDesktop desktop = Cytoscape.getDesktop();

    InteractionTools tools = new InteractionTools();

    GridBagConstraints c = new GridBagConstraints();
    c.anchor = GridBagConstraints.LINE_START;
    c.weightx = 0.5;

    buttonListener buttonPressed = new buttonListener();

    // TERM DATABASE AND WEIGHTS

    JPanel qmbpTermsPanel = new JPanel(new GridBagLayout());

    termDB = new JComboBox(tools.discoverTermDatabases());
    c.gridx = 1;
    c.gridy = 0;
    qmbpTermsPanel.add(termDB, c);  


                ...

I'd like to access 'termDB' in my buttonListner class. 我想在我的buttonListner类中访问'termDB'。 How do I do that? 我怎么做?

Simply access it using its name, that should work as it's inside the outer class. 只需使用它的名称访问它,它就应该在外部类内部工作。

See also: http://download.oracle.com/javase/tutorial/java/javaOO/innerclasses.html 另请参见: http : //download.oracle.com/javase/tutorial/java/javaOO/innerclasses.html

Access it as you posted here. 按照您在此处发布的内容进行访问。 Some comments: 一些评论:

  1. show method of JFrame (actually, of java.awt.Window ) is deprecated, use setVisible(true); 不推荐使用JFrame show方法(实际上是java.awt.Window show方法),请使用setVisible(true); instead. 代替。

  2. I'm not sure test.add(hello); 我不确定test.add(hello); is that you really need. 是您真正需要的。 Is it? 是吗? It adds the frame to the label. 它将框架添加到标签。

  3. termDB.getSelectedItem() returns an Object , JLabel constructor requires a string: termDB.getSelectedItem().toString() ? termDB.getSelectedItem()返回一个ObjectJLabel构造函数需要一个字符串: termDB.getSelectedItem().toString()吗?

You can create a subclass of ButtonListener and pass the termDB into it when you create it, or otherwise set it. 您可以创建ButtonListener的子类,并在创建时将termDB传递给它,或者进行其他设置。

Or you can can define an anonymous inner class where need the button listener and make termDB final, and it will be available in your ButtonListener implementation. 或者,您可以在需要按钮侦听器的地方定义一个匿名内部类,并使termDB为final,它将在您的ButtonListener实现中可用。 Or you could pass the termDB reference to the anonymous inner classs like you would in the first option I presented. 或者,您可以像我介绍的第一个选项一样,将termDB引用传递给匿名内部类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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