我的新游戏JButton不工作?

嗨,我目前正在完成一项98%完成的作业。 我已经制作了gui程序,其中jtextfield设置为0但是当你玩游戏时它会改变。

现在我创建了一个名为“NEW GAME”和“QUIT”的按钮。 单击时,我的退出按钮工作正常。 但我的新游戏按钮是我的问题。

我想要它,以便当我点击按钮时它将分数设置为0

public ShinyButtonsGUIProgramToShare(String tit, int x, int y) { //The button GUI ShinyButtonsGUIToShare sbg = new ShinyButtonsGUIToShare("NYI", 552, 552, new ShinyButtons()); sbg.setLocation(10, 10); getContentPane().add(sbg); //The score text and text box JLabel jlb = new JLabel("Score: "); jlb.setLocation(12, (y - 75)); jlb.setSize(45, 40); getContentPane().add(jlb); JTextField jtf = new JTextField("0"); jtf.setLocation(60, (y - 70)); jtf.setSize(150, 30); jtf.setHorizontalAlignment(JTextField.RIGHT); getContentPane().add(jtf); JButton NewGame, Quit; NewGame = new JButton("New Game"); Quit = new JButton("Quit"); Quit.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { System.exit(0); }}); NewGame.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { JTextField jtf.setText("0"); }}); NewGame.setLocation((x - 220), (y - 70)); NewGame.setSize(100, 30); getContentPane().add(NewGame); Quit.setLocation((x - 110), (y - 70)); Quit.setSize(100, 30); getContentPane().add(Quit); setDefaultCloseOperation(EXIT_ON_CLOSE); // allow window to close setSize(x, y); setLayout(null); setResizable(false); } public static void main(String[] args) { ShinyButtonsGUIProgramToShare sbgp = new ShinyButtonsGUIProgramToShare("Shiny Buttons", 578, 634); sbgp.setVisible(true); } } 

你有一个上下文问题……

无法在NewGameActionListener的上下文中引用jtf的实例

您需要创建jtf和实例变量,以便可以从ShinyButtonsGUIProgramToShare对象的实例中的任何位置访问它。

请参阅 了解 Java编程语言的 类成员和代码约定