2014-02-14 27 views
0

我被困在這個錯誤'名稱在組件中具有私有訪問'。我不明白它是什麼意思,但我想我可能在主要方法中錯誤地初始化了變量'name'。 startGame()方法內的錯誤點,我初始化'label1'。獲取錯誤:組件中的變量私有訪問

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

public class Gamey extends JFrame 
{ 
private JPanel panelUp; 
private JPanel panelDown; 
private JButton btnPlay, btnNext; 
private JLabel label1; 

public Gamey() 
{ 
    super("Game"); 
    startGame(); 
} 

public void startGame() 
{ 
    Container c = getContentPane(); 
    panelUp = new JPanel(); 
    panelDown = new JPanel(); 
    label1 = new JLabel(name + "Snow glows white on the mountain tonight"); //name has a private access in Component 
    btnPlay = new JButton("Play"); 
    btnNext = new JButton("Next"); 

    btnPlay.addActionListener(new Handler()); 

    panelUp.add(label1); 
    panelDown.add(btnPlay); 

    c.add(panelUp, BorderLayout.CENTER); 
    c.add(panelDown, BorderLayout.PAGE_END); 


} 

public class Handler implements ActionListener 
{ 


    public void actionPerformed(ActionEvent e) 
    { 
     if(e.getSource() == btnPlay) 
     { 
      btnPlay.setText("Next"); 
      label1.setText("Not a footprint to be seen"); 

     } 

    } 

} 




public static void main(String[] args) 
{ 
    String name = JOptionPane.showInputDialog(null, "enter name: "); 
    Gamey game = new Gamey(); 

    game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    game.setSize(450,450); 
    game.setVisible(true); 
    game.setLocationRelativeTo(null); 
} 

} 

回答

1

Gamey類擴展JFrame類,後者又擴展Component類。在方法startGame()中,您在此聲明中使用了一個名爲name的字段。

label1 = new JLabel(name + "Snow glows white on the mountain tonight"); 

由於是在Gamey類名稱的實例變量,它已經漲了層次檢查這般田地,發現在Component類中的一個存在。但本場nameprivate訪問修飾符,這就是爲什麼你得到錯誤

name has a private access in Component. 

爲了擺脫這種錯誤的,無論是在你的Gamey類聲明name領域還是在startGame()根據您的要求。

注:你的代碼是有點混亂,但我看得出來,你在main()方法具有可變name。您可以將其設置爲實例變量,然後在main()方法中填充其值,然後可以在startGame()方法中使用該方法。這樣的事情:

public class Gamey extends JFrame { 
    // Other fields 
    private String name; 
    // Getter & setter for name 

    ... 

    public static void main(String[] args) { 
     Gamey game = new Gamey(); 
     game.setName(JOptionPane.showInputDialog(null, "enter name: ")); // Set the name with the value from the input dialog 
    ... 
    } 
} 
+0

好吧我已經按照你的建議。謝謝!但這是另一個。它編譯但name變量顯示爲null,如下所示:nullSnow今晚在山上發出白光。它爲什麼這樣做? – Smee