【发布时间】:2020-12-24 16:26:13
【问题描述】:
问题:下面是一些代码来制作一个充满按钮的框架。单击按钮后,我需要知道单击按钮的坐标。程序随后将检查该特定图块的状态,并根据状态将其更改为某种颜色。我在收回这个坐标时遇到了一些问题,有人可以帮我吗? (我只是在学习如何用 Java 编程,所以我的代码可能并不理想)
代码:
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);
}
});
}
}
【问题讨论】:
-
为按钮设置一个id,并使用HashMap将其链接到一个Point。
-
coordinates是什么意思?放置位置(x、y)还是网格位置(行、列)?