1

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); //} } 

}

3 Answers 3

2

Try using getName().equals("Thread1") instead.

equals compares the strings, == checks if the two strings are the same object.

Sign up to request clarification or add additional context in comments.

Comments

1

Try:

if (Thread.currentThread().getName().equals("Thread1")) 

or

if (Thread.currentThread().getName().compareTo("Thread1") > 0) 

Comments

1
  1. why do you have that check for the current threads name anyway? That thread will be the only one to call that method anyway.

  2. You must not compare String values using == as it checks for object identity. You should use Thread.currentThread().getName().equals("Thread1") instead.

  3. You should not interact with any Swing/AWT components outside of the Event Dispatch Thread!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.