Can I execute a thread JPanel?

I want my Jpanel to do a bouncing ball. So I decided to use a thread to update the coordinates regularly. How do I set the panel to visible and at the same time run run()? As you will see, it doesn't work (Code for drawing I haven't placed yet. Instead I placed System.out.println("hello"); to see if it runs):
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
public class bouncingBall extends JPanel implements Runnable
     private int balls;
     private int ballCount;
     public bouncingBall()
          setSize(500,500);
          addMouseListener(
               new MouseAdapter()
                    public void mouseClicked(MouseEvent e)
                    public void mousePressed(MouseEvent e)
                    public void mouseReleased(MouseEvent e)
          ExecutorService threadExecutor = Executors.newFixedThreadPool( 1 );
          threadExecutor.execute( Thread.currentThread() );
     public void run()
          while(true)
               System.out.println("Hello");     
     public void paintComponent(Graphics g)
     public static void main(String args[])
          JFrame cage = new JFrame("Bouncing Balls");
          bouncingBall app = new bouncingBall();
          cage.setSize(app.getSize());
          cage.add(app);
          cage.setVisible(true);
     }

A JPanel already runs within its own thread... kind
of.
Swing usually works with two threads: one that wraps
up all the displaying objects (this is the one you
create) and another one (which you have no access
to), which takes care of all the event handling and
rendering.
(Ironically, I said this way to often in the last few
days:) Avoid multithreading in Swing/AWT! If you need
anything time based, use the swing timer. If you
still need other threads, make sure that they don't
contain any Swing/AWT components, but just update any
status.
DON'T !! try to split up your displaying items onto
several threads! This might cause unpredictable
lockdowns!What about this new paradigm I'm reading about in the latest Swing books that says there is a flaw in the traditional way of creating a JFrame, e.g.
JFrame aWindow = new JFrame("title");
aWindow.setVisible(true);that makes them not thread safe? The new model for creating JFrames says you need to add them to the event queue. That seems to belie your statement that we don't have access to the "other thread' that handles events.
Actually, below is a Hello World example of the new method for creating a JFrame that I found in the java docs(ugly!). It involves two steps:
1) Create the JFrame inside a method
2) Attach the method to the event dispatching thread
import javax.swing.*;       
public class HelloWorldSwing {
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
    private static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);
        //Create and set up the window.
        JFrame frame = new JFrame("HelloWorldSwing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Add the ubiquitous "Hello World" label.
        JLabel label = new JLabel("Hello World");
        frame.getContentPane().add(label);
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
}http://java.sun.com/docs/books/tutorial/uiswing/learn/example1.html
If you still need other threads, make sure that
they don't contain any Swing/AWT components,
but just update any status.Can you pass a Swing Component reference to the thread's constructor and call repaint() from inside the thread?

