【发布时间】:2017-07-31 19:18:52
【问题描述】:
我创建了一个带有许多按钮的板,例如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[][] button而不是构造函数
标签: java swing loops button actionlistener