点击之后重命名按钮 - Java JButton

7

我想在单击按钮时将其从“开始”更改为“停止”。 我尝试了下面的方法,查找并尝试复制指南,但我不知道我做错了什么。 我可能错过了一些“}”,因为我省略了许多不相关的代码。 有人能看出我错在哪里吗?

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

public class PipeGameApp extends JFrame implements ActionListener {

    private static int BOARD_SIZE = 11;
    private PipeGame game;      // The model
    private PipeGameView view;      // The view

    // This constructor builds the window
    public PipeGameApp(String title) {
        super(title);

        game = new PipeGame(BOARD_SIZE);
        view = new PipeGameView(game);

        //THE TOP BAR
        JPanel topBar = new JPanel();
        JButton startButton = new JButton("Start");
        startButton.addActionListener(this);



        ButtonGroup bg1 = new ButtonGroup();
        JRadioButton rb1 = new JRadioButton("2 minutes", true);
        rb1.addActionListener(this);


        JRadioButton rb2 = new JRadioButton("10 minutes", false);
        JRadioButton rb3 = new JRadioButton("No Time Limit", false);
        bg1.add(rb1);
        bg1.add(rb2);
        bg1.add(rb3);





        topBar.add(startButton);
        topBar.add(rb1);
        topBar.add(rb2);
        topBar.add(rb3);
        //END OF TOP BAR

        //THE BOTTOM BAR
        JPanel bottomBar = new JPanel();
        JLabel timeLeft = new JLabel("Time Left: ");
        JProgressBar bar = new JProgressBar();
        bottomBar.add(timeLeft);
        bottomBar.add(bar);
        bottomBar.setVisible(false);
        //end of bottom

        /*
         //bottom 2
         int fscore=10;
         JPanel bottomBar2 = new JPanel();
         JLabel score = new JLabel("Final score:" + fscore);
         bottomBar2.add(score);
         bottomBar2.setVisible(false);
         */


        getContentPane().add(view); //CHANGE LOCATION OF BOARD GAME HERE BorderLayout.SOUTH

        getContentPane().add(topBar, BorderLayout.NORTH);
        getContentPane().add(bottomBar, BorderLayout.SOUTH);

        //getContentPane().add(bottomBar2, BorderLayout.SOUTH);



        // Add the listeners to the view's buttons
        for (int r = 0; r < BOARD_SIZE; r++) {
            for (int c = 0; c < BOARD_SIZE; c++) {
                view.getButton(r, c).addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        handleTileSelection(e);
                    }
                });
            }
        }

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        //setSize(446,466);
        setSize(446, 530);
        setResizable(false);
    }

    // Handle a Tile Selection.   Just change the model and update the view.
    private void handleTileSelection(ActionEvent e) {
        // Find the row and column of the pressed button, then make the change
        int r = 0, c = 0;
        for (int i = 0; i < BOARD_SIZE; i++) {
            for (int j = 0; j < BOARD_SIZE; j++) {
                if (e.getSource() == view.getButton(i, j)) {
                    if (game.placePipe(i, j)) {
                        view.update();
                    }
                    return;
                }
            }
        }
    }

    // This is where it all begins
    public static void main(String[] args) {
        new PipeGameApp("The Frantic Pipe Layer").setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        startButton.setText("asdf");
    }
}

请查看我对答案的编辑。你的问题不是变量遮蔽,而是变量作用域。我很惊讶你的代码能编译通过,因为你没有一个开始按钮的类引用。或者它实际上没有编译通过吗? - Hovercraft Full Of Eels
2个回答

5
你的问题是变量范围有限。你的startButton变量在构造函数中声明,因此只能在构造函数中访问。你需要在类中声明它而不是在构造函数中重新声明它,这样整个类就可以“看到”这个变量并使用它。
即,将此代码更改为:
public class PipeGameApp extends JFrame implements ActionListener {

    private static int BOARD_SIZE = 11;
    private PipeGame game;      // The model
    private PipeGameView view;      // The view

    public PipeGameApp(String title) {

        JButton startButton = new JButton("Start");
        startButton.addActionListener(this);
        // etc...

转换为:

public class PipeGameApp extends JFrame implements ActionListener {

    private static int BOARD_SIZE = 11;
    private PipeGame game;      // The model
    private PipeGameView view;      // The view
    private JButton startButton; // *** note change ***

    public PipeGameApp(String title) {

        startButton = new JButton("Start"); // *** note change ***
        startButton.addActionListener(this);
        // etc...

或者:

  • 使用JToggleButton
  • 或者使用ActionEvent的getSource()方法返回的对象,并根据其当前状态设置其新状态。

例如:

@Override
public void actionPerformed(ActionEvent ae) {
    Object source = ae.getSource();
    if (source instanceof JButton) {
       if (ae.getText().equals("Start")) {
          ae.setText("Stop");
          // do other stuff
       } else if (ae.getText().equals("Stop")) {
          ae.setText("Start");
          // do more stuff
       }
    }
}

关于"我可能错过了一些 “}”,因为我省略了很多不相关的代码。"请你尽力避免这种情况的发生。缺少的“}”会让我们更难理解你的代码并帮助你。如果你要求别人在空闲时间帮助你,请不要发布垃圾代码。


非常感谢,我会记住发布所有代码的事情。我想我会使用getSource方法,因为我需要按钮进行切换。 - user1692517
@user1692517:很高兴你解决了它。但请理解,“我的所有代码”通常太多了。最重要的是,不要像最初那样发布垃圾代码。缺少的大括号并不无关紧要,实际上非常重要。它导致一个叫Ravindra的帮手浪费了自己宝贵的空闲时间来帮助你解决一个不存在的问题,这对他来说是不公平的。 - Hovercraft Full Of Eels

2

您在main方法之后保留了构造函数的结束括号。这是更正后的代码。

public PipeGameApp(String title) {
    super(title);

    JPanel topBar = new JPanel();
    JButton startButton = new JButton("Start");
    startButton.addActionListener(this);
}

public static void main(String[] args) {
    new PipeGameApp("The Frantic Pipe Layer").setVisible(true);
}

@Override
public void actionPerformed(ActionEvent ae) {
    startButton.setText("asdf");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接