我目前正在更改扩展按钮,使其使用合成,并在将MouseListeners转换为动作侦听器的过程中。我需要知道它何时被点击并且isRollover();我是GUI新手,非常感谢帮助。如何在不同的类中正确声明按钮?我在哪里在EmptySpace类中添加actionListeners?
public class EmptySpace{
private JButton button;
protected int x;
protected int y;
protected String name;
public EmptySpace(String text, int x, int y){
this.name = text;
this.x = x;
this.y = y;
button = new JButton(text);
}
public String toString(){
return "Name: " + name + " Xcoords: " + x + " Ycoords: " + y;
}
public JButton getButton(){
return button;
}
}
不同的班级
for (int i = 0; i < lengthx*lengthy; i++) {
if(i<lengthx){
x = i+1;
}else x = i % lengthx+1;
if(i<lengthx){
y=1;
}else y = i/lengthx+1;
String xString = Integer.toString(x);
String yString = Methods.getChar(y);
buttons[x-1][y-1] = new EmptySpace(xString+yString,x,y);
buttons[x-1][y-1].setPreferredSize(new Dimension(25, 25)); //error
buttons[x-1][y-1].setBackground(Color.WHITE); //error
buttons[x-1][y-1].setText(""); //error
buttons[x-1][y-1].setToolTipText(xString+yString); //error
pane.add(buttons[x-1][y-1]); //error
答案 0 :(得分:0)
如果要向按钮而不是鼠标侦听器添加动作侦听器,请首先确保已导入java.awt.event 像这样在你的按钮上添加一个actionlistener:
button.addActionListener(new myButtonListener());
然后创建一个内部类,其中包含动作侦听器的名称,如下所示:
public class myButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ev){
//do what you want your button to do
}
}
确保该函数始终被称为已执行的操作,并始终将actionEvent作为参数。