我正在尝试创建数量为i * j的按钮。
在每个按钮上我想添加一个mouseUp动作,但是出现错误。
我试图创建一个“ Line”类来处理侦听器事件,但失败了。
这是我目前拥有的:
protected void createContents() {
// Connect to prolog engine
Query.hasSolution("use_module(library(jpl))"); // only because we call e.g. jpl_pl_syntax/1 below
String t1 = "consult('dots_lines.pl')";
Query.hasSolution(t1);
// Build GUI
shell = new Shell();
shell.setSize(450, 300);
shell.setText("SWT Application");
shell.setLayout(null);
txtDotsAndLines = new Text(shell, SWT.BORDER);
txtDotsAndLines.setBounds(175, 10, 86, 21);
txtDotsAndLines.setText("Dots and lines");
Button btnStartGame = new Button(shell, SWT.NONE);
btnStartGame.setBounds(180, 226, 70, 25);
btnStartGame.setText("Start Game");
// TODO: Play with sizes
int size = 5;
Line[] lines = new Line[size * (size - 1)];
// Buttons are line
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size; j++) {
lines[i] = new Line(shell, SWT.NONE);
lines[i].setBounds(100 + i * 35,54 + j * 13,32,11);
lines[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
lines[i].setEnabled(false);
lines[i].setBackground(Display.getDefault().getSystemColor(SWT.COLOR_GREEN));
String t4 = "move([[line(9,10,cpu),line(11,16,cpu),line(16,17,cpu),line(17,22,p1),line(5,6,p1),line(2,3,p1),line(1,2,p1)],cpu],4,X).";
System.out.println("each solution of " + t4);
}
});
}
}
}
这是Line类:
public class Line extends Button {
public Line(Composite parent, int style) {
super(parent, style);
// TODO Auto-generated constructor stub
}
protected void checkSubclass() {
// Disable the check that prevents sub-classing of SWT components
}
public void mouseUp(MouseEvent e) {
Line.this.setEnabled(false);
Line.this.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_GREEN));
String t4 = "move([[line(9,10,cpu),line(11,16,cpu),line(16,17,cpu),line(17,22,p1),line(5,6,p1),line(2,3,p1),line(1,2,p1)],cpu],4,X).";
System.out.println("each solution of " + t4);
}
public void pc() {
Line.this.setEnabled(false);
Line.this.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_RED));
}
我得到的错误是: 封闭范围中定义的局部变量i必须是final或有效的final。
非常感谢。
答案 0 :(得分:2)
您不能在鼠标适配器匿名类中引用i
,因为其值会更改。而是使用:
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size; j++) {
final Line line = new Line(shell, SWT.NONE);
lines[i] = line;
line.setBounds(100 + i * 35,54 + j * 13,32,11);
line.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(final MouseEvent e) {
line.setEnabled(false);
line.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_GREEN));
...
}
});
}
}
在这里final Line line
创建了可以在侦听器中引用的行的最终实例。