我不認爲這是一個非常複雜的問題,但我不知道要解決這個問題。如果你看看我下面的代碼,它使用一個JButton的與X,Y參數創建按鈕的網格,就像這樣:爲參數能夠正常工作的單個JButton製作actionListener
現在,如果你對代碼的底部看在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");
}
}
}
我會擴展JButton來創建我自己的版本,其中將包含一個變量'name'。然後每當按下,我會得到的名稱(如2-2),並打印出來... – Plirkee
'grid [x] [y] .setActionCommand(x +「:」+ y);''public void actionPerformed(ActionEvent e ){ JButton button =(JButton)e.getSource(); System.out.println(Button「+ button.getActionCommand()+」was pressed。「); }' –