如何创建一个禁用 JButton 的方法?

2024-01-12

我正在尝试制定一种禁用方法JButtons.

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

}


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

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

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

之后我添加了一个ActionListener, see 如何使用动作 https://docs.oracle.com/javase/tutorial/uiswing/misc/action.html教程。

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()这将禁用 2 个单击按钮之间的所有按钮:

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;
                }
            }
        }
    }
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何创建一个禁用 JButton 的方法? 的相关文章

  • Spring - Path 的工厂方法

    我正在尝试生成一个代表的 beanjava nio file Path使用静态方法Paths get String path 我当前的 Spring 设置如下
  • 如何对这个字符串进行子串化

    我想得到这个字符串的 4 个部分 String string 10 trillion 896 billion 45 million 56873 我需要的4个部分是 10万亿 8960亿 4500万 和 56873 我所做的是删除所有空格 然
  • Spring boot JPA不使用findById返回现有结果

    我使用 Oracle 数据库和一些 JPA 查询创建了一个非常小且简单的 Spring Boot 应用程序 这是不返回数据的代码片段 该数据实际上存在于数据库中 letterRecipientNonOas letterRecipientNo
  • 时间序列中的峰值检测

    我目前正在开展一个小项目 我想在其中比较两个时间序列 相似性度量确实很模糊 如果两个时间序列大致具有相同的形状 则它们被认为是相似的 所以我心想 如果它们只需要具有相同的形状 我只需比较两个时间序列的峰值 如果峰值位于相同的位置 那么时间序
  • Java:如何像 C++ 一样存储和检索内存地址

    我有 C 背景 在 C 中 我可以存储我刚刚在全局数组中新建的内存地址 并在以后重新使用它 例如 假设我有两个类 X Y 并且我创建了两个对象 x y 全局数组 StoreAddresses 2 定义为 uint32 t StoreAddr
  • 无法在 Eclipse IDE 中使用 java 建立与 SQL Server 2008 的数据库连接

    我正在尝试在 Eclipse IDE 中使用 Java 代码连接到 HP Operations Manager 数据库 我能够通过 Microsoft SQL Server Management Studio 2008 成功连接 但通过代码
  • 如何使用 JNDI 和 Digest-MD5 对 LDAP 进行身份验证

    我正在尝试使用 DIGEST MD5 加密对 LDAP 服务器进行身份验证 使用简单加密时 它工作得很好 但由于显而易见的原因 我无法通过网络以纯文本形式发送密码 奇怪的是 在使用 Softerra LDAP 浏览器时 我可以使用 Dige
  • PESSIMISTIC_WRITE 是否锁定整个表?

    只是为了确保我正确理解事情是如何运作的 If I do em lock employee LockModeType PESSIMISTIC WRITE 它会仅阻止该实体吗 employee 或整个表Employees 如果重要的话 我正在谈
  • hibernate外键问题:执行DDL“alter table...”时出错

    我有一个非常简单的对象结构 它给了我一个我无法解决的错误 已经做了很多搜索 我认为这一定是一个非常常见的用例 所以不确定问题是什么 我有这三个课程 Entity public class Widget Id GeneratedValue s
  • API 调用 datastore_v3.Put() 的请求太大

    我正在使用 google cloud sql 和 appengine 我正进入 状态com google apphosting api ApiProxy RequestTooLargeException The request to API
  • 如何为最终用户方便地启动Java GUI程序

    用户想要从以下位置启动 Java GUI 应用程序Windows 以及一些额外的 JVM 参数 例如 javaw Djava util logging config file logging properties jar MyGUI jar
  • 如何在 Play java 中创建数据库线程池并使用该池进行数据库查询

    我目前正在使用 play java 并使用默认线程池进行数据库查询 但了解使用数据库线程池进行数据库查询可以使我的系统更加高效 目前我的代码是 import play libs Akka import scala concurrent Ex
  • 在 HTTPResponse Android 中跟踪重定向

    我需要遵循 HTTPost 给我的重定向 当我发出 HTTP post 并尝试读取响应时 我得到重定向页面 html 我怎样才能解决这个问题 代码 public void parseDoc final HttpParams params n
  • Final字段的线程安全

    假设我有一个 JavaBeanUser这是从另一个线程更新的 如下所示 public class A private final User user public A User user this user user public void
  • JavaMail 只获取新邮件

    我想知道是否有一种方法可以在javamail中只获取新消息 例如 在初始加载时 获取收件箱中的所有消息并存储它们 然后 每当应用程序再次加载时 仅获取新消息 而不是再次重新加载它们 javamail 可以做到这一点吗 它是如何工作的 一些背
  • 操作错误不会显示在 JSP 上

    我尝试在 Action 类中添加操作错误并将其打印在 JSP 页面上 当发生异常时 它将进入 catch 块并在控制台中打印 插入异常时出错 请联系管理员 在 catch 块中 我添加了它addActionError 我尝试在jsp页面中打
  • 从 127.0.0.1 到 2130706433,然后再返回

    使用标准 Java 库 从 IPV4 地址的点分字符串表示形式获取的最快方法是什么 127 0 0 1 到等效的整数表示 2130706433 相应地 反转所述操作的最快方法是什么 从整数开始2130706433到字符串表示形式 127 0
  • 在两个活动之间传输数据[重复]

    这个问题在这里已经有答案了 我正在尝试在两个不同的活动之间发送和接收数据 我在这个网站上看到了一些其他问题 但没有任何问题涉及保留头等舱的状态 例如 如果我想从 A 类发送一个整数 X 到 B 类 然后对整数 X 进行一些操作 然后将其发送
  • 加密 JBoss 配置中的敏感信息

    JBoss 中的标准数据源配置要求数据库用户的用户名和密码位于 xxx ds xml 文件中 如果我将数据源定义为 c3p0 mbean 我会遇到同样的问题 是否有标准方法来加密用户和密码 保存密钥的好地方是什么 这当然也与 tomcat
  • 如何在 javadoc 中使用“<”和“>”而不进行格式化?

    如果我写

随机推荐