You can use the same Listener
for multiple Label
s:
public static void main(String[] args)
{
final Display display = new Display();
Shell shell = new Shell(display);
GridLayout layout = new GridLayout(8, true);
layout.horizontalSpacing = 0;
layout.verticalSpacing = 0;
shell.setLayout(layout);
shell.setText("Chess");
/* Define listener once */
Listener listener = new Listener()
{
@Override
public void handleEvent(Event event)
{
/* event.widget is the source of the event */
if(event.widget instanceof Label)
{
System.out.println(event.widget.getData());
}
}
};
for(int i = 0; i < 64; i++)
{
Label label = new Label(shell, SWT.CENTER);
label.setText(i + "");
label.setData(i);
/* Use listener here */
label.addListener(SWT.MouseUp, listener);
label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
Color background = ((i + (i/8))%2 == 0) ? display.getSystemColor(SWT.COLOR_BLACK) : display.getSystemColor(SWT.COLOR_WHITE);
Color foreground = ((i + (i/8))%2 == 0) ? display.getSystemColor(SWT.COLOR_WHITE) : display.getSystemColor(SWT.COLOR_BLACK);
label.setBackground(background);
label.setForeground(foreground);
}
shell.pack();
shell.setSize(200, 200);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
It will print out the Label
s data on click.
Looks like this:
