简体   繁体   English

如何检测点击了哪个按钮 - Java

[英]How to detect which button was clicked - Java

Problem: below some code to make a frame filled with buttons.问题:下面是一些代码来制作一个充满按钮的框架。 After the button is clicked, I would need to know the coordinates of the button clicked.单击按钮后,我需要知道单击按钮的坐标。 The program will afterwards check the status of that specific tile and depending on the status it should change to a certain color.程序随后将检查该特定图块的状态,并根据状态将其更改为某种颜色。 I'm having some issues when retracting this coordinate, could someone help me?我在收回这个坐标时遇到了一些问题,有人可以帮我吗? (I'm only just learning how to program in Java, so my code might not be ideal) (我只是在学习如何在 Java 中编程,所以我的代码可能并不理想)

Code:代码:

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

public class GUIBoard {

    JPanel buttonPanel = new JPanel();
    JButton button = new JButton();
    JFrame frame;

    ButtonClicked clicked = new ButtonClicked();

    public GUIBoard(String title, int nbRows, int nbColumns) {

        frame = new JFrame(title);
                
        buttonPanel.setLayout(new GridLayout(nbRows, nbColumns));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.BOTH;
    
        for (int i = 0; i < nbRows; i++) {
            for(int j = 0; j < nbColumns; j++) {
                button = new JButton();
                button.setBackground(Color.LIGHT_GRAY);
                button.addActionListener(clicked);
                gbc.gridx = j;
                gbc.gridy = i;
                buttonPanel.add(button, gbc);
            }
        }
    
        frame.setPreferredSize(new Dimension(1000, 600));
        frame.getContentPane().add(buttonPanel, BorderLayout.CENTER);

        frame.pack();
        frame.setVisible(true);
    
    }

    private class ButtonClicked implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
        
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                new GUIBoard("Batlleship Board", 10,10);
            }
        });
    }
}

Now that I think I have understood what you want to do I am going to give you a new and easier approach: Here is the code, you just need to use the method getSource() to get an instance of the button which has been pressed .现在我想我已经理解了您想要做什么,我将为您提供一种新的更简单的方法:这是代码,您只需要使用方法getSource()来获取已按下按钮的实例. Then you change the color .然后你改变颜色

public class GUIBoar {

JPanel buttonPanel = new JPanel();
JButton button = new JButton();
JFrame frame;


public GUIBoar(String title, int nbRows, int nbColumns) {

    frame = new JFrame(title);

    buttonPanel.setLayout(new GridLayout(nbRows, nbColumns));
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill = GridBagConstraints.BOTH;

    for (int i = 0; i < nbRows; i++) {
        for (int j = 0; j < nbColumns; j++) {
            button = new JButton();
            button.setBackground(Color.LIGHT_GRAY);
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e){
                    Object source = e.getSource();
                    JButton b = (JButton)source;
                    b.setBackground(Color.RED); //IMAGINE THATS THE COLOR
                }
            });
            gbc.gridx = j;
            gbc.gridy = i;
            buttonPanel.add(button, gbc);
        }
    }

    frame.setPreferredSize(new Dimension(1000, 600));
    frame.getContentPane().add(buttonPanel, BorderLayout.CENTER);

    frame.pack();
    frame.setVisible(true);

}


public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new GUIBoar("Batlleship Board", 10, 10);
        }
    });
}

} }

If by coordinates you mean the actual x and y placement location of the button clicked upon then you can use this within your buttons ActionPerformed event:如果coordinates是指单击按钮的实际xy放置位置,则可以在按钮ActionPerformed事件中使用它:

public void actionPerformed(ActionEvent e) {
    JButton btn = (JButton)e.getSource();
    System.out.println(btn.getX() + ", " + btn.getY());
}

Will print the top left location of the button clicked upon.将打印单击按钮的左上角位置。 This isn't very helpful however since these locations can change if the Form is resized in any way.但是,这不是很有帮助,因为如果以任何方式调整表单的大小,这些位置可能会发生变化。

If you mean by grid location as in the row and column of the button clicked upon then the easiest would be to ensure that an identifier is applied to each of the buttons by placing the grid location into the buttons Name property, when creating your buttons, for example:如果您指的是单击按钮的行和列中的网格位置,那么在创建按钮时,最简单的方法是通过将网格位置放入按钮名称属性中来确保将标识符应用于每个按钮,例如:

for (int i = 0; i < nbRows; i++) {
    for (int j = 0; j < nbColumns; j++) {
        button = new JButton();
        // Apply an identifier to the Button:
        button.setName(new StringBuilder("Button_").append(i)
                        .append(",").append(j).toString());
        button.setBackground(Color.LIGHT_GRAY);
        button.addActionListener(clicked);
        gbc.gridx = j;
        gbc.gridy = i;
        buttonPanel.add(button, gbc);
    }
}

Then in your buttons ActionPerformed event:然后在您的按钮ActionPerformed事件中:

public void actionPerformed(ActionEvent e) {
    JButton btn = (JButton)e.getSource();
    System.out.println(btn.getName());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM