Java JFrame - 触发事件时访问对象实例

时间:2014-12-10 15:19:08

标签: java swing

我正在请求帮助我如何从按下按钮时调用的方法访问变量(在jframe中)。

这是我的代码:

public class GUI extends javax.swing.JFrame {

/**
 * Creates new form GUI
 */
public GUI() {
    initComponents();
    //my own objects for registration, matches and reports
    MyObject myObject = new MyObject();
}

private void buttonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // How would I access 'myObject' here?
    myObject.soSomething();
}

我如何使用buttonActionPerformed()访问'myObject'?

3 个答案:

答案 0 :(得分:4)

public GUI() {
    initComponents();
    //my own objects for registration, matches and reports
    MyObject myObject = new MyObject();
}

在上面的代码中,myObject是GUI()构造函数中的局部变量。一旦构造函数完成,myObject变量就会被销毁。构造函数之外的任何东西都无法看到它。

您需要使对象成为类的成员变量。

public class GUI extends javax.swing.JFrame {

    private MyObject myObject; // member variable

/**
 * Creates new form GUI
 */
public GUI() {
    initComponents();
    //my own objects for registration, matches and reports
    myObject = new MyObject();
}

private void buttonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // How would I access 'myObject' here?
    myObject.soSomething();
}

答案 1 :(得分:0)

在类中声明myObject,而不是在方法

中声明

然后你在哪里制作框架:

    JButton button = new JButton("Click me");//The JButton name.
    frame.add(button);//Add the button to the JFrame.
    button.addActionListener(this);//Add a listener to the button

同时在课程中添加下一个方法,在这里你将点击按钮时运行的代码

public void actionPerformed(ActionEvent e) {
    myObject.soSomething();
}

答案 2 :(得分:0)

不妨给出答案:

public class GUI extends javax.swing.JFrame {

private MyObject myObject;  // Moved from constructor scope to class scope.

public GUI() {
     myObject = new MyObject();
}

private void buttonActionPerformed(java.awt.event.ActionEvent evt)
{                                           
    // How would I access 'myObject' here?
    myObject.soSomething();
}