Java 如何在循环外使用在for循环中创建的JButton?
Java How to use a JButton that created in for loop, outside the loop?
我的观点是如何在 for 循环之外使用方法。我不能在外面使用,因为所有按钮都是为循环创建的。每当我创建一个数组按钮时,我都会给按钮的一些属性,它们不起作用
private clicks = 0;
JButton[] test = new JButton[24];
for(i=0; i < 24; i++){
test[i] = new JButton("" + i);
test[i].setBackground(Color.YELLOW);
//and some properties ,action listener
if((clicks < 15) && clicks % 5 !=0 ) {
test[].setVisible(False);// i don't know what to write in "[]"
}
clicks++;
else if(clicks%5 == 0) {
JOptionPane.showMessageDialog(p1, calculateAverage(anArrayList));
} //calculate average is a method that i created it
}
test[].addActionListener(new ActionListener() {//i dont know what to write in []
public void actionPerformed(ActionEvent e) {
if((clicks < 15) && clicks % 5 !=0 ) {
test[].setVisible(False);// i don't know what to write in "[]"
}
clicks++;
else if(clicks%5 == 0) {
JOptionPane.showMessageDialog(p1, calculateAverage(anArrayList));
}
}
calculateAverage
方法总是给出相同的输出。我怎样才能解决这个问题?当我将 if-else
代码放在循环的外部时,我无法使用按钮。
不确定您要做什么,但我会猜测并说明:
- 您不需要数组来跟踪您的按钮
- 您不需要为每个按钮创建一个新的 ActionListener
- 创建按钮时应将 ActionListener 添加到按钮
相反,您创建了一个由所有按钮共享的通用 ActionListener,并在创建按钮时将侦听器添加到按钮。然后将按钮同时添加到面板,这样就不需要数组了。代码的基本结构可以是这样的:
ActionListener al = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
if (...)
button.setVisible( false );
}
};
for (...)
{
JButton button = new JButton(...);
button.addActionListener( al );
panel.add( button );
}
我的观点是如何在 for 循环之外使用方法。我不能在外面使用,因为所有按钮都是为循环创建的。每当我创建一个数组按钮时,我都会给按钮的一些属性,它们不起作用
private clicks = 0;
JButton[] test = new JButton[24];
for(i=0; i < 24; i++){
test[i] = new JButton("" + i);
test[i].setBackground(Color.YELLOW);
//and some properties ,action listener
if((clicks < 15) && clicks % 5 !=0 ) {
test[].setVisible(False);// i don't know what to write in "[]"
}
clicks++;
else if(clicks%5 == 0) {
JOptionPane.showMessageDialog(p1, calculateAverage(anArrayList));
} //calculate average is a method that i created it
}
test[].addActionListener(new ActionListener() {//i dont know what to write in []
public void actionPerformed(ActionEvent e) {
if((clicks < 15) && clicks % 5 !=0 ) {
test[].setVisible(False);// i don't know what to write in "[]"
}
clicks++;
else if(clicks%5 == 0) {
JOptionPane.showMessageDialog(p1, calculateAverage(anArrayList));
}
}
calculateAverage
方法总是给出相同的输出。我怎样才能解决这个问题?当我将 if-else
代码放在循环的外部时,我无法使用按钮。
不确定您要做什么,但我会猜测并说明:
- 您不需要数组来跟踪您的按钮
- 您不需要为每个按钮创建一个新的 ActionListener
- 创建按钮时应将 ActionListener 添加到按钮
相反,您创建了一个由所有按钮共享的通用 ActionListener,并在创建按钮时将侦听器添加到按钮。然后将按钮同时添加到面板,这样就不需要数组了。代码的基本结构可以是这样的:
ActionListener al = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
if (...)
button.setVisible( false );
}
};
for (...)
{
JButton button = new JButton(...);
button.addActionListener( al );
panel.add( button );
}