2015-09-26 142 views
3

我無法訪問內部類「listPanel」的對象中的變量。 有變量「tutajcos」,但我無法從CosView類中的其他方法訪問。無法訪問內部類變量

什麼問題? Eclipse不會提示我任何東西

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"); 
     } 
    } 
} 

回答

5

問題不在於訪問修飾符,而是在於繼承。您的listPanel變量被聲明爲JPanel類型,該變量沒有名爲tutajcos的可訪問字段。 爲了能夠訪問它,你嘗試的方式,你需要聲明listPanel爲ListPanel:

private ListPanel listPanel; 

或調用之前將它轉換:

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

謝謝! private ListPanel listPanel;幫助 – Mateusz