如何获取Java中的JButton的gridlayout单元格位置?
我正在使用几个按钮在java中进行猜测网格游戏。该程序使用java gridlayout布局,当单击按钮时,我希望它将GridLayout位置(不是x & y)添加到数组中。如何获取Java中的JButton的gridlayout单元格位置?
这里是需要单元格定位器的代码条。
public void actionPerformed(ActionEvent e)
{
if(placementLimit < 5){
//placementlimit is limit to buttons clicked
JButton clickedButton = (JButton)e.getSource();
clickedButton.setBackground(Color.RED);
/* something like: int pos = clickedButton.getGridPos
* arrayplacedpositions.add(pos);
*/
placementLimit++;
}
我没有做一个JPanel所以 整个项目是在这里:
/* Guessing game GoldMiner By Alexander Smirnov
* A Computer Game where you hide and place gold.
*/
package standard;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.*;
public class game extends JPanel
{
JButton buttons[] = new JButton[64];
int placementLimit = 0;
ArrayList goldPos = new ArrayList();
public game()
{
setLayout(new GridLayout(8,8));
initializebuttons();
}
public void initializebuttons()
{
for(int i = 0; i <= 63; i++)
{
buttons[i] = new JButton();
buttons[i].setText("");
buttons[i].addActionListener(new buttonListener());
add(buttons[i]);
}
}
private class buttonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(placementLimit < 5){
JButton clickedButton = (JButton)e.getSource();
clickedButton.setIcon(new ImageIcon("/Users/Administrator/Desktop/gold2.jpg"));
clickedButton.setBackground(Color.RED);
JPanel.getComponents();
placementLimit++;
} else {
JOptionPane.showMessageDialog(null, "You have placed the maximum amount of gold!");
}
}
}
public static void main(String[] args)
{
JFrame window = new JFrame("GoldMiner");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(new game());
window.setBounds(300,200,300,300);
Container c = window.getContentPane();
window.setVisible(true);
}
}
这不是最容易做的事情......有可能会握住你的JButton
S IN更有用一个2D阵列,或者更好地保存一张JButton
的位置图。
如果你真的必须辨别从按钮的栅格单元,称之为
JPanel.getComponents()
(或任何父容器是),并找到你的按钮在那里。然后做数学。
说你在指数6
则由于网格为x由x和y分拿到行,国防部通过X拿到列中找到它。
所以说网格IX的4x4
6/4是1,所以你是与索引1(第二行)
6%4为2的行中,所以你与列索引2(第三列)
你可以给一个代码示例。 –
此外,我的按钮是使用for循环形成的,所以我无法手动调用每个按钮。 –
(1+)的好建议。另外,我不确定它是否是一个kludge,但是在创建时使用'putClientProperty(...)'方法可以将网格位置填充到JButton中。 –
如果这不是重复的,请编辑您的问题以包含显示您修改方法的[mcve]。 – trashgod