好的,所以我要构建的程序很简单。有五个按钮,名称从0到4。如果按下任何按钮,则控制台上将打印数字0到4。
我已经使用GridLayout将按钮放置在框架中。为了设置每个按钮,我创建了一个方法inicializarIG()
。
此inicializarIG()
方法创建一个由5个按钮组成的数组,并且在for循环内执行此操作:
令人惊讶的是,这个简单的程序无法正常工作。无论按下什么按钮,它始终会打印数字“5”:
注意:我必须将
index
var放在inicializarIG()
方法之外,以便满足监听器的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/