本文介绍了如何制作禁用JButton的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一种禁用JButtons的方法.

I am trying to make a method that disables JButtons.

JButtons以网格形式位于数组中,JButton [int][int],并且整数应为坐标.

The JButtons are in an array in the form of a grid, JButton [int][int] and the integers are supposed to be coordinates.

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

}

推荐答案

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

I did some changes in your code:

  1. public static JFrame f = new JFrame("BS"); JFrame不应为static,并且应具有更有意义的名称(例如frame).

  1. public static JFrame f = new JFrame("BS"); JFrame shouldn't be static and should have a more meaningful name (like frame for example).

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

final JButton[][] coordinates = new JButton[15][15]; moved this array as a class member and made it non final and also changed the name to buttons as it's easier to know what it is (coordinates to me, sounds more like an array of Point or int)

此后,我添加了ActionListener,请参见如何使用动作教程.

After that I added an ActionListener, see How to use Actions tutorial.

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()的方法,该方法将禁用两个单击的按钮之间的所有按钮:

And a method called disableButtons() which disables all the buttons between the 2 clicked buttons:

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
        }
    }
}

最后,我们的代码如下所示:

At the end our code ends like this:

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

我希望这是您正在尝试做的...如果没有请澄清.

I hope this is what you were trying to do... if not please clarify.

对于Java 7及更低版本,请在ActionListener上使用此代码:

For Java 7 and lower use this for the 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;
                }
            }
        }
    }
};

这篇关于如何制作禁用JButton的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 18:27