2013-04-13 43 views
1

我是一名Java初學者,最終我想爲我爲高級項目製作的機器人創建代碼。我正在計劃讓機器人以特定的模式設置多米諾骨牌然後被擊倒。我首先需要編寫一個程序,讓我可以選擇將多米諾骨牌放在網格上。然後,我計劃讓這個程序爲Arduino打印一個新程序。初學者:JButton/Gridlayout(類似於掃雷)

作爲一個測試和學習,我想用JButtons做一個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]); 
           } 
          } 
         } 
      } 
+0

被格式化一樣,你實際的源代碼?那會讓我頭疼...... – syb0rg

回答

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(); 
    } 
+0

非常感謝。那樣做了。對此,我真的非常感激。我的新問題是while循環的結構,它將前10個單擊的按鈕值添加到單擊[]的int數組中,然後將其打印出來。循環卡在else/listening區域,永遠不會讓我有機會點擊另一個按鈕。我更新了上面的代碼。 – user2278269

+0

我不知道你想在你的while循環中做什麼,但顯然你的代碼將永遠循環,因爲:1-'int newvalue = value;'2-'if(value!= newvalue)'這將是方程'1'永遠爲'false',所以它永遠不會執行,並會進入'else'語句'newvalue = value;',其中你沒有改變'count',所以它會='0' –

+0

this是你卡在哪裏,所以告訴我你想要使用它的算法:) –