java - 单击后重命名按钮 - Java JButton

标签 java swing jframe jbutton actionlistener

我正在尝试将我的按钮从点击它时说“开始”更改为“停止”。我在下面尝试这样做,我查了一下并试图复制指南,但我看不出我做错了什么。我可能遗漏了一些“}”,因为我遗漏了很多不相关的代码。有人可以看到我做错了什么吗?

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

最佳答案

您的问题是变量范围有限。您的 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
       }
    }
}

关于 “我可能遗漏了一些“}”,因为我遗漏了很多不相关的代码。” 请努力避免这种情况发生。缺少的“}”不应该丢失,这会使我们更难理解您的代码并为您提供帮助。如果您要求其他人在空闲时间努力帮助您,那么不要发布垃圾代码并不过分。

关于java - 单击后重命名按钮 - Java JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15285977/

相关文章:

java - 如果在 DefaultListModel 中选择之前单击按钮,可以防止崩溃吗?

java - 为什么 validateTree 不起作用?

java - Swing:将数据从 JFrame 传递到另一个 JFrame

java - Windows 8 扭曲了我的托盘图标

java - 由paintComponent()绘制的东西在调用repaint()后消失

java - Android studio 更新后出现以下错误,任何人都可以帮我解决2

java - 如何在JXTreeTable的子节点设置字体和背景颜色

java - 为 JFrame 制作自定义图标

java - Spring RequestMapping查看路径错误

java - Android——谷歌对单例模式的矛盾