Event dispatching to swing components

Hi,
I'm implementing an extension of JTextPane, and I would like to make it as much reusable as possible.
In order to do this, the class don't have to know about the external world (components)..
The class should notify events (e.g. an event could be that a specific string has been typed..) to the other components just sending a message (or event), and all the components registered to that specific event implement their behavior to react to it.. quite simple..
which is the simplest solution in Java to do this?
thanks in advance..

You should implement event dispatching based on the listener model, for consistency. Since you are extending JTextPane, a lot of the event dispatching code is written for you. Look up JTextPane in the javadocs and check out all the classes it is derived from. To take advantage of the already written listener code, simply call the appropriate fireWhateverEvent method whenever something happens. That will cause the event to be dispatched to all listeners registered with that component. If you want to define some new events that aren't covered by any of the listener methods in any of the classes your new class is derived from, here's the general way to do it:
1) Define a new listener interface that implements the EventListener interface (which contains no methods).
2) In your new listener interface, include methods for specific events, such as keyPressed, actionPerformed, textTyped, etc...
3) Each of these methods should take a single parameter describing the event. This parameter should be a class that extends EventObject and that contains data relevant to your event. For example, you may define a TextEvent class that extends EventObject. The only methods EventObject has is getSource() and toString(). You won't really need to override these as long as you call the EventObject(Object) constructor from your TextEvent constructors.
4) In your JTextPane derived class, define methods that can add, remove, and get a list of all registered event listeners for your event (ex: void addTextListener(TextListener t), void removeTextListener(TextListener t), TextListener[] getTextListeners()).
5) add*Listener should add the listener to an internal list of listeners (a LinkedList or a Vector are good ways to store the registered listener lists). remove*Listener should remove the listener from the list, and get*Listeners should return the list in array form.
6) For ease-of-use, define a fire method like fireTextListener(params), which creates a new TextEvent (assuming you're doing the TextListener thing) holding the specified event data and iterates through the internal list of listeners, calling the appropriate method in each one and passing your TextEvent to it.
7) Call your fire*Event functions wherever appropriate to fire events.
It's simpler than it sounds. Here's a small example:
// TextListener.java
public class TextListener implements EventListener {
    public void textInserted (TextEvent e);
    public void textDeleted  (TextEvent e);
// TextEvent.java
public class TextEvent extends EventObject {
    protected int    pos0;
    protected int    pos1;
    protected String text;
    public TextEvent (Object source, int pos0, int pos1, String text) {
        super(source);
        this.pos0 = pos0;
        this.pos1 = pos1;
        this.text = (text != null) ? text : "";
    public TextEvent (Object source, int pos0, int pos1) {
        this(source, pos0, pos1, null);
    public int getPos0 () {
        return pos0;
    public int getPos1 () {
        return pos1;
    public String getText () {
        return text;
// MyTextPane.java
public class MyTextPane extends JTextPane {
    LinkedList textListeners = new LinkedList();
    // This is just some method you defined, can be anything.
    public void someMethodThatInsertsText () {
        fireTextInserted(pos0, pos1, textInserted);
    // Same with this, this can be anything.
    public void someOtherMethodThatDeletesText () {
        fireTextDeleted(pos0, pos1);
    public void addTextListener (TextListener t) {
        textListeners.add(t);
    public void removeTextListener (TextListener t) {
        textListeners.remove(t);
    public TextListener[] getTextListeners () {
        TextListener ts = new TextListener[textListeners.size()];
        Iterator     i;
        int          j;
        // Don't think toArray works good because I'm 99% sure you'll
        // have trouble casting an Object[] to a TextListener[].
        for (j = 0, i = textListeners.iterator(); i.hasNext(); j ++)
            ts[j] = (TextListener)i.next();
    protected fireTextInserted (int pos0, int pos1, String text) {
        TextEvent e = new TextEvent(this, pos0, pos1, text);
        Iterator  i = textListeners.iterator();
        while (i.hasNext())
            ((TextListener)i.next()).textInserted(e);
    protected void fireTextDeleted (int pos0, int pos1) {
        TextEvent e = new TextEvent(this, pos0, pos1);
        Iterator  i = textListeners.iterator();
        while (i.hasNext())
            ((TextListener)i.next()).textDeleted(e);
};There. I just typed that there, didn't test or compile it, but you get the gist of it. Then, like you do with any listener stuff, when you want to set up a listener and register it with a MyTextPane instance, just create some class that extends TextListener and overrides textInserted and textDeleted to do whatever your application needs to do.
Hope that makes sense.
Jason

Similar Messages

  • Explicit Event Enabling for Swing Components

    Hi all swing-experts,
    I want to enable some events for an JInternalFrame explicitely,
    but I can't find the corresponding EVENT_MASK anywhere...
    Who knows??
    Anja

    Hello again,
    (besonderes HALLO an Stephen fuer die Muehe!!!)
    there exist two ways of handling an event, at least for awt events:
    1) writing an action listener and adding it to the component who will handle the event
    2) letting the component handle the event itself by "explicit event enabling"
    I am talking about no 2.
    This works so:
    a) Subclass component
    b) in the constructor of the subclass, call
    enableEvents(AWTEvent.XXX_EVENT_MASK)
    c) provide the subclass with a processXXXEvent() method (that should call the superclass' version of this method)
    An other version of my question: is this also possible with Swing?
    Where do I find the appropriate XXX_EVENT_MASK and processXXXEvent method?
    Seems to be an unusual problem...
    Anja
    PS: sieht so aus...

  • Determine event handler for swing components from the API browser

    Is there a way to determine what event handlers are assocaited with the different swing classes. For example JTextField is associated to ActionListener, and JCheckbox uses the event handle ItemListener. Is there a way to determine this by looking at the class via the Java API?

    Yes, there is. You'll observe that JTextField has an "addActionListener(ActionListener)" method, for a start. And JTextField is a subclass of JTextComponent, which has "addCaretListener(CaretListener)" and "addInputMethodListener(InputMethodListener)" methods. And JTextComponent is a subclass of JComponent, which has an "addAncestorListener(AncestorListener)" method. And so on... there are more. All of this can be found in the API documentation by looking for methods whose names start with "add".

  • Two Event Dispatch threads?

    I took a core dump of my swing app and it shows 2 threads in the following name (*AWT-EventQueue-0, AWT-EventQueue-1*). When does this happen? I know there could be only one Event dispatch thread. Please clarify! Tks
    name: AWT-EventQueue-1 id: 155 daemon: false alive: true priority: 6 state: WAITING thread group: java.lang.ThreadGroup[name=javawsSecurityThreadGroup,maxpri=10]
    stack trace:
    [java.lang.Object.wait(Native Method), java.lang.Object.wait(Object.java:485), java.awt.EventQueue.getNextEvent(Unknown Source), java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source), java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source), java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source), java.awt.EventDispatchThread.pumpEvents(Unknown Source), java.awt.EventDispatchThread.pumpEvents(Unknown Source), java.awt.EventDispatchThread.run(Unknown Source)]
    name: AWT-EventQueue-0 id: 29 daemon: false alive: true priority: 6 state: TIMED_WAITING thread group: java.lang.ThreadGroup[name=main,maxpri=10]
    stack trace:
    [java.lang.Object.wait(Native Method), com.lb.stomp.tiger.gui.Level2View.setClientMode(Level2View.java:87), com.lb.stomp.tiger.gui.Level2View.doClientModeRefresh(Level2View.java:302), com.lb.stomp.tiger.gui.Level2View.access$100(Level2View.java:44), com.lb.stomp.tiger.gui.Level2View$4.run(Level2View.java:291), java.awt.event.InvocationEvent.dispatch(Unknown Source), java.awt.EventQueue.dispatchEvent(Unknown Source), java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source), java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source), java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source), java.awt.EventDispatchThread.pumpEvents(Unknown Source), java.awt.EventDispatchThread.pumpEvents(Unknown Source), java.awt.EventDispatchThread.run(Unknown Source)]

    Please answer me direct if you have anything to add or please let someone else answer that knows about it.WARNING:
    You'll not like my reply...
    ok now I change my stance and saying my question is not related to what I am trying to investigate on my app. If this is irony towards tjacobs' reply, be prepared for a culture schock around here.
    Lot of (most?) problems submitted here end up being solved very differently than what the questions started as. Often a poster will ask a narrow question, be asked about the context and reason for asking it, disclose what his real problem is, be warned that the problem may be orthogonal to his question, and be advised to attack and solve it in a very different way.
    Posters of questions solved this way are generally grateful, although sometimes they may be deterred by what they feel is a dismissing or blurring of their original question.
    The "which secret are you hiding" is a recurrent whinning too, and is, how to say it nicely,... utterly unprofesional and childish (at best).
    Keep in mind that all people here are volunteers, and bear on their time to help other people out. It is a nonsense to groan that someone offering you a hand is secretly plotting against you gaining knowledge. If he really was, he wouldn't answer you in the first place.
    Just a curious question as to why would there be 2 AWT-EventQueue threads. This can happen with applets is what I read. This swing app was simply lauched from a command prompt.Now I like it better.
    I can't answer your question, and my curiosity is piqued as well.
    Although it's a reasonable assumption that there is only one event queue per application context, and one thread serving it, the docs go a long way saying that it's implementation-dependant. I found this paragraph in the docs (+<JDK_HOME>/docs/api/java/awt/doc-files/AWTThreadIssues.html+):
    The reason is that AWT encapsulates asynchronous event dispatch machinery to process events AWT or Swing components can fire. The exact behavior of this machinery is implementation-dependent. In particular, it can start non-daemon helper threads for its internal purposes. In fact, these are the threads that prevent the example above from exiting. The only restrictions imposed on the behavior of this machinery are as follows:
    * EventQueue.isDispatchThread returns true if and only if the calling thread is the event dispatch thread started by the machinery;
    * AWTEvents which were actually enqueued to a particular EventQueue (note that events being posted to the EventQueue can be coalesced) are dispatched:
    o Sequentially.
    That is, it is not permitted that several events from this queue are dispatched simultaneously.
    o In the same order as they are enqueued.
    That is, if AWTEvent A is enqueued to the EventQueue before AWTEvent B then event B will not be dispatched before event A.
    * There is at least one alive non-daemon thread while there is at least one displayable AWT or Swing component within the application (see Component.isDisplayable).
    So, since we agree that it's implementation-dependant, could you add here your system's specs (OS, JRE version)?

  • In swing for painting is separte thread from event-dispatching thread

    hi,
    event -dispatching thread is diffenent from paint thread in swing ???

    I don't believe so... or if it is, they have a special relationship tieing them together.
    why?

  • Catching events on Desktop , without using any AWT or Swing components.

    How can I catch events(for eg: mouse clicks) on the Desktop? I do not want to use any AWT or Swing components in my application.
    Also, i want to get events even some other java/non-java application windows are visible on desktop, as long as my application is running.

    Myrequirement is to capture all AWT events, regardless of on which component its being happened.
    I mean I have to capture events outside the current running application (on desktop and any other java/no-java appliation windows also).
    I couldn't find any other forum which discusses about event handling.
    This is part of my app. other end extensively uses awt.

  • Exception during event dispatching - Dont want to use Swing.invokeLater()

    I am getting NullpointerException while event dispatching. I am using threads, where each thread executes soem functions and one synchonized method to update graphics (table.updateUI())
    I am using thread.start to invoke the threads and not SwinUtilities.invokelater(). I know this is the problem because threads which update graphics should be invoked by invokelater, so that they are in queue in the awt event thread.
    But the method that updates gui is a synchonized method, so there should not be any collision. Also invokelater runs through all the threads and then invokes each, this reduces performance.
    Any help is very much appreciated.
    Thanks,
    JavaSeems.

    Hi Teka,
    Thanks for the response.
    Ok following is the exception i get :-
    Exception occurred during event dispatching:java.lang.NullPointerException     at sun.awt.RepaintArea.paint(RepaintArea.java:300)     at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:196)     at java.awt.Component.dispatchEventImpl(Component.java:2663)     at java.awt.Container.dispatchEventImpl(Container.java:1213)     at java.awt.Component.dispatchEvent(Component.java:2497)     at java.awt.EventQueue.dispatchEvent(EventQueue.java:339)     at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:131)
    I read soem thread stuff and soem forums, all say that whenever thread updates gui, dont invoke them using start method, use invokelater. But that degrades performance, also all threads dont run simulanouelsy.
    There will be a minimum of 6 threads in my program which will run for the lifetime of the dialog, so i need all of them to run simulatenoussly. But invokelater queues them in the awt evnt thread one after the other, and they dont run together.
    The thread will update gui by methods like tabelmodel.updateRow, Table.updategui. I see exceptions after these statements.
    Does this info help?

  • ..this method should be invoked from the event-dispatching thread?

    I see this (the title that is) in every single Java demo/example program on this (Sun's) site. However, I just tend to
    public static void main(String[] args){
       new whateverTheClassIsCalled();
    }And I've seen this approach on other sites and other example programs.
    So what exactly is better about this;
        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();
        }where createAndShowGUI() sets and packs the frame. I just do all this in the class constructor (when it's a JFrame!)
    So what does all this thread dispatching stuff mean, why should I use it etc etc.
    tia.

    Is it just me? For some reason it rubs me the wrong way that swing isn't thread safe. From what I've read, my understanding is that its safe to modify swing components from other threads as long as they haven't asked to be painted. If you don't do paint(), pack() or setVisible(true) until the end of your initialization, you will be safe.
    The reason for not being thread safe is almost certainly performance. Swing is slow enough as it is. Since the vast majority of Swing activity takes place in response to events and thus is on the EDT, there usually isn't a problem.
    This is a serious nuisance in network and database programs where multiple threads are used. I end up using invokeLater a lot in those cases, but never for initialization. Sun has only started to recomment that recently.
    Note that the fireXXX methods do not put the event on the EDT, these simply create Event objects and send them to Listeners. If they are executed off the EDT the Listeners will get called off the EDT.

  • How to synchronize two Event Dispatcher threads?

    I have two applications running in the same jvm. The flow should go like--
    a) First application (A1) has a swing window containing componets like buttons, text boxes etc.
    b) On click of this button, Event Dispatcher thread (T1) , calls the other application (A2).
    c) The second application A2, creates a swing window using EventQueue.invokeLater method and in the mean time Thread T1 should wait for this new A2 window to get some results from the database.
    Is it possible to stop thead T1 in between without freezing the GUI components of application A2.
    Thanks

    I think what tjacobs01 is getting at, is that there is only one Event Dispatcher Thread per JVM. So your question does not make sense. If there really is two EDT threads, then you are dealing with inter-process communication (since there would be two JVM processes, one for each application).
    It sounds like there is only one JVM, one EDT and two instances of a java.awt.Window. You probably think of the window == an application. In that case, you can probably solve your problem by executing the DB access (the long-running task) in the doInBackground() method of a SwingWorker.
    http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html

  • Event-dispatching create'n'showGUI useful for applets?

    I want to create and show the GUI in my applet's init method. Do I still need to wrap my code like this:
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    // create and show gui code
    (The applet is extends the JApplet class.)

    Yes. It is not guaranteed that it is the event dispatch thread that invokes init().
    http://java.sun.com/docs/books/tutorial/uiswing/components/applet.html#thread

  • Event dispatching in lightweight component

    Hi all
    I'm trying to figure out how the event dispatch works for the Swing's lightweight component, and there's something I can't find in the tutorials I found.
    Lightweight components doesn't have a peer, so they don't receive directly paint events, but it's their containers that call it inside their paint() method (and that's why one should always write super.paint() if wants to override the container's paint() ).
    But what about the other events? I suppose they are received by the container (just as paint events) but I can't understand how that container dispatches them to the right lightweight container...
    Thank you

    This is what I know about the painting in light weight component in Java.
    Lets us concentrate on the button only.
    Whenever we press the button we change it s state from 'normal' to 'pressed'. ( Some boolean might be used in the actual code ).
    Like wise whenever we do some user inputs to the button ( or any other lightweight component ) it results in the change in the state of the button.
    These basic actions are handled by BasicButtonListener.
    Now whenever the state of a component is changed it triggers a ChangeEvent associated with that perticular state change.
    The implementation of the button is such that it calls the repaint method itself whenever any state of the button changes.
    So it is the component itselt who calls its paint method and not its outermost container as you think.
    The container of any component can result in repainting of its child component only when it revalidates itself.

  • GetTreeLock during constructor for swing components

    I've noticed some dead locks in our application that are showing up in the call to getTreeLock that exists in the constructor for various JComponents. Specifically, the updateUI method winds up calling validateTree.
    I thought it was OK to construct JComponents from any thread, this suggests it is not.
    Has anyone else experienced this?

    It goes like this:
    On win32, thread 0 is our windows message pump. If dispatching one of our messages results in a call from C into Java that constructs a JComponent, we call getTreeLock from thread 0.
    Imagine that at the same time, the awt event disptatch thread is trying to show a frame. Since the awt event dispatch thread is part of our process, when the native implemention of the frame calls SendMessage to show the frame, the call to SendMessage blocks until thread 0 calls GetMessage.
    Since thread 0 is now blocking waiting for synchronized(getTreeLock()) to return and the awt event dispatch thread has the tree lock - fetched while executing the show() method - we are in a dead lock.
    This is not a problem with AWT components, only swing components.
    The stack looks like this:
         at java.awt.Component.getTreeLock(Component.java:811)
         at java.awt.Container.invalidateTree(Container.java:1116)
         at java.awt.Container.setFont(Container.java:1148)
         at javax.swing.JComponent.setFont(JComponent.java:2310)
         at javax.swing.LookAndFeel.installColorsAndFont(LookAndFeel.java:89)
         at javax.swing.plaf.basic.BasicButtonUI.installDefaults(BasicButtonUI.java:124)
         at com.sun.java.swing.plaf.windows.WindowsButtonUI.installDefaults(WindowsButtonUI.java:63)
         at javax.swing.plaf.basic.BasicButtonUI.installUI(BasicButtonUI.java:60)
         at javax.swing.JComponent.setUI(JComponent.java:449)
         at javax.swing.AbstractButton.setUI(AbstractButton.java:1616)
         at javax.swing.JButton.updateUI(JButton.java:119)
         at javax.swing.AbstractButton.init(AbstractButton.java:1952)
         at javax.swing.JButton.<init>(JButton.java:109)
         at javax.swing.JButton.<init>(JButton.java:64)
    It seems like we could simply have the invalidateTree method return early if there is no parent or there are no children or somesuch.
    A work around we've done is to have the updateUI method delegate to the event dispatch thread. This is a drag as we need to subclass all the JComponents and make sure developers use the safe subclass.

  • Not Running on the Event Dispatch thread, but UI still freezes

    The environment: I am currently working on an application that requires some heavy lifting in response to user input on a UI. To do this I am using a version of SwingWorker that was backported from java 1.6 to java 1.5 in conjunction with a slew of custom threads.
    The problem: I am currently running into an issue where I am not operating on the Event Dispatch thread (checked by doing a javax.swing.SwingUtilities.isEventDispatchThread()) but the UI is still freezing during this section. The operation involves a loop with about 2000 iterations and contains several file accesses. I have thought about how to make a new thread to perform the same operation, but I do not see how it would be any different since as it is I am not on the EDT. The call is being made from doInBackground and specifically the piece that is slowing things down is the File Accesses (2 for every iteration of the loop). At this point I am not sure how to go about resolving the issue. Any one have any suggestions?

    I am not operating on the Event Dispatch threadThat is the problem. Use multiple threads for GUI, which should delegates to the EDT, and your app logic.

  • Swing components in applet not working in web browser

    Hi Guys,
    I've created an applet which makes use of some swing components, but unfortunately, not all of them function properly in my web browser (internet explorer or Mozilla Firefox). Its mainly the buttons; the last buttons works and displays the correct file within the broswer, but the first 5 buttons do not work...
    any help please on how I can sort this problem out?
    Heres the code for my applet:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.applet.*;
    public class MainAppWindow extends JApplet
    int gapBetweenButtons = 5;
    final JPanel displayPanel = new JPanel(new BorderLayout());
    public void init()
       //Panel for overall display in applet window.
       JPanel mainPanel = new JPanel(new BorderLayout());
       mainPanel.add(new JLabel(new ImageIcon(getClass().getResource("images/smalllogo2.gif"))),BorderLayout.NORTH);
       //sub mainPanel which holds all mainPanels together.
       JPanel holdingPanel = new JPanel(new BorderLayout());
       //Panel for displaying all slide show and applications in.
       displayPanel.setBackground(Color.white);
       displayPanel.add(new JLabel(new ImageIcon(getClass().getResource("images/IntroPage.jpg"))),BorderLayout.CENTER);
       displayPanel.setPreferredSize(new Dimension(590,400));
       JPanel buttonPanel = new JPanel(new GridLayout(6,1,0,gapBetweenButtons));
       buttonPanel.setBackground(Color.white);
       JButton button1 = new JButton("User guide");
       button1.addActionListener(
         new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   if(displayPanel.getComponents().length > 0)displayPanel.removeAll(); // If there are any components in the mainPanel, remove them and then add label
                   displayPanel.setBackground(Color.white);
                   displayPanel.add(new JLabel(new ImageIcon("images/UserGuide.jpg")));
                   displayPanel.revalidate(); // Validates displayPanel to allow changes to occur onto it, allowing to add different number images/applicaions to it.
       JButton button2 = new JButton("What is a Stack?");
       button2.addActionListener(
       new ActionListener() {
               public void actionPerformed(ActionEvent e)
                   if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                   displayPanel.setBackground(Color.white);
                   displayPanel.add(new JLabel(new ImageIcon("images/WhatIsAStack.jpg")));
                   displayPanel.revalidate();
       JButton button3 = new JButton("STACK(ADT)");
       button3.addActionListener(
       new ActionListener() {
             public void actionPerformed(ActionEvent e)
                   if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                   displayPanel.setBackground(Color.white);
                   displayPanel.add(new JLabel(new ImageIcon("images/StackADT.jpg")));
                   displayPanel.revalidate();
       JButton button4 = new JButton("Stacks in the Real World");
       button4.addActionListener(
       new ActionListener() {
             public void actionPerformed(ActionEvent e)
                   if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                   displayPanel.setBackground(Color.white);
                   displayPanel.add(new JLabel(new ImageIcon("images/StacksInTheRealWorld.jpg")));
                   displayPanel.revalidate();
       JButton button5 = new JButton("DEMONSTRATION");
       button5.addActionListener(
       new ActionListener() {
             public void actionPerformed(ActionEvent e)
                 if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                 Demonstration app = new Demonstration();
                 JPanel appPanel = app.createComponents();//gets the created components from Demonstration application.
                 appPanel.setBackground(Color.pink);
               displayPanel.add(appPanel);
               displayPanel.revalidate();
       JButton button6 = new JButton("Towers Of Hanoi");
       button6.addActionListener(
       new ActionListener() {
             public void actionPerformed(ActionEvent e)
                     if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                     TowerOfHanoi app = new TowerOfHanoi();
                     JPanel appPanel = app.createComponents();//gets the created components from Towers of Hanoi
                     JPanel mainPanel = new JPanel();//panel used to centralise the application in center
                     mainPanel.add(appPanel);
                     mainPanel.setBackground(Color.pink); //sets mainPanel's background color for 'Towers Of Hanoi'
                     displayPanel.add(mainPanel);
                     displayPanel.revalidate();
       //adding buttons to the buttonPanel.
       buttonPanel.add(button1);
       buttonPanel.add(button2);
       buttonPanel.add(button3);
       buttonPanel.add(button4);
       buttonPanel.add(button5);
       buttonPanel.add(button6);
       JPanel p = new JPanel(); // Used so that the buttons maintain their default shape
       p.setBackground(Color.white);
       p.add(buttonPanel);
       holdingPanel.add(p,BorderLayout.WEST);
       holdingPanel.add(displayPanel,BorderLayout.CENTER);
       //Positioning of holdingPanel in mainPanel.
       mainPanel.add(holdingPanel,BorderLayout.CENTER);
       //indent mainPanel so that its not touching the applet window frame.
       mainPanel.setBorder(BorderFactory.createEmptyBorder(10,20,10,20));
       mainPanel.setBackground(Color.white);
       mainPanel.setPreferredSize(new Dimension(850,600)); //size of applet window
       mainPanel.setOpaque(false); // Needed for Applet
       this.setContentPane(mainPanel);
    }

    Thanks for the response. I don't quite understand what you're talking about though. I have, in my humble knowledge, done nothing with packages. I have put the applet class (WiaRekenToolActiz.class is the applet class) in the jar file wia_actiz_archive.jar. From what I read on the tutorial, java looks for the applet class in all the jar files specified. Since I put my CODEBASE as the main url, I thought it baiscally didn't matter where you out the html file.
    I shall include the complete html page complete with applet tag to perhaps illuminate a bit more what I mean...
    <html>
    <head>
    <title>Wia Rekenmodule hello!</title>
    </head>
    <body bgcolor="#C0C0C0">
    <applet
    CODEBASE= "http://www.creativemathsolutions.nl/test"
    ARCHIVE= "Actiz/wia_actiz_archive.jar, Generic/wia_archive.jar"
    CODE="WiaRekenToolActiz.class" 
    WIDTH=915 HEIGHT=555
    >
    <PARAM NAME = naam VALUE = "Piet Janssen">
    <PARAM NAME = gebdag VALUE = "01">
    <PARAM NAME = gebmaand VALUE = "06">
    <PARAM NAME = gebjaar VALUE = "1970">
    <PARAM NAME = geslacht VALUE = "man">
    <PARAM NAME = dienstjaren VALUE = "10">
    <PARAM NAME = salaris VALUE = "56500">
    <PARAM NAME = deeltijdpercentage VALUE = "100">
    <PARAM NAME = accountnaam VALUE = "Zorginstelling 'De Zonnebloem'">
    </applet>
    </body>
    </html>

  • Event Dispatch Thread Hangs, what is wrong?

    The Event Dispatch Thread Hangs when showing a modal dialog while running a
    SwingWorker Thread.
    I have included my code at the bottom of the page. There are three classes. I have posted a bug report to red hat. But I want to make sure my code is correct.
    My test case just puts the SwingWorker to sleep
    but the problem occurs if I do something real, like connect to a database, etc.
    Also I have tried little different variations of the logic calling
    setVisible(true)/(false) in different places and the same problem occurs.
    It seems to work with Sun JDK, note I am using IcedTea with Fedora Core 8.
    Version-Release number of selected component (if applicable):
    [szakrews@tuxtel ~]$ java -version
    java version "1.7.0"
    IcedTea Runtime Environment (build 1.7.0-b21)
    IcedTea Client VM (build 1.7.0-b21, mixed mode)How reproducible:
    Every couple times.
    javac TestClass2
    java TestClass2eventually it will hang. If it doesn't try again.
    You don't have to wait for the program to finish either.
    The program runs the Dialog 10 times but it never works or fails in the middle, it will either work or fail from the first dialog displayed.
    I have included a thread dump. That is about the most informative information I can get. Neither tracing nor writing a custom ThreadQueue or Drawing Manager to trace events produces any helpful information.
    Actual results:
    The JProccessBar won't move, and the SwingWorker finishes but the done() method is never run. The PROGRAM is not hung however because if I close the dialog then it will continue.
    Expected results:
    The JProccessBar should always move and the SwingWorker should always run the done() method.
    Additional info:
    java thread dump after freeze, taken with kill -s SIGQUIT <pid>
    2008-06-25 12:25:50
    Full thread dump IcedTea Client VM (1.7.0-b21 mixed mode):
    "DestroyJavaVM" prio=10 tid=0x938afc00 nid=0x1419 waiting on condition
    [0x00000000..0x0018a074]
       java.lang.Thread.State: RUNNABLE
    "AWT-EventQueue-0" prio=10 tid=0x938ae400 nid=0x1429 in Object.wait()
    [0x07f96000..0x07f96f04]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x96748f80> (a java.awt.EventQueue)
            at java.lang.Object.wait(Object.java:503)
            at java.awt.EventQueue.getNextEvent(EventQueue.java:485)
            - locked <0x96748f80> (a java.awt.EventQueue)
            at
    java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:248)
            at
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:201)
            at
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:195)
            at java.awt.Dialog$1.run(Dialog.java:1073)
            at java.awt.Dialog$3.run(Dialog.java:1127)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.awt.Dialog.show(Dialog.java:1125)
            at java.awt.Component.show(Component.java:1456)
            at java.awt.Component.setVisible(Component.java:1408)
            at java.awt.Window.setVisible(Window.java:871)
            at java.awt.Dialog.setVisible(Dialog.java:1012)
            at net.xtel.production.WaitDialog.showWaitDialog(WaitDialog.java:72)
            at net.xtel.production.WaitDialog.showWaitDialog(WaitDialog.java:102)
            at TestClass2.showWait(TestClass2.java:79)
            at TestClass2.createAndShowGUI(TestClass2.java:126)
            at TestClass2.access$0(TestClass2.java:114)
            at TestClass2$3.run(TestClass2.java:138)
            at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:227)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:603)
            at
    java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:276)
            at
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:201)
            at
    java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:191)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:186)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:178)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:139)
    "AWT-Shutdown" prio=10 tid=0x938ad000 nid=0x1428 in Object.wait()
    [0x03ea7000..0x03ea7f84]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x96749268> (a java.lang.Object)
            at java.lang.Object.wait(Object.java:503)
            at sun.awt.AWTAutoShutdown.run(AWTAutoShutdown.java:281)
            - locked <0x96749268> (a java.lang.Object)
            at java.lang.Thread.run(Thread.java:675)
    "AWT-XAWT" daemon prio=10 tid=0x938a8400 nid=0x1423 runnable
    [0x02ccc000..0x02ccd104]
       java.lang.Thread.State: RUNNABLE
            at sun.awt.X11.XToolkit.waitForEvents(Native Method)
            at sun.awt.X11.XToolkit.run(XToolkit.java:550)
            at sun.awt.X11.XToolkit.run(XToolkit.java:525)
            at java.lang.Thread.run(Thread.java:675)
    "Java2D Disposer" daemon prio=10 tid=0x93854000 nid=0x1421 in Object.wait()
    [0x07aea000..0x07aead84]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x966e7010> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
            - locked <0x966e7010> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:150)
            at sun.java2d.Disposer.run(Disposer.java:143)
            at java.lang.Thread.run(Thread.java:675)
    "Low Memory Detector" daemon prio=10 tid=0x93c15000 nid=0x141f runnable
    [0x00000000..0x00000000]
       java.lang.Thread.State: RUNNABLE
    "CompilerThread0" daemon prio=10 tid=0x93c13400 nid=0x141e waiting on condition
    [0x00000000..0x03a8a954]
       java.lang.Thread.State: RUNNABLE
    "Signal Dispatcher" daemon prio=10 tid=0x93c11c00 nid=0x141d waiting on
    condition [0x00000000..0x00000000]
       java.lang.Thread.State: RUNNABLE
    "Finalizer" daemon prio=10 tid=0x095e7000 nid=0x141c in Object.wait()
    [0x005d2000..0x005d3004]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x966e71d8> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
            - locked <0x966e71d8> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:150)
            at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:177)
    "Reference Handler" daemon prio=10 tid=0x095e2400 nid=0x141b in Object.wait()
    [0x00581000..0x00582084]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x966e7260> (a java.lang.ref.Reference$Lock)
            at java.lang.Object.wait(Object.java:503)
            at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:134)
            - locked <0x966e7260> (a java.lang.ref.Reference$Lock)
    "VM Thread" prio=10 tid=0x095dec00 nid=0x141a runnable
    "VM Periodic Task Thread" prio=10 tid=0x93c17400 nid=0x1420 waiting on condition
    JNI global references: 836
    Heap
    def new generation   total 960K, used 152K [0x93f40000, 0x94040000, 0x966a0000)
      eden space 896K,   9% used [0x93f40000, 0x93f56148, 0x94020000)
      from space 64K, 100% used [0x94020000, 0x94030000, 0x94030000)
      to   space 64K,   0% used [0x94030000, 0x94030000, 0x94040000)
    tenured generation   total 4096K, used 1088K [0x966a0000, 0x96aa0000, 0xb3f40000)
       the space 4096K,  26% used [0x966a0000, 0x967b01b0, 0x967b0200, 0x96aa0000)
    compacting perm gen  total 12288K, used 9169K [0xb3f40000, 0xb4b40000, 0xb7f40000)
       the space 12288K,  74% used [0xb3f40000, 0xb4834740, 0xb4834800, 0xb4b40000)
    No shared spaces configured.CLASS1:
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.sql.SQLException;
    import java.util.concurrent.ExecutionException;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.RepaintManager;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    public class TestClass2 extends JFrame implements ActionListener {
            /** Action Command for <code>searchbtn</code> */
            public static final String SEARCH_BTN_ACTION = "search_btn_action";
             * Constructor.
            public TestClass2() {
                    setSize(650, 350);
                    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                    setLocation(screenSize.width / 2 - getSize().width / 2,
                                    screenSize.height / 2 - getSize().height / 2);
                    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                    addWindowListener(new WindowAdapter() {
                            @Override
                            public void windowClosing(WindowEvent e) {
                                    exit();
                    JPanel panel = new JPanel();
                    add(panel);
                    setVisible(true);
            @Override
            public void actionPerformed(ActionEvent e) {
                    if (e.getActionCommand().equals(SEARCH_BTN_ACTION)) {
                            JOptionPane.showMessageDialog(this, "Button Pressed");
            public void showWait() {
                    try {
                            WaitDialog.showWaitDialog(this, "Testing...", new SwingWorkerInterface(){
                                    @Override
                                    public Object workToDo() throws Throwable {
                                            Thread.currentThread().sleep(3000);
                                            return null;
                    } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    } catch (ExecutionException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
             * Exits the program.
            public void exit(){
                    System.exit(0);
             * Create the GUI and show it. For thread safety, this method should be
             * invoked from the event-dispatching thread.
             * @throws UnsupportedLookAndFeelException
             * @throws IllegalAccessException
             * @throws InstantiationException
             * @throws ClassNotFoundException
             * @throws NullInstanceVariableException
             * @throws SQLException
            private static void createAndShowGUI() {
                    // set look and feel
                    try{
                            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                            // Create instance of the ProductCatalog
                            TestClass2 root = new TestClass2();
                            for(int i = 0; i < 10; i++){
                                    root.showWait();
                    }catch(Exception e){
                            e.printStackTrace();
             * @param args
             *            this program does not use arguments
            public static void main(String[] args) {
                    SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                    createAndShowGUI();
    }CLASS 2:
    import java.awt.Component;
    import java.awt.Frame;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.util.concurrent.ExecutionException;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    import javax.swing.SwingWorker;
    public class WaitDialog extends JDialog {
            private boolean disposed = false;
            private boolean displayed = false;
            private WorkerThread worker = null;
            WaitDialog(Frame parent, String text, SwingWorkerInterface in){
                    super(parent, true);
                    worker = new WorkerThread(in);
                    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                    addWindowListener(new WindowAdapter() {
                            @Override
                            public void windowOpened(WindowEvent e) {
                                    worker.execute();
                            @Override
                            public void windowClosing(WindowEvent e) {
                                    disposeWaitDialog();
                    this.setResizable(false);
                    JLabel message = new JLabel();
                    message.setText(text);
                    JProgressBar pb = new JProgressBar();
                    pb.setIndeterminate(true);
                    // set size and location
                    setSize(200, 100);
                    setLocationRelativeTo(parent);
                    JPanel panel = new JPanel();
                    panel.add(message);
                    panel.add(pb);
                    add(panel);
            public void showWaitDialog(){
                    if(displayed == true){
                            return;
                    if(disposed == true){
                            disposed = false;
                            return;
                    disposed = false;
                    displayed = true;
                    setVisible(true);
            public void disposeWaitDialog(){
                    if(disposed == true){
                            return;
                    if(displayed == true){
                            displayed = false;
                            setVisible(false);
                            return;
                    disposed = true;
                    displayed = false;
            public static Object showWaitDialog(Component parent, String text, SwingWorkerInterface in) throws InterruptedException, ExecutionException {
                    WaitDialog waitDialog = null;
                    if (parent == null) {
                            waitDialog = new WaitDialog(JOptionPane.getRootFrame(), text, in);
                    } else {
                            waitDialog = new WaitDialog(JOptionPane.getFrameForComponent(parent), text, in);
                    while(!waitDialog.worker.isDone()){
                            System.out.println("about to show");
                            waitDialog.showWaitDialog();
                            System.out.println("done showing");
                    waitDialog.dispose();
                    return waitDialog.worker.get();
            class WorkerThread extends SwingWorker<Throwable, Void> {
                    private SwingWorkerInterface in = null;
                    WorkerThread(SwingWorkerInterface in){
                            this.in = in;
                    public Throwable doInBackground(){
                                    try {
                                            System.out.println("about to do work");
                                            in.workToDo();
                                            System.out.println("done work no exception");
                                    } catch (Throwable e) {
                                            System.out.println("done work with exception");
                                            return e;
                                    return null;
                    public void done(){
                                    System.out.println("about to dispose");
                                    disposeWaitDialog();
                                    System.out.println("disposed");
    }CLASS 3:
    public interface SwingWorkerInterface {
            public Object workToDo() throws Throwable;
    }

    There's nothing directly wrong with it, but it will
    prevent other threads acquiring the class lock - but
    that may be what you want.True. Although the typical case for code that looks like this would be to use wait--usually the various threads in question require the same lock, so you have to use wait in order for the waiting thread to give it up and allow the other thread to do its work. Hard to say for sure though what he's doing.
    Also, if loading is all that the other thread does, and you're waiting for that thread to die, use join. But then, if that's the case, and you're only waiting for a single other thread, then you might as well just put it all in one thread, as already indicated.

Maybe you are looking for