我正在使用幾個按鈕在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);
}
}
如果這不是重複的,請編輯您的問題以包含顯示您修改方法的[mcve]。 – trashgod