【问题标题】:How to make a method that disables JButton?如何制作禁用 JButton 的方法?
【发布时间】:2018-04-05 15:07:17
【问题描述】:

我正在尝试制作一种禁用 JButtons 的方法。

JButtons 在一个网格形式的数组中,JButton [int][int] 并且整数应该是坐标。

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.*;


public class BS {

public static JFrame f = new JFrame("BS");



public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable()
    {
      public void run()
      {
        initializeGui();
      }
    });

}

static void initializeGui() {

     JPanel gui = new JPanel(new BorderLayout(3,1));
//This is the array of the JButtons in the form of a grid
     final JButton[][] coordinates = new JButton[15][15];
     JPanel field;


    // set up the main GUI
    gui.setBorder(new EmptyBorder(5, 5, 5, 5));
    field = new JPanel(new GridLayout(0, 15));

    field.setBorder(new CompoundBorder(new EmptyBorder(15,15,15,15),new LineBorder(Color.BLACK)));

    JPanel boardConstrain = new JPanel(new GridBagLayout());
    boardConstrain.add(field);
    gui.add(boardConstrain);

//The making of the grid
    for (int ii = 0; ii < coordinates.length; ii++) {
        for (int jj = 0; jj < coordinates[ii].length; jj++) {
            JButton b = new JButton();

            ImageIcon icon = new ImageIcon(
                    new BufferedImage(30, 30, BufferedImage.TYPE_INT_ARGB));
            b.setIcon(icon);

            coordinates[jj][ii] = b;
            field.add(coordinates[jj][ii]);
        }
    }

    f.add(gui);
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);              
    f.pack();
    f.setMinimumSize(f.getSize());
    f.setVisible(true);
}

}

【问题讨论】:

  • 在您要禁用的JButton 中调用JButton#setEnabled(false)。现在为了获得更好的帮助,请尽快发布正确的minimal reproducible example,表明您正在努力自己解决问题
  • @Frakcool 很抱歉没有发布完整的代码,出于某种原因,这个问题在我脑海中听起来很简单 :)
  • 这是一个简单的问题,但在本站您必须提供您的代码,否则您的代码会被视为“过于宽泛”。您何时尝试禁用JButton?什么时候点击?
  • 解释一下,“跟随它的给定数量的按钮也会被禁用” 多少?只是同一行?下一行?列?如何?顺便说一句,在更大的程序中使用短名称作为类名或任何其他变量可能会造成混淆(BS 这是什么意思?)

标签: java swing jbutton


【解决方案1】:

我对您的代码做了一些更改:

  1. public static JFrame f = new JFrame("BS"); JFrame 不应该是 static 并且应该有一个更有意义的名称(例如 frame)。

  2. final JButton[][] coordinates = new JButton[15][15]; 将此数组作为类成员移动并使其成为非最终数组,并将名称更改为buttons,因为它更容易知道它是什么(coordinates 对我来说,听起来更像是一个数组Pointint)

之后我添加了一个ActionListener,参见How to use Actions 教程。

private ActionListener listener = e -> {
    //Loops through the whole array in both dimensions
    for (int i = 0; i < buttons.length; i++) {
        for (int j = 0; j < buttons[i].length; j++) {
            if (e.getSource().equals(buttons[i][j])) { //Find the JButton that was clicked
                if (isStartButton) { //startButton is a boolean variable that tells us if this is the first button clicked or not
                    startXCoord = i;
                    startYCoord = j;
                } else {
                    endXCoord = i;
                    endYCoord = j;
                    disableButtons(); //Only when we have clicked twice we disable all the buttons in between
                }
                isStartButton = !isStartButton; //In every button click we change the value of this variable
                break; //No need to keep looking if we found our clicked button. Add another one with a condition to skip the outer loop.
            }
        }
    }
};

还有一个名为disableButtons() 的方法会禁用两个点击按钮之间的所有按钮:

private void disableButtons() {
    compareCoords(); //This method checks if first button clicked is after 2nd one.
    for (int i = startXCoord; i <= endXCoord; i++) {
        for (int j = startYCoord; j <= endYCoord; j++) {
            buttons[i][j].setEnabled(false); //We disable all buttons in between
        }
    }
}

最后我们的代码是这样结束的:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

public class DisableButtonsInBetween {

    private JFrame frame = new JFrame(getClass().getSimpleName());
    private JButton[][] buttons;

