2017-03-17 50 views
-1

我不認爲這是一個非常複雜的問題,但我不知道要解決這個問題。如果你看看我下面的代碼,它使用一個JButton的與X,Y參數創建按鈕的網格,就像這樣:爲參數能夠正常工作的單個JButton製作actionListener

enter image description here

現在,如果你對代碼的底部看在actionListener中,有一個if語句打印出「2-2已被按下!」如果按鈕2-2已被按下。對於這個程序,我打算讓網格根據用戶輸入的大小進行調整(例如,用戶輸入3,5並創建一個3×5的按鈕網格),所以爲每個按鈕編寫if語句看起來像是一個白癡會做...

所以我的問題是這樣的:是否有可能使actionListener能夠做一些事情,如打印按鈕的座標而不做一些荒謬的事情,比如爲每個按鈕創建一個if語句?

我試圖做的事情就像從裏面ActionListener的引用x和y,但它不工作,因爲他們是在爲公衆測試構造的循環,如果

import java.awt.GridLayout; //imports GridLayout library 
import java.awt.event.ActionListener; 
import java.awt.event.ActionEvent; 
import java.awt.Color; 

public class Testing extends JFrame implements ActionListener { 

    JFrame frame = new JFrame(); //creates frame 
    JButton[][] grid; //names the grid of buttons 



    public Testing(int width, int length) { //constructor 
     frame.setLayout(new GridLayout(width, length)); //set layout 
     grid = new JButton[width][length]; //allocate the size of grid 

     for (int y = 0; y < length; y++) { 
      for (int x = 0; x < width; x++) { 
       grid[x][y] = new JButton("(" + x + "," + y + ")"); //creates new button  
       frame.add(grid[x][y]); //adds button to grid 
       grid[x][y].addActionListener(this); 
      } 
     } 

     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.pack(); //sets appropriate size for frame 
     frame.setSize(1000, 1000); 
     frame.setVisible(true); //makes frame visible 

    } 

    public static void main(String[] args) { 
     new Testing(5, 5); /*length and width of the grid in terms of number  of buttons */ 
    } 

    public void actionPerformed(ActionEvent e) { 
     if (e.getSource() == grid[2][2]) { 
      System.out.println("2-2 Has been pressed"); 
     } 

    } 

    } 
+0

我會擴展JButton來創建我自己的版本,其中將包含一個變量'name'。然後每當按下,我會得到的名稱(如2-2),並打印出來... – Plirkee

+0

'grid [x] [y] .setActionCommand(x +「:」+ y);''public void actionPerformed(ActionEvent e ){ JButton button =(JButton)e.getSource(); System.out.println(Button「+ button.getActionCommand()+」was pressed。「); }' –

回答

0

所以寫的每個按鈕的聲明看起來像一個白癡會做...

正確,但創建一個網格來獲取用戶輸入也沒有任何意義。

也許可能使用兩個組合框或兩個JSpinners來表示x/y值。

然後你點擊一個「製作網格」按鈕,並從兩個組件獲得值。

另一種選擇是使用按鈕的「行動命令」:

JButton button = new JButton("(" + x + "," + y + ")"); 
button.setActionCommand(x + ":" + y); 
button.addActionListener(this); 
grid[x][y] = button;button  
frame.add(button); //adds button to grid 

然後在ActionListener的,您可以訪問的動作命令:

String command = event.getActionCommand(); 
String[] values = command.split(":"); 
int x = Integer.parseInt(values[0]); 
int y = ... 

或者使用了雙迴路創建按鈕,那麼爲什麼你不能使用雙循環來搜索按鈕?

+0

第二種解決方案效果很好,非常感謝您的幫助! – InvalidGuest