Modification of variables passed by parameters

0

Is it possible to change a button passed by a parameter?

I have a main class and a secondary ...

In the main class I instantiate one of the secondary one by passing a string and a button.

Secundaria s = new Secundaria (String s, Botao B);

In the secondary class I have to paint this button B. I can not do this in the main class, I would have to modify the main button in the secondary. How?

I tried to declare an auxiliary button in the secondary which receives button B, and paint this auxiliary, but did not work.

In my main class I have this:

PingThread reitoria = new PingThread ("200.132.148.6",d.jButton3);
   reitoria.start();  

And in my class I test if a server is online, I want to paint the button, I use this:

public class PingThread  extends java.lang.Thread  {

public  JButton aux;   
String ip;
public  JFramePrincipal d = new JFramePrincipal();

 public PingThread( String ip, JButton B) { // ip do servidor e botão correspondente 
    this.ip = ip; 
    aux = B;
 }

 @Override
 public void run() {

        Ping p = new Ping();
        Reitoria R = new Reitoria();

        p.runSystemCommand("ping " +ip);
    if (p.retorno == true) { // Servidor Online
        d.setVisible(true);
        aux.setBackground(Color.red);
        System.out.println(p.retorno); // true if online
    }
    else {
        System.out.println(p.retorno); // false else
    }
 } //fim run()

 } //fim classe

In case I wanted to paint the button B I get in the PingThread class constructor.

    
asked by anonymous 18.03.2015 / 18:26

1 answer

1

You may not be observing the expected result simply because you are trying to access Windows windows from a secondary thread, and that is illegal.

You should not try to change the appearance of a button from another thread. You need to synchronize this other thread first, so the button painting will actually occur on the main thread. Try using the synchronized method, like this:

 @Override
 public void run() {

        Ping p = new Ping();
        Reitoria R = new Reitoria();

        p.runSystemCommand("ping " +ip);
    if (p.retorno == true) { // Servidor Online
        synchronized(this) {
            d.setVisible(true);
            aux.setBackground(Color.red);
            System.out.println(p.retorno); // true if online
        }
    }
    else {
        System.out.println(p.retorno); // false else
    }
 }
    
18.03.2015 / 20:43