好的,所以我要构建的程序很简单。有五个按钮,名称从 0 到 4。如果按下其中任何一个按钮,那么控制台将打印数字 0 到 4。
我使用 GridLayout 将按钮放置在框架中。为了设置每个按钮,我创建了一个方法 inicializarIG()
。
此 inicializarIG()
方法创建一个包含 5 个按钮的数组,并在 for 循环中执行以下操作:
- 为按钮数组中的每个单元格创建一个按钮实例。
- 为每个按钮设置一个 mouseListener。每个 Listener 中要打印的值是不同的,它由循环的索引决定(我想通过使用索引来实现!)。
- 将按钮添加到主框架。
令人惊讶的是,这个简单的程序无法正常工作。无论按下什么按钮,它总是打印数字“5”:
注意:我必须将 index
var 放在 inicializarIG()
方法之外,以便满足 Listeners 的 var 范围。我不知道这个问题是否相关,只是说因为它可能会有所帮助。
代码:
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class IGrafica {
private JFrame frame;
public int index=0;
public IGrafica(){
frame = new JFrame();
configureFrame();
inicializarIG();
}
public void configureFrame(){
frame.setBounds(100,100,400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout(1,5)); //
}
public void inicializarIG(){
//Buttons
JButton [] botones = new JButton [5];
//Loop to set up buttons and add the mouseListener
for (index = 0; index < botones.length; index++) {
botones[index] = new JButton(Integer.toString(index));
//Set up each listener
botones[index].addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
System.out.println(index);
//texto.setBackground(colores[index]);
}
});
//Add the button
frame.getContentPane().add(botones[index]);
}
}
public void visualizate(){
frame.setVisible(true);
}
public static void main(String[] args) {
IGrafica window = new IGrafica();
EventQueue.invokeLater(new Runnable() {
public void run() {
window.visualizate();
}
});
}
}
提前致谢。欢迎任何想法。
耶稣
最佳答案
首先,不要为此使用 MouseListener,而是使用 ActionListener,因为这最适合按钮。接下来,你需要记住你的监听器是它自己的一个类,它需要一个自己的变量来存储它自己的索引,否则它会使用循环索引的最终值,这不是你想要的。这或者使用 ActionEvent 的 actionCommand 属性,一个与按钮文本匹配的值。所以:
botones[index].addActionListener(new MyActionListener(index));
和
// a private inner class
private class MyActionListener implements ActionListener {
private int index;
public MyActionListener(int index) {
this.index = index;
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("index is: " + index);
System.out.println("Action Command is: " + e.getActionCommand());
}
}
或者如果你想使用匿名内部类:
botones[index].addActionListener(new ActionListener() {
private int myIndex;
{
this.myIndex = index;
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("index is: " + myIndex);
}
});
关于Java Swing为一组按钮添加鼠标监听器(内部类)导致故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32898192/