    private int startXCoord = -1;
    private int startYCoord = -1;
    private int endXCoord = -1;
    private int endYCoord = -1;
    private boolean isStartButton = true;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new DisableButtonsInBetween().initializeGui();
            }
        });
    }

    void initializeGui() {
        JPanel gui = new JPanel(new BorderLayout(3, 1));
        // This is the array of the JButtons in the form of a grid
        JPanel pane;
        buttons = new JButton[15][15];

        // set up the main GUI
        gui.setBorder(new EmptyBorder(5, 5, 5, 5));
        pane = new JPanel(new GridLayout(0, 15));

        pane.setBorder(new CompoundBorder(new EmptyBorder(15, 15, 15, 15), new LineBorder(Color.BLACK)));

        JPanel boardConstrain = new JPanel(new GridBagLayout());
        boardConstrain.add(pane);
        gui.add(boardConstrain);

        // The making of the grid
        for (int ii = 0; ii < buttons.length; ii++) {
            for (int jj = 0; jj < buttons[ii].length; jj++) {
                buttons[jj][ii] = new JButton();

                ImageIcon icon = new ImageIcon(new BufferedImage(30, 30, BufferedImage.TYPE_INT_ARGB));
                buttons[jj][ii].setIcon(icon);
                buttons[jj][ii].addActionListener(listener);

                pane.add(buttons[jj][ii]);
            }
        }

        frame.add(gui);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.pack();
        frame.setMinimumSize(frame.getSize());
        frame.setVisible(true);
    }

    //The ActionListener is what gets called when you click a JButton
    private ActionListener listener = e -> {
        //These for loops are done to identify which button was clicked.
        for (int i = 0; i < buttons.length; i++) {
            for (int j = 0; j < buttons[i].length; j++) {
                if (e.getSource().equals(buttons[i][j])) {
                    if (isStartButton) {
                        //We save the coords of the 1st button clicked
                        startXCoord = i;
                        startYCoord = j;
                    } else {
                        //We save the coords of the 2nd button clicked and call the disableButtons method
                        endXCoord = i;
                        endYCoord = j;
                        disableButtons();
                    }
                    isStartButton = !isStartButton;
                    break;
                }
            }
        }
    };

    //This method disables all the buttons between the 2 that were clicked
    private void disableButtons() {
        compareCoords();
        for (int i = startXCoord; i <= endXCoord; i++) {
            for (int j = startYCoord; j <= endYCoord; j++) {
                buttons[i][j].setEnabled(false);
            }
        }
    }

    //This method compares the coords if the 2nd button was before (in its coords) than the 1st one it switched their coords
    private void compareCoords() {
        if (endXCoord < startXCoord) {
            int aux = startXCoord;
            startXCoord = endXCoord;
            endXCoord = aux;
        }
        if (endYCoord < startYCoord) {
            int aux = startYCoord;
            startYCoord = endYCoord;
            endYCoord = aux;
        } 
    }
}

我希望这是你想要做的......如果不是,请澄清。

我没有箭头运算符“->”。我认为它需要更高的Java。有没有办法代替这个?

对于 Java 7 及更低版本,请将此用于 ActionListener

private ActionListener listener = new ActionListener() {    
    @Override
    public void actionPerformed(ActionEvent e) {
        for (int i = 0; i < buttons.length; i++) {
            for (int j = 0; j < buttons[i].length; j++) {
                if (e.getSource().equals(buttons[i][j])) {
                    if (isStartButton) {
                        startXCoord = i;
                        startYCoord = j;
                    } else {
                        endXCoord = i;
                        endYCoord = j;
                        disableButtons();
                    }
                    isStartButton = !isStartButton;
                    break;
                }
            }
        }
    }
};

【讨论】:

  • 我没有箭头运算符“->”。我认为它需要更高的Java。有什么办法可以代替吗?
  • 添加ActionListener时出现如下错误:类型new ActionListener(){}必须实现继承的抽象方法ActionListener.actionPerformed(ActionEvent)
  • 你添加了下 2 行吗?就像我在编辑的代码中所做的那样,就像 @Overridepublic void actionPerformed(ActionEvent e) { 一样?只需复制粘贴整个ActionListener 就可以了
  • 我通过导入 java.awt.event.ActionEvent 并删除覆盖来修复它
  • 您介意在方法上方添加某种 cmets,我正在尝试理解它。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-02
  • 1970-01-01
  • 2012-04-20
相关资源
最近更新 更多