【发布时间】:2017-04-18 17:14:58
【问题描述】:
我正在使用几个按钮在 java 中制作一个猜谜网格游戏。该程序使用 java gridlayout 布局,当单击按钮时,我希望它将其 GridLayout 位置(不是 x 和 y)添加到数组中。
这是需要单元格位置查找器的一段代码。
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);
}
}
【问题讨论】:
-
如果这不是重复的,请编辑您的问题以包含一个minimal reproducible example,以显示您修改后的方法。
标签: java swing user-interface jbutton