内部类变量Access

时间:2015-03-23 01:10:00

标签: dialog this box

在这种情况下,我有点困惑为什么我不能将myFrame用作showMessageDialog函数中的第一个参数。为什么这不起作用?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class BabyCalculator extends JFrame{

public BabyCalculator(){
    //You set this up so that you can refer to the frame using the inner class below.
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setName("Baby Calculator");
    setLayout(new GridLayout(3,0));
    //add
    JLabel addLabel = new JLabel("Amount to add:");
    JTextField addField = new JTextField(10);
    JButton addButton = new JButton("add");
    addButton.addActionListener(new AddListener());
    //multiply
    JLabel multiplyLabel = new JLabel("Amount to multiply:");
    JTextField multiplyField = new JTextField(10);
    JButton multiplyButton = new JButton("multiply");
    //total
    JLabel totalLabel = new JLabel("Total");
    JTextField totalField = new JTextField(10);
    totalField.setEditable(false);
    JButton stopButton = new JButton("Stop");
    stopButton.addActionListener(new StopListener());
    //Create Panels
    JPanel topRow = new JPanel(new BorderLayout());
    JPanel middleRow = new JPanel (new BorderLayout());
    JPanel bottomRow = new JPanel (new FlowLayout());
    //Add the top Row
    topRow.add(addLabel,BorderLayout.WEST);
    topRow.add(addField, BorderLayout.CENTER);
    topRow.add(addButton, BorderLayout.EAST);
    add(topRow);

    middleRow.add(multiplyLabel,BorderLayout.WEST);
    middleRow.add(multiplyField, BorderLayout.CENTER);
    middleRow.add(multiplyButton, BorderLayout.EAST);
    add(middleRow);

    bottomRow.add(totalLabel);
    bottomRow.add(totalField);
    bottomRow.add(stopButton);

    add(bottomRow);



    pack();
    setVisible(true);
}

public static void main (String[] args){
    JFrame myFrame = new BabyCalculator();
}

public class AddListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
        JOptionPane.showMessageDialog(myFrame, "You Clicked the add button");

    }
}
//end class AddListener

public class StopListener implements ActionListener{//this is an inner class
    public void actionPerformed(ActionEvent e){
        JOptionPane.showMessageDialog(myFrame, "You Clicked the stop button");
    }//end class StopListener
}

}

我知道这是一个内部类,我不确定访问权限,但似乎应该有一些方法来访问main函数中的“myFrame”变量。

1 个答案:

答案 0 :(得分:0)

在BabyCalculator类的顶部添加一个声明语句:

JFrame myFrame;

或者您可以将其设为公共变量:

public JFrame myFrame = ...