Mateusz
Mateusz

Reputation: 624

Cannot get access to inner class variables

I cannot get access to variables in object of inner class "listPanel". There is variable "tutajcos" but I cannot get access from other methods in CosView class.

What is a problem? Eclipse does not prompt me anything

package cos.view;

import java.awt.*;
import java.awt.event.*;
import java.util.Observable;

import util.Model;
import util.View;

import javax.swing.*;

import cos.controller.CosController;
import cos.model.CosModel;

public class CosView extends View implements ActionListener {

    private JPanel buttonsPanel;
    private JPanel listPanel;
    private CosModel theModel;
    private CosController theController;

    public CosView(CosController theController, CosModel theModel) {
        this.theModel = theModel;
        this.theController = theController;

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                buildGui();
            }
        });
    }

    private void buildGui() {
        setTitle("Program GUI");
        listPanel = new ListPanel();
        buttonsPanel = new ButtonPanel();
        add(buttonsPanel, BorderLayout.NORTH);
        add(listPanel, BorderLayout.CENTER);

        pack();
        setVisible(true);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 600);
        registerWithModel(theModel);
    }

    class ButtonPanel extends JPanel {

        JButton refreshButton = new JButton("Refresh");
        JTextField adresField = new JTextField("tutaj link", 10);

        public ButtonPanel() {
            refreshButton.addActionListener(CosView.this);
            add(refreshButton);
            add(adresField);
        }
    }

    class ListPanel extends JPanel {
        JTextField tutajcos;

        public ListPanel() {
            tutajcos = new JTextField(8);
            add(tutajcos);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String action = e.getActionCommand();
        theController.processUserAction(action);
    }

    @Override
    public void update(Observable o, Object arg) {
        System.out.println("Updating interface");
        if (o instanceof CosModel) {
            String content;
            //there is a problem-------------
            listPanel.tutajcos.setText("siema");
        }
    }
}

Upvotes: 3

Views: 96

Answers (1)

Aleksandr Erokhin
Aleksandr Erokhin

Reputation: 1982

The problem is not with access modifiers but rather with inheritance. Your listPanel variable is declared to be of type JPanel which has no accessible fields named tutajcos. In order to be able to access it the way you try, you need to declare listPanel as ListPanel:

private ListPanel listPanel;

or cast it before call:

((ListPanel)listPanel).tutajcos.setText("siema");

Upvotes: 5

Related Questions