我在程序中的菜单类GraphMenu()
的一个元素上有一个监听器,它需要调用在该类外部创建的现有对象的方法,我似乎无法找到方法实现这一点。
我正在定义我需要在panel
类中调用GraphPanel()
的方法:
public class GraphPanel extends JPanel {
private JLabel textLabel, graphicLabel;
private JTextArea textArea;
private JPanel graphPanel;
public void appendTextArea(String s) {
textArea.append(s + '\n');
}
我需要调用该方法的GraphMenu()
的监听器是:
public class GraphMenu {
...
// Add the action listeners that identify the code to execute when the options are selected.
menuItemLoad.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final JFileChooser fc = new JFileChooser();
// you can set the directory with the setCurrentDirectory method.
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
// User has selected to open the file.
File file = fc.getSelectedFile();
try {
// Open the selected file
BufferedReader reader = new BufferedReader(new FileReader(file));
// Output the contents to the console.
String nextLine = reader.readLine();
while ( nextLine != null ) {
panel.appendTextArea(nextLine);
System.out.println(nextLine);
nextLine = reader.readLine();
}
reader.close();
} catch (IOException e1) {
System.err.println("Error while reading the file");
}
};
}
});
...
有没有办法可以像上面的示例中那样调用appendTextArea()
对象上的panel
?
我在主函数中创建了类GraphPanel()
和GraphMenu()
的两个对象:
GraphPanel panel = new GraphPanel();
frame.getContentPane().add(panel);
GraphMenu menu = new GraphMenu();
frame.setJMenuBar(menu.setupMenu());