Question

Working on my first java swt program and I am having trouble, possibly a stupidity issue! I am trying to create a basic network program to listen for connections, i have a button and I want to start the socket then change a label to display " server listening" or whatever

Here is the button

Button startServerBtn = new Button(shlChattybox, SWT.NONE);
        startServerBtn.addSelectionListener(new SelectionAdapter() {

            ServerSocket serversocket = new ServerSocket(PORT); 

Can I not change the text of a label here ??

            serverStatusLbl2.setText("listening!"); 

            public void widgetSelected(SelectionEvent e) {
            }
        });
    startServerBtn.setFont(SWTResourceManager.getFont("Segoe UI", 16, SWT.BOLD));
    startServerBtn.setBounds(53, 63, 260, 75);
    startServerBtn.setText("Start Server");

    listeningPortTxt = new Text(shlChattybox, SWT.BORDER);
    listeningPortTxt.setBounds(143, 26, 76, 21);

    Label listeningPortLbl = new Label(shlChattybox, SWT.NONE);
    listeningPortLbl.setBounds(53, 29, 84, 15);
    listeningPortLbl.setText("Listening Port: ");

    Label serverStatusLbl1 = new Label(shlChattybox, SWT.NONE);
    serverStatusLbl1.setBounds(53, 157, 84, 15);
    serverStatusLbl1.setText("Server Status:");
Was it helpful?

Solution

There are two ways to do this:

  1. Make the Label a field of the class
  2. Make the Label final

Here is an example:

private Label fieldLabel = new Label(shell, SWT.NONE);

public void testMethod()
{
    Button button = new Button(shell, SWT.PUSH);
    button.setText("Print");

    final Label finalLabel = new Label(shell, SWT.NONE);

    button.addListener(SWT.Selection, new Listener(){
        @Override
        public void handleEvent(Event e)
        {
            fieldLabel.setText("TEXT");
            finalLabel.setTexT("TEXT");
        }
    })
}

This is nothing specific to SWT, so you might want to read something about closure in programming.

Here is a related question on SO where the infamous Jon Skeet posted an answer...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top