Panel implements Runnable?

Is it possible to implement Runnable in a Frame panel?
I have an Applet Frame for drawing polylines and I want to add a scrolling text panel at the bottom of the frame.
I have a horizontal text applet already, however, when I try to add it's functionality to the frame's panel I get a nullpointerexception error.
Can anybody help,
thanks Aidan

This is the original applet that I used for scrolling text.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class TextPanel extends Applet implements Runnable
private Thread textthread;
boolean FirstPass;
private String Text;
private int S;
private Color bgC;
private Color textC;
private Color tempC;     
private int xPos;
private int yPos;
private int textWidth;
private int aWide;
private int aHigh;
private String fontName;
private Font F;
private Image iBuff;
private Graphics gBuff;
private Image iTheText;
private Graphics gTheText;
private boolean LoadPause;
private int RP;
private int VB;
public TextPanel()
textthread= null;
FirstPass = true;
Text = " Scrolling Text. ";          
S = 40;
xPos = 1;
yPos = 0;
textWidth = 0;
aWide = 0;
aHigh = 0;
bgC = new Color(255, 255, 255);          
textC = new Color(0, 0, 0);
tempC = textC;               
fontName = "TimesRoman";
LoadPause = true;
RP = 1000;
VB = 0;
iBuff = null;
gBuff = null;
public void init()
aWide = 600;
aHigh = 16;
prepMessage();
makeText();
if (iBuff == null)
iBuff = createImage(aWide, aHigh);
gBuff = iBuff.getGraphics();
public void prepMessage()
FontMetrics fontmetrics = null;
F = new Font(fontName, Font.PLAIN, 16);
fontmetrics = getFontMetrics(F);
textWidth = fontmetrics.stringWidth(Text);
int j = fontmetrics.getAscent();
yPos = aHigh - fontmetrics.getMaxDescent() - fontmetrics.getMaxDescent() / 3;
yPos = yPos + VB;
public void makeText()
iTheText = createImage(textWidth, aHigh);
gTheText = iTheText.getGraphics();
gTheText.setColor(bgC);          
gTheText.fillRect(0, 0, textWidth, aHigh);
gTheText.setColor(tempC);          
gTheText.setFont(F);
if(!FirstPass)
gTheText.drawString(Text, 0, yPos);
public void update(Graphics g)
paint(g);
public void paint(Graphics g)
if(++xPos > textWidth)
xPos = 1;
int i = xPos * -1;
do
if(!FirstPass)
gBuff.drawImage(iTheText, i, 0, this);
if(FirstPass)
gBuff.drawImage(iTheText, 0, 0, this);
i = 0;
i += textWidth;
} while(i < aWide);
g.drawImage(iBuff, 0, 0, this);
public void start()
if(textthread== null)
textthread= new Thread(this);
textthread.start();
public void stop()
if(textthread!= null)
textthread= null;
public void run()
if(FirstPass)
FirstPass = false;
     makeText();
     if (!FirstPass)
     do
try
repaint();
if(LoadPause)
try
TextPanel _tmp = this;
Thread.sleep(RP);
catch(InterruptedException interruptedexception) { }
LoadPause = false;
TextPanel _tmp1 = this;
Thread.sleep(S);
catch(InterruptedException interruptedexception1)
stop();
     }while(true);
     else
     return;
I was hoping to have a class
Where the applet created a frame with e.g. a canvas panel and a textscrolling panel i.e. by changing the init() method to include the following.
public void init()
Frame frame = new Frame("Text scroller");
frame.setSize(600, 100);
Panel panel = new Panel();
panel.setSize(aWide, aHigh);
TextPanel textpanel = new TextPanel();
panel.add(textpanel);
frame.add(panel);
textpanel.start();
frame.setVisible(true);
The text scroller runs in the html page and the frame is empty. is it possible to add the scrolling text to the frame.

Similar Messages

  • Threads: implement runnable or extend Thread.  Which is better?

    I want to know which way is better, as I want to do some work in threads.
    Thanks,
    Virum

    I want to know which way is better, as I want to do
    some work in threads.
    Thanks,
    VirumOne reason for implementing runnable can be that java doesnot allow multiple inheritance so by implementing runnable you can, at the same time, extend another class.
    Another reason though not recommended and not good programming practice is that although you cannot restart a dead thread, if you use runnables, you can submit the old runnable instance to a new thread, thus practically starting a thread more than once.

  • Qestion for implementing Runnable

    HI,
    I have a function which executes multiple methods and store the result from those methods in List<Stirng> before the last methods executes I need to insert these List<String> values in a database with my dao object.
    I was wondering if I do the following:
    new Thread(new myInsertWorker()).start();
    executeMyFunction();
    Would I improve the performance on my program since it is very important for this last function to be fast.
    My question is if I insert the strings as a separate thread how do I need to write the thread to be as simple as possible and not cause any performance issues?

    Here is my code, I am new to concurrent programming, therefore I move slowly :) and check my code with someone else to prevent issues I am not aware of.
    Can I improve this simple piece of code to make sure if it does fail or hangs my application will not be affected?
    Thank you
    public class LogMessageWorker implements Runnable {
        List<LogMessage>_messages = new LinkedList();
        LogMessageDAO _logMessageDAO=null;
        public LogMessageWorker(LogMessageDAO logMessageDAO, List<LogMessage> messages){
            this._messages = messages;
            this._logMessageDAO = logMessageDAO;
        public LogMessageWorker(LogMessageDAO logMessageDAO, LogMessage message){
            this._messages.add(message);
            this._logMessageDAO = logMessageDAO;
        public void run() {
            try{
                _logMessageDAO.add(_messages);
            }catch(Exception e){
                e.printStackTrace();
    }This is how I call it:
    try {
                Thread logMsgThread = new Thread(new LogMessageWorker(logMessageDAO, logMessages));
                //logMsgThread.setPriority(Thread.MIN_PRIORITY);
                logMsgThread.start();
            } catch (Exception e) {
                e.printStackTrace();
            }Edited by: kminev on Dec 3, 2009 2:06 PM

  • Question about methods in a class that implements Runnable

    I have a class that contains methods that are called by other classes. I wanted it to run in its own thread (to free up the SWT GUI thread because it appeared to be blocking the GUI thread). So, I had it implement Runnable, made a run method that just waits for the thread to be stopped:
    while (StopTheThread == false)
    try
    Thread.sleep(10);
    catch (InterruptedException e)
    //System.out.println("here");
    (the thread is started in the class constructor)
    I assumed that the other methods in this class would be running in the thread and would thus not block when called, but it appears the SWT GUI thread is still blocked. Is my assumption wrong?

    powerdroid wrote:
    Oh, excellent. Thank you for this explanation. So, if the run method calls any other method in the class, those are run in the new thread, but any time a method is called from another class, it runs on the calling class' thread. Correct?Yes.
    This will work fine, in that I can have the run method do all the necessary calling of the other methods, but how can I get return values back to the original (to know the results of the process run in the new thread)?Easy: use higher-level classes than thread. Specifically those found in java.util.concurrent:
    public class MyCallable implements Callable<Foo> {
      public Foo call() {
        return SomeClass.doExpensiveCalculation();
    ExecutorService executor = Executors.newFixedThreadPool();
    Future<Foo> future = executor.submit(new MyCallable());
    // do some other stuff
    Foo result = future.get(); // get will wait until MyCallable is finished or return the value immediately when it is already done.

  • Implementing Runnable interface  Vs  extending Thread class

    hi,
    i've come to know by some people says that Implementing Runnbale interface while creating a thread is better option rather than extending a Thread class. HOw and Why? Can anybody explain.?

    Its the same amount of programming work...
    Sometimes it is not possible to extend Thread, becuase your threaded class might have to extend something else.
    The only difference between implementing Runnable and extending Thread is that by extending Thread, each of your threads has a unique object associated with it, whereas with Runnable, many threads share the same object instance.
    http://developerlife.com/lessons/threadsintro/default.htm#Implementing

  • Reflect the class that implements Runnable

    Hi,
    I am implementing the reflection of the class that implements Runnable. In order to start a new thread I am trying to invoke "start()" method ( which is obviously not defined my class ) and I therefore I am getting "java.lang.NoSuchMethodException".
    I am wondering is it possible at all to start a new thread on a reflected class?
    thanks in advance.
    {              Class refClass = Class.forName(className);
    String methodName = "start";
    Class[] types = new Class[1];
    types[0] = Class.forName("java.util.HashMap");
    Constructor cons = refClass.getConstructor(types);
    Object[] params = new Object[5];
    params[0] = new HashMap();
    Method libMethod = refClass.getMethod(methodName, null);
    libMethod.invoke(objType, null); }

    Well, if we knew what it meant to "start a thread on a class" we could probably figure out how to "start a thread on a reflected class". If we knew what a "reflected class" was, that is.
    In other words, it would help if you rephrased your question using standard terminology (and also explained why you want to do whatever it is you want to do).
    But let's guess for now: If you have an object which implements Runnable then you start a thread to run that object like this:
    Runnable r = // some object which implements Runnable
    new Thread(r).start();Not what you wanted? Go ahead and clarify then.

  • How can I know a class which implements Runnable interface has terminated?

    Hello! I have a class which has implements Runnable interface, while I want to execute some operation when the thread has terminate in multithread enviroment.How can I know the thread has terminated?Does it give out some signal?Cant I just call my operation at the end of the run() method?

    I want to execute some operation when
    the thread has terminate in multithread enviroment....
    Cant I just call my operation at the end
    of the run() method?Sure. Before run() ends, invoke that other operation.
    How
    can I know the thread has terminated?Does it give out
    some signal?Not that I'm aware of, but you can do what you described above, or I believe a different object can call isAlive on the thread.

  • Access denied when I implement Runnable?

    Wow.. I've been trying to isolate this problem for ages. I just got down to it by first making an applet that displays a static image, which works fine, and then using a run() method to animate it with just one more frame. When I use the run method it churns out a lot of rubbish in the DOS window, which ends
    at sun.applet.AppletPanel.run(AppletPanel.java:293)
    at java.lang.Thread.run(Thread.java:484)
    I don't know what's going on here... Is there a problem with my JDK, because I've installed it twice already? It compiles fine, with just one mention that I've overridden a method, namely paint, which is empty anyway. Help!

    Without the code and the exact exception, I can't be entirely sure of the problem, however I can guess. If you are implementing Runnable, you should not be calling your run method directly. You mentioned that this is an applet, so you should write your start method as:
    public void start(){
      (new Thread( this ) ).start();
    }Which will create and start a new thread whose run method (the code it will be executing) is what you have written in your run method.

  • Implements Runnable vs extends Thread

    Hello,
    Why do we call method run() in a Runnable class a thread? (at least my textbook implies such concept)
    If thread is an independent process, which runs on its own - then it's not about Runnable.run().
    public class RunnableThread implements Runnable
        public void run()
            for (int i=0; i<100000; i++)
                if (i%50000 == 0)
                System.out.print(i+" ");
        public static void main (String args[])
            System.out.println("Before thread");
            new RunnableThread().run();
            System.out.println("Thread started");// this line is executed only after
            // run() returns, not like with "true" threads, where execution course          
            //doesn't wait for start() to return
    }Or should I consider run() a regular (non-thread) method needed only to bypass extends restrictions?

    Why do we call method run() in a Runnable class a
    thread? We don't.
    (at least my textbook implies such concept)Perhaps you could post what your textbook says, and we can decipher it for you.
    If thread is an independent process, which runs
    on its own - then it's not about Runnable.run().Don't know what you mean by it being "about" Runnable.run()?
    Runnable.run is the method that gets executed when a thread is started.
    Or should I consider run() a regular (non-thread)
    method needed run() is a regular method. It happens to be one that is declared in the Runnable interface and is called by an executing thread. In your example code, you use just call run as you would any other method, so it acts just like any other method. To run it in a separate thread, you should call start() on the thread, not run(). The Thread object will then enter the waiting state and will call run() itself at the appropriate time.

  • Implement Runnable

    I think the often given advice of implement Runnable rather than extend Thread (unless it is some kind of Thread!) is good advice, but sort of incomplete.
    Alice wrote:
    class A {...}Bob writes:
    class B extends A {...}Alice improves class A:
    class A implements Runnable
      // Do the A-something in another thread
      new Thread( this ).start();
      public void run() {...}
    }Everything is fine, the contract of class A did not change (or did it?).
    Bob improves class B:
    class B implements Runnable
      // Do the B-something in another thread
      new Thread( this ).start();
      public void run() {...}
    }Now the A-something is not done anymore and the B-something is done twice!
    I think the complete advice should be to prefer inner classes that implement Runnable.
    class A
      // Do the A-something in another thread
      new Thread( new Runnable {
         public void run()
             doTheASomething();
      } ).start();
      private void doTheASomething() {...}
    }Any thoughts?

    More I think about it, the problem is more general.
    Implementing yet another interface in a class should
    d not be taken lightly and I must confess, I used to
    take it lightly. Adding new public methods, who
    should care? Seems that when we implement an
    interface we do more than just add a few public
    methods. The contract does change!Yes and no, IMO.
    If a given method synchronously would return a value, then obviously the asynchronous version cannot. (You could have a callback or some other notification mechanism to get the value formerly returned). So in a formal sense, there is now an additional contract, should a given class choose to realize that interface. However, the original synchronous contract presumably remains unchanged.
    Further, if you implement a given interface, you must honor its contract. The contract itself does not change. You simply realize an implementation of it.
    - Saish

  • Performance wise which is best extends Thread Class or implement Runnable

    Hi,
    Which one is best performance wise extends Thread Class or implement Runnable interface ?
    Which are the major difference between them and which one is best in which case.

    Which one is best performance wise extends Thread Class or implement Runnable interface ?Which kind of performance? Do you worry about thread creation time, or about execution time?
    If the latter, then don't : there is no effect on the code being executed.
    If the former (thread creation), then browse the API Javadoc about Executor and ExecutorService , and the other execution-related classes in the same package, to know about the usage of the various threading/execution models.
    If you worry about, more generally, throughput (which would be a better concern), then it is not impacted by whether you have implemented your code in a Runnable implementation class, or a Thread subclass.
    Which are the major difference between them and which one is best in which case.Runnable is almost always better design-wise :
    - it will eventually be executed in a thread, but it leaves you the flexibility to choose which thread (the current one, another thread, another from a pool,...). In particular you should read about Executor and ExecutorService as mentioned above. In particular, if you happen to actually have a performance problem, you can change the thread creation code with little impact on the code being executed in the threads.
    - it is an interface, and leaves you free to extend another class. Especially useful for the Command pattern.
    Edited by: jduprez on May 16, 2011 2:08 PM

  • Naming a thread that is created implementing Runnable

    How could I name a thread that I create using Runnable Interface?
    public class Test {
         * @param args the command line arguments
        public static void main(String[] args) {
            TestRunnable tr = new TestRunnable();
            /* running thread */
            new Thread(tr).start();//THREAD 3
    public class TestRunnable implements Runnable {
        public void run() {
            for(int y = 1; y < 1000; y++) {
                System.out.println("3333333333333333333333333333333333333333 " + Thread.currentThread() );
    }

    well, I'm just experimenting; learning about Threads. As you can see I
    was able to name the other two threads, I was just curious how you would do it,
    using the Runnable Interface, seeing as those two naming options I used don't
    seem to be an option for it. I may be misunderstanding your reply...
        public static void main(String[] args) {//thread 0
            FrameThread ft = new FrameThread();//extends Thread
            ft.setName("ft");
            Thread td = new Thread("td") {
                @Override
                public void run() {
                    for(int a = 1; a < 1000; a++) {
                        System.out.println("1111111111111111111111111111111111111111 " + Thread.currentThread() );
            TestRunnable tr = new TestRunnable();//class implements Runnable
            /* running threads */
            td.start();//THREAD 1
            ft.start();//THREAD 2
            new Thread(tr).start();//THREAD 3
    }I'm naming them so when I use : Thread.currentThread() the return slot has the name I provide.
    Edited by: rico16135 on May 3, 2008 3:14 PM
    Edited by: rico16135 on May 3, 2008 3:17 PM

  • ...implements Runnable

    Hi!
    I have a frame implementing the Runnable interface in my app to be able
    to show some images in a loop in the run() method and I'd like to know
    if it's considered good MVC practice to do this.
    Thanks

    No. Your thread should be in a seperate object. Even an inner class would be better than implementing Runnable off of your Frame itself.

  • Extending Applet implements Runnable    --explain

    kindly give an explanation of the need to use the
    <extends Applet implements Runnable > code
    while creating an applet program is there a need to use both Applets and Runnable
    wht are the methods available in Applet class
    and Runnable interface

    The most common use of the Runnable interface is for threading.
    An applet doesn't need to implement Runnable to be run as an Applet, but an applet often needs to be doing things in the background, not just when specific user events like init, start, mouse events etc. come in. For example the applet might run some kind of animation.
    An applet should return promptly from events of the above sort, allowing the browser to get on with it's own business. If it is to do something itself one of these events needs to start a thread.
    Declaring the Applet runnable allows you to do something like:
    new Thread(this).start();for example in the init method. This starts a new thread of execution which runs the run method of the applet, which will do the background activity.
    You don't have to do it this way, you can create another Runnable object whose run method will be executed by the thread. Often you use anonymous classes for this e.g.
    new Thread(new Runnable() {
       public void run() {
              doBackgroudStuff();
        }).start();

  • HttpServlet implements Runnable thread issue

    Hi,
    I have a servlet that implements Runnable. In web.xml I have set this servlet to load-on-start=1. In the init method of the servlet I have a thread that starts and basically runs forever. Now I am facing some issues and am not able to figure out what exactly is going on. I see exceptions in the log file and then my servlet stops. I have catch block all over but somehow whenever some exception occurs my Thread just stops and the servlet stops too I have to manually invoke the servlet so the Thread to start over again. Here is a code snippet. Now if any error occurs in insert() method somehow Thread just stops even though I am catching an exception. This servlet is not called from anywhere it just loads as soon as the app is deployed and then the thread keeps running and in my insert method I am reading some files and inserting into the database. How can stop the thread from being stopping and where at the top level I can add catch block to exactly print the error even though I am catching all the exceptions in the code itself. How can I keep my thread alive even after any exceptions.
    public class InsertData extends HttpServlet implements Runnable {
        Thread thread;
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
            thread = new Thread(this);
            thread.setPriority(Thread.MIN_PRIORITY);
            thread.start();
        public void run() {      
            while (true) {                     
               insert();
               try {
                thread.sleep(10000);
              catch (InterruptedException ignored) { ; }
        private insert()
         try{
         catch(Exception exception)
        }Thanks

    Hi,
    After more debugging it turned out all the exceptions are handled correctly but some how after some time the thread just stops running in the servlet and even after invoking the servlet manually it doesn't start. Now asThread may take arround couple of minutes to finish but I am starting a new run every 1 minute which may lead to several Threads running a one particular time and as the time goes on thread increase also. So wondering if there's any limit on number of Threads to run at one particular time or is the Application Server removing any of these as in the code I don't see anything and no errors in the logs either.
    Is there a way to find out if a servlet is loaded. As in the Application Server control I do see a servlet loaded but I don't see any of the Thread running that calls the insert method.
    Also is it a good idea to have a Thread start in the init method that runs forever. Any other approach I can take. Writing a windows service or a cron job can be one but it's not in the scope. Other option I though of was using JMS and thru MDB I manually invoke the servlet and so I don't have to use Threads.
    Is there any other approach I can have by using servlet itself. Basically I want to call my servlet every lets say 30 minutes automatically.
    Thanks

Maybe you are looking for

  • ORA-01489 Received Generating SQL for Report Region

    I am new to Apex and I am running into an issue with an report region I am puzzled by. Just a foreword, I'm sure this hack solution will get a good share of facepalms and chuckles from those with far more experience. I welcome suggestions and critici

  • Why isn`t the Apple Store Genius reservation system not working?

    Hello the apple store genius reservation system on Apple website is not working for Turkey.

  • HT1222 Lion Update 10.7.5   not working

    Something is not correct. I installed Snow Lion with all the updates before attempting to install Lion which installed to 10.7.4  with no problems when I got this gem. I than took my computer back stating something was wrong and they gave me another

  • Java.lang.NegativeArraySizeException

    Following the tutorial part 2 at http://developers.sun.com/techtopics/mobility/midp/articles/tutorial2/ i've run into this problem: I start the emulator, launch the application and click connect. I allow it to use air-time, and then this exception sh

  • What backend should be used?

    well i m developing a card game in java. i would like to know for saving the game settings like the cards and variables of the game what backend should i use. i want the application to be fully platform independent and also dont want to use any propr