初学者:JButton / Gridlayout(类似于扫雷)

时间:2013-04-13 20:45:05

标签: java swing jbutton grid-layout minesweeper

我是Java的初学者,最终我想为一个高级项目的机器人创建代码。我计划让机器人以指定的模式设置多米诺骨牌然后被击倒。我首先需要编写一个程序,允许我选择将多米诺骨牌放在网格上。然后我计划让程序为Arduino打印一个新程序。

作为测试和学习,我想用JButton制作一个20x40的网格。然后我想点击几个Jbuttons然后将Jbutton值添加到一个新数组。恩。我点击第1,第5,第30和第799按钮。然后,程序会将这些内容添加到array[0]=1array[2]=5;

的新数组中

我花了很多时间进行反复试验,并在线查看以下代码: 现在的问题是它似乎正在跳过Buttongrid方法(?)。如果我使方法public static void main(String [] args){,则动作监听器不起作用。

同样,我只是开始所以如果很多事情都错了,我不会感到惊讶。 请看一下它,帮我弄清楚我要解决的问题。 感谢

import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
public class ButtonGrid extends JFrame implements ActionListener  {
static int clicked[]=new int[800];  
static JButton button[]=new JButton[800];
static int x;
static int count=0;
int value;
ActionListener listen;
    public  ButtonGrid() { 
        JFrame frame= new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        GridLayout grid=new GridLayout(20,40);
        frame.setLayout(grid);
    //fill clicked with 0s////////////////////////////////////
            for (int c=0;c<=10;c++){
        clicked[c]=0;}
            for(x=0;x<800;x++){  
           button[x]= new JButton();
           button[x].setActionCommand(Integer.toString(x));
           frame.add(button[x]);
           button[x].addActionListener(this);
            }}
            public void actionPerformed (ActionEvent e){


            while(count<11){
                int newvalue=value;
                 value=Integer.parseInt( e.getActionCommand());  
                 if(value!=newvalue){
                    clicked[count]=this.value;
                    count=count+1;
                    System.out.println("Found");
                 }
                 else{
                     newvalue=value;
                     System.out.println("Looking...");}}
            }   public static void main(String [] args){
                        ButtonGrid b=new ButtonGrid();
                        if (count>10){
                        for (int t=0;t<=11;t++){
                            System.out.println(clicked[t]);
                                }
                            }
                        }
            }

1 个答案:

答案 0 :(得分:0)

这是因为你没有在主类中调用你的ButtonGrid框架,如下所示:

 public static void main(String[] args) {
        System.out.println("this prints and no window pops up. it skipped       the grid/frame code");
        ButtonGrid b = new ButtonGrid();
    }