获取错误:Component中的变量私有访问

时间:2014-02-14 10:42:07

标签: java jlabel

我遇到了这个错误,'名称在Component中有私人访问权限'。我不明白它的含义,但我想我可能错误地在main方法中初始化了变量'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 个答案:

答案 0 :(得分:1)

您的班级Gamey会扩展JFrame类,而后者会扩展Component类。在方法startGame()中,您在此语句中使用了名为name的字段。

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

由于Gamey类中没有该名称的实例变量,因此它已升级层次结构以检查此类字段,并在Component类中找到一个字段。但是,此字段name具有private访问修饰符,这就是您收到错误的原因

name has a private access in Component.

要消除此错误,请在name课程或Gamey中声明startGame()字段,具体取决于您的要求。

注意:您的代码有点乱,但我可以看到您在name方法中有一个变量main()。您可以将其设为实例变量,并在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
    ...
    }
}