0

I'm trying to do look alike chess-board in SWT, JAVA. I tried to do array of buttons, but the color of a button can't be changed (after a long research I have done!). So I did an array of labels that I can change their color, but now I cannot handle them in one listener, and I don't think that 64 copy-paste listeners are the right thing to do. However, I found the setActionCommand is not for labels at all.

Do you have any suggestions what can I do to fix that out?

Thanks.

zvika
  • 23
  • 1
  • 4

1 Answers1

4

You can use the same Listener for multiple Labels:

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 Labels data on click.

Looks like this:

enter image description here

Baz
  • 36,440
  • 11
  • 68
  • 94