Skip to main content

Jbutton in thread prints 0 when fetching constructor value

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
1 reply [Last post]
dinud123
Offline
Joined: 2013-03-20

hello, Two classes ..
public class constg {
public static void main(String[] args)
{
threadconst tc=new threadconst();
tc.start();
tc=new threadconst(5);
tc.stop();
}
}

public class threadconst extends Thread {
JFrame frame=new JFrame();
JButton ack=new JButton("ACKNOWLEDGE ME !!");
int p;
threadconst(int i)
{
this.p=i;
System.out.println(p); //prints 5
}
public threadconst() {
// TODO Auto-generated constructor stub
}

public void run()
{
ack.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
System.out.println("button "+p); ///prints button 0
}
});
ack.setBounds(0,0,300,300);
frame.add(ack);
frame.setVisible(true);
}
}

y does the button variable print value 0 instead of 5 ??
How to overcome this problem. ? plzz help ??

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
MackSix
Offline
Joined: 2013-03-27

You should use the code tags (button with "<>") so your code is readable.

Why do you think p is equal to 5 when you start the thread with an object where p is uninitialized?

public class constg {

    public static void main(String[] args) {
        threadconst tc = new threadconst();
        tc.start();
        tc = new threadconst(5);
        tc.stop();
    }

}

public class threadconst extends Thread {

    JFrame frame = new JFrame();
    JButton ack = new JButton("ACKNOWLEDGE ME !!");
    int p;

    threadconst(int i) {
        this.p = i;
        System.out.println(p); //prints 5
    }

    public threadconst() {
// TODO Auto-generated constructor stub
    }

    public void run() {
        ack.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                System.out.println("button " + p); ///prints button 0
            }
        });
        ack.setBounds(0, 0, 300, 300);
        frame.add(ack);
        frame.setVisible(true);
    }

}