Similar Messages

  • Can I execute C code in current Thread(process)?

    Hi all,
    I want to execute a Linux command within current Thread, but Runtime.exec() will start a new process to execute the command specified.
    Does JNI can execute any system command or any C program in current Thread?
    BTW, I tried JNA, following code will start new process too:
    public interface CLibrary extends Library {
    CLibrary INSTANCE = (CLibrary)Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"),CLibrary.class);
    void printf(String format, Object... args);
    void system(String cmd);
    public static void main(String[] args) {
         CLibrary.INSTANCE.system("sleep 5s");
    Can I execute the Linux command within current Thread with JNA?
    Any anwser will be appreciated!! Thanks!!
    Raymond Zeng
    Edited by: raymond.zeng on Dec 2, 2009 8:19 AM

    Hi sabre150,
    Thank you very much!
    In fact, the reason I want native code run in current process is that native code will lock some system resource(such as COM port), I want to manipulate that resource in Java code after calling native code. (native code may run in a new thread for a long time, in the same time, Java code may need to manipulate the resource in other thread)
    It is not import about whether start a new thread or not, but I really want the native code will be executed in a same process, so OS will not prevent me to manipulate that resource.
    Is there any smart solution to do this?
    Thanks!
    Raymond Zeng

  • Can use the same thread safe variable in the different processes?

    Hello,
    Can  use the same thread safe variable in the different processes?  my application has a log file used to record some event, the log file will be accessed by the different process, is there any synchronous method to access the log file with CVI ?
    David

    Limiting concurrent access to shared resources can be better obtained by using locks: once created, the lock can be get by one requester at a time by calling CmtGetLock, the other being blocked in the same call until the lock is free. If you do not want to lock a process you can use CmtTryToGtLock instead.
    Don't forget to discard locks when you have finished using them or at program end.
    Alternatively you can PostDeferredCall a unique function (executed in the main thread) to write the log passing the apprpriate data to it.
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

  • How can I close core thread in ThreadPoolExecutor?

    If I use unbounded LinkedBlockingQueue in ThreadPoolExecutor and set the core pool size to 5. When more than 5 tasks are submitted, there will be 5 threads created to handle the request. After finish, these threads will not be closed. How can I make the threads in core pool be closed when finishing their job? I couldn't use maximum pool for that I do need an unbounded queue.

    If you really want that functionality, set the core pool size to 0, the maximum pool size to 5 or greater, and the keepAliveTime to 0L. This will remove excess threads as soon as their tasks have completed.
    It's very wasteful though if you plan on executing the tasks repeatedly to create new threads everytime you submit a task. One of the benefits of using a thread executor is not having to construct and start a Thread object everytime you run a task.
    Brushfire,

  • Always get "Can't detect initial thread location" when using compiler

    Hi,
    I'm a newbie in installing java into my computer and i couldn't find any thread in this forum that discuss regarding to this matter...
    Well basically, all binary extraction was going fine and j2sdk1.4.2_04 folder was created successfully without error message at all...
    The problem is, i get this message everytime i execute java compiler...
    Java HotSpot(TM) Client VM warning: Can't detect initial thread stack location
    java version "1.4.2_04"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_04-b05)
    Java HotSpot(TM) Client VM (build 1.4.2_04-b05, mixed mode)
    I'm using FreeBSD 5.2.1. and running linux compatibility port... so the java sdk was extracted successfully without any modification or whatsoever...
    I appreciate if someone can help me with this...

    I had the same problem and found this thread that fixed it....
    http://www.mail-archive.com/[email protected]/msg60015.html

  • Error message encore cs5 end action can't execute on the final chapter point

    Dvd plays great. Exported it as a mpeg 2-dvd,  video only. Audio separate as a .wav. imported video as a timeline, audio as an asset. Video is not transcoded.
    But I have a sub menu, with 6 chapter markers. I check the project and I get this: "error message encore cs5 end action can't execute on the final chapter point"
    Do I need to make a chapter playlist? Because that gave me a "orphaned playlist" error message.
    I selected the last chapter masker and had the end action go to the sub menu.
    Thanks!

    Saw a previous thread where bill hunt said it ignore it and try to burn a copy.

  • Is ThreadPoolExecutor.execute(Runnable) thread-safe?

    Is ThreadPoolExecutor.execute(Runnable) thread-safe, i.e. is it safe
    to invoke this method from multiple threads without making any
    special arrangements to ensure that not more than one thread is
    in the execute() method of the ThreadPoolExecutor object at the same time
    (such as synchronizing on the ThreadPoolExecutor object)?
    I can find nothing in the Java 6 documentation to say it is thread-safe
    (Executor, ExecutorService, ThreadPoolExecutor and package documentation).
    Note that I am not asking anything about the actual execution of the Runnables.
    I am asking about the act of inserting the Runnables into the thread pool.

    Thanks to everyone who replied.
    The three example implementations in the interface documentation for Executor, including the one where the Runnable is executed by the invoking thread, are thread-safe but only the last one needs to do anything special (namely make the execute(...) method synchronized) to be thread-safe. It is not clear whether the thread-safety of the first two implementations is conscious or accidental. Even if conscious that would not imply that it is necessary.
    I think the published documentation (unless I've missed something) is deficient. The method would not be useless if not thread-safe. I don't think thread-safety is a safe default assumption. I think a package that supports concurrent programming should be clear on where it is thread-safe.
    I've had a quick look at the source code in the 1.6 JDK implementation. It makes a serious and plausible effort to be thread-safe. It was written by Doug Lea.
    I'm going to assume the method is thread-safe, based on looking at the source code.

  • How Can I stop my thread?

    Hi!
    I'm developing an application of computacional geometry. It consist on a JFrame where I put some components like a JToolBar, a JTextArea, etc, and a JPanel. When the JPanel it's painted, there are a button that runs the JPanel in a new Thread.
    The problem is that I have another button to stop the thread, but I can't stop it completely if it is in a I/O operation.
    Here is the code of the run() method:
    public void run()
    Thread thisThread = Thread.currentThread();
    while (kicker == thisThread)
    if (runMode)
    lhull.removeAllElements();
         hull.removeAllElements();
    GrahamScan();
    runMode = false;
    aFrame.doneButton.setEnabled(true);
    stop();
    I stop the thread, but when it's in the GrahamScan() method, it continues painting things in the panel.
    How can I stop the thread completely?
    Thanxs in advance!!

    What's the matter with my line separators and my code indentation?
    Try to use yourThread.interrupt() at your button push event, and this code;
    public void run()
    Thread thisThread = Thread.currentThread();
    try {
    while (kicker == thisThread)
    if (runMode)
    lhull.removeAllElements();
    hull.removeAllElements();
    GrahamScan();
    runMode = false;
    aFrame.doneButton.setEnabled(true);
    stop();
    } catch (InterruptedException iEx){

  • Jdeveloper threads?? how can I start a thread?

    Does anyone know how I can automatically set a thread in motion once I call a file in the project? I basically want a background process to run constantly while my app runs.
    Any thoughts??

    Try this:
    http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html
    http://developer.java.sun.com/developer/Books/threads/chap9.pdf
    Linda
    null

  • How can I execute a Procedure with OUT variable is %ROWTYPE on SQL Prompt

    Hi,
    I have a procedure with OUT variable is %ROWTYPE
    How can I execute the following procedure on SQL prompt.
    (without creating anonymous block)
    CREATE OR REPLACE PROCEDURE zz_sp_EMP(VEMPNO IN EMP.EMPNO%TYPE,
    V_REC IN OUT EMP%ROWTYPE)
    AS
    BEGIN
    SELECT * INTO V_REC FROM EMP WHERE EMPNO = VEMPNO;
    END;
    Thanks & Regards,
    Naresh

    as previous posters said: it's not possible to do this without declaring a variable in the anonymous block.
    With anonymous block it would look like this (had to change it a bit, since i'm using hr-schema on oracle XE):
    declare
    l_rec EMPLOYEES%ROWTYPE;
    begin
    zz_sp_EMP(VEMPNO => 100, V_REC => l_rec);
    DBMS_OUTPUT.PUT_LINE ( 'first_name = ' || l_rec.first_name );
    DBMS_OUTPUT.PUT_LINE ( 'last_name = ' || l_rec.last_name );
    end;
    first_name = Steven
    last_name = King

  • How can i execute vb scripts in java program

    hi
    how can i execute any batch files or any other exe files (vb scripts) from java programs
    thanks

    Hi,
    You use Runtime.exec to execute commands / exe-files. See the documentation (and remember that it will only work on windows):
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html
    /Kaj

  • How can I execute Stored Procedures in PARALLEL and DYNAMICALLY ?

    Hi 
    I have a stored procedure. It can be executed like this
    exec test @p = 1;
    exec test @p = 2
    exec test @p = n;
    n can be hundred.
    I want the sp being executed in parallel, not sequence. It means the 3 examples above can be run at the same time.
    If I know the number in advance, say 3, I can create 3 different Execution SQL Tasks. They can be run in parallel.
    However, the n is not static. It is coming from a table. 
    How can I execute Stored Procedures in PARALLEL and DYNAMICALLY ?
    I think about using script task. In the script, I get the value of n, and the list of p, from the table, then running a loop with. In the loop, I create a threat and in the threat, I execute the sp like : exec test @p = p. So the exec test may
    be run parallel. But I am not sure if it works.
    Any idea is really appreciated.

    Hi nam_man,
    According to your description, you want to call stored procedures in parallel, right?
    In SSIS, we can create separate jobs with different stored procedures, then set the same schedule to kick the jobs off at the same time. In this way, we should be careful to monitor blocking and deadlocking depending on what the jobs are doing.
    We can also put all stored procedures in SSIS Sequence container, then they will be run in parallel.
    For more information about SSIS job and Sequence container, please refer to the following documents:
    http://www.mssqltips.com/sqlservertutorial/220/scheduling-ssis-packages-with-sql-server-agent/
    https://msdn.microsoft.com/en-us/library/ms139855(v=sql.110).aspx
    If you have any more questions, please feel free to ask.
    Thanks,
    Wendy Fu
    Wendy Fu
    TechNet Community Support

  • How can I execute program after using F4_Filename function?

    Hi all,
    I'm a new user on the forum. I've been working with ABAP and SAP for a few weeks. I wrote a program for importing data from excel file to SAP using BDC. During searching this forum I found information about F4_Filename function which allows users to browse the disc for a file. I'd like to add this function to my program. I have a parameter for a file name but this is an ordinary static string field. When I added the code which I found in the message on this forum the rest of program doesn't execute.
    This is simple program for example:
    REPORT  Z_TEST8_AB.
    DATA f_name TYPE STRING.
    PARAMETERS p_file like rlgrap-filename DEFAULT 'c:\test.xls'.
    f_name = p_file.
    write:/ f_name.
    This program works correctly. There is a field for parameter. I can change the default name for a file.
    After all, I can run the program (F8) and rest of the code is executed. The field for parameter dissapears from the screen and the file name is displayed. ( command write)
    Now I added a function F4_Filename
    REPORT  Z_TEST8_AB.
    DATA f_name TYPE STRING.
    PARAMETERS p_file like rlgrap-filename DEFAULT 'c:\test.xls'.
    at selection-screen on value-request for p_file.
      call function 'F4_FILENAME'
           exporting
                program_name  = syst-repid
                dynpro_number = syst-dynnr
                field_name    = 'p_file'
           importing
                file_name     = p_file.
    f_name = p_file.
    write:/ f_name.
    I can browse a computer for a file now but after selecting the file I can't run the rest of the code. When I click on the icon or press key F8 the field for parameter doesn't dissapier and the command write is not executed.
    What do I do wrong?
    Could anyone suggest me a solution? How can I executed the code after using this function?
    Thanks in advance.
    Regards,
    Arek.

    Hi arkadiusz,
    1. simple
    2.
    <b>start-of-selection.</b>
    f_name = p_file.
    write:/ f_name.
    regards,
    amit m.

  • How can I execute external application?

    Hi friends I want printing my barcodes a laser printer (Kyocera) it isn't a barcode printer. So I think (and I look kyocera web page my model doesn't support barcode printing in sap) print my barcodes using an external system. Before SAP we are using JollyPrint application for printing barcodes. It is using an Excel file.
    I can create a excel file for this application. I must execute this (JollyPrint-it is a label application) application when I press a button. How can I execute this application?
    Thanks
    Mehmet
    P.S. I have been writing this message with details may be somebody can give me a simple way for this

    Well, I can suggest you following steps. May be it works for you .
    -Create an external OS command in SM69
    -Test OS command in SM49 ( <u><i>about OS command if you search in SDN you’ll get lot of material</i></u> )
    -Create a Script at your OS level, I’m assuming you might have some UNIX flavor or Sun solaria’s.
    -Create a Shell script , which execute the printer job from OS .
    -Shell script will have parameters . ( e.g. printer name, destination etc )
    -set the path of shell script directory in SM69 ( the command you just created )
    -Execute shell script using your ABAP program ( use FM "SXPG_COMMAND_EXECUTE" )
    In the ABAP  program you can pass the parameters and execute the command from ABAP as a result your job will start printing on the required destination. Moreover, you can also capture the spool at OS level .
    FYI
    For UNIX script, if you search in www.google.com ( UNIX forums) . you’ll get shell script .
    Hope this’ll give you idea!!
    <b>P.S award the points.</b>
    Good luck
    Thanks
    Saquib Khan
    "Some are wise and some are otherwise"

  • How can I execute an .app remotely in a server via internet?

    Hi,
    Using PHP, or something like it,  how can I execute a MAC OSX app but have it run remotely in the server?
    I know this may sound like a simple question but I have almost no experience with Web apps.
    Thanks,
    Juan Dent

    All you need is a trigger that starts the execution. A simple HTML link to the file will do.

Maybe you are looking for

  • VOICE MEMOS R GONE HELPPP

    Hi, i recently restarted my ipod by mistake and everything got deleted however i had alreaedy saved all the pics before this. problem is that all my voice memos r gone and i never made a backup file earlier. what do i do???????????i need 2 recover th

  • Getting other people's messages on iMessage after losing my #? Help!

    I used to have phone service through T-Mobile but I ran out of money to pay for bills, and T-Mobile canceled my account eventually. Someone else in the area got an account with them and now they have my number. However, all my friends who had me in t

  • Iphoto library from old to new mac

    I just upgraded to Macbook pro retina display. I have all my photos in iphoto on my older macbook. I use faces on every photo and instead of just copying the photos, I want to make sure I do not lose anything (like faces desigantions). How can I do t

  • I just purchased a copy of Adobe Photoshop Elements 8 and the computer disc drive will not read it

    I just pruchased a copy of Adobe Photoshop Elements 8 and the disc drive will not read the disc. What to do?

  • How to replace all existed objects when impdp a schame ???

    I wrote 2 functions which do expdp and impdp the impdp funciton is : create or replace function impdp_schema(fromusr in varchar2,                                         tousr   in varchar2,                                         dir     in varchar2