简体   繁体   中英

Netbeans GUI and dealing with Threads inside “main”

I'm using Netbeans IDE to make a GUI. The point is that when I add a JFrame frame to my project package:

创建新的Jframe

it declares every variable of the frame (button, textArea, ..etc) as private and can't change it. the problem comes when I'm trying to create thread that uses these variables in run() method inside main method.

note: I've tried to create separate class extends Thread, I can't call it in the main unless I declare it as static , then same problem rises again.

how can I make thread that uses these variables (ie appending text to text area) inside the main ?

Do not try to do that. UI elements shall not be accessed from another thread than the Event Dispatch Thread. You will find references on Oracle Java tutorial Concurrency in Swing . Extracts (emphasize mine) :

A Swing programmer deals with the following kinds of threads:

  • Initial threads, the threads that execute initial application code.
  • The event dispatch thread, where all event-handling code is executed. Most code that interacts with the Swing framework must also execute on this thread.
  • Worker threads, also known as background threads, where time-consuming background tasks are executed.

Some Swing component methods are labelled "thread safe" in the API specification; these can be safely invoked from any thread. All other Swing component methods must be invoked from the event dispatch thread . Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM