0
我創建了一個包含多個按鈕的板, 900+。由於這是很多工作,我認爲我會循環做。但是現在我想爲每個按鈕添加一個ActionListener,這些按鈕將爲行i和列j中的按鈕賦予arrary number [i] [j]值1.我不認爲有任何方法可以做到這一點,它按鈕按鈕。我已經期待你的回答。在這裏我的代碼:在循環中創建的訪問按鈕
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JButton;
public class MakeMotive {
int howManyButtonsVer = 34;
int howManyButtonsHor = 27;
int sideLength = 50;
int [][] number = new int [howManyButtonsHor+1][howManyButtonsVer+1];
JButton[][] button = new JButton [howManyButtonsHor+1][howManyButtonsVer+1];
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MakeMotive window = new MakeMotive();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MakeMotive(){
frame = new JFrame("Menu");
frame.getContentPane().setBackground(Color.yellow);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.getContentPane().setLayout(null);
frame.setVisible(true);
for(int i = 0; i<=howManyButtonsHor; i++){
for(int j = 0; j<=howManyButtonsVer; j++){
button[i][j] = new JButton();
button[i][j].setBounds(sideLength*i, sideLength*j, sideLength,sideLength);
button[i][j].setFont(new Font("Tahoma",Font.PLAIN, 10));
button[i][j].setBackground(Color.green);
button[i][j].setText(i+"a"+j);
frame.getContentPane().add(button[i][j]);
button[i][j].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
}
};
}
}
在字段中聲明'JButton [] []按鈕'而不是構造函數 –