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)
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); } }); } }
Advertisement
Answer
If by coordinates
you mean the actualx
and y
placement location of the button clicked upon then you can use this within your buttons ActionPerformed event:
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:
public void actionPerformed(ActionEvent e) { JButton btn = (JButton)e.getSource(); System.out.println(btn.getName()); }