Reputation: 4112
I wrote a simple program with java swing which suppose to start another thread and in that thread a JForm will show up when I click a button. But JForm is not showing up... I used if (Thread.currentThread().getName() == "Thread1")
to do the specific task for that thread, when I comment that program runs perfectly, I can't understand why it is not going to the if block... Please someone help me with this...
Thanks in advance!
Here is the code,
public class Test extends JFrame implements ActionListener {
JPanel panel;
JButton button;
public Test() {
setVisible(true);
setSize(300, 300);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
panel = new JPanel();
button = new JButton("click me");
button.addActionListener(this);
panel.add(button);
add(panel, BorderLayout.CENTER);
}
public static void main(String[] args) {
Test tst=new Test();
}
@Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource()==button){
System.out.println("test");
test2 test = new test2();
Thread tr1 = new Thread(test);
tr1.setName("Thread1");
tr1.start();
}
}
}
class test2 implements Runnable{
public void run() {
//if (Thread.currentThread().getName() == "Thread1") {
System.out.println("inside thread");
JFrame frame2=new JFrame();
frame2.setVisible(true);
frame2.setSize(300, 300);
frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//}
}
}
Upvotes: 1
Views: 340
Reputation: 308001
why do you have that check for the current threads name anyway? That thread will be the only one to call that method anyway.
You must not compare String
values using ==
as it checks for object identity. You should use Thread.currentThread().getName().equals("Thread1")
instead.
You should not interact with any Swing/AWT components outside of the Event Dispatch Thread!
Upvotes: 1
Reputation: 4870
Try:
if (Thread.currentThread().getName().equals("Thread1"))
or
if (Thread.currentThread().getName().compareTo("Thread1") > 0)
Upvotes: 1
Reputation: 91260
Try using getName().equals("Thread1")
instead.
equals
compares the strings, ==
checks if the two strings are the same object.
Upvotes: 2