Question on SwingUtilities.invokeLater

The program I have included is attempting to "simulate" opening and loading a file into memory.
Run the program, select File and then select Open. You will notice that the File menu does not disappear for 3 seconds (i.e. until the file has been completely read).
I was hoping it was possible to close the File menu while the file is being read. While reading through various documentation on the invokeLater() method I found the following:
"Both invokeLater() and invokeAndWait() wait until all pending AWT events finish before they execute"
Therefore by adding an invokeLater() method I was hoping to accomplish the following series of events:
1) click on Open menuItem
2) invoke OpenAction
3) do the "repaint" (which would cause the file menu to disappear)
4) finish the OpenAction
5) do the long running task
Hopefully you understand what I am trying to accomplish and can provide some guidance. Here is the sample program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestInvokeLater extends JFrame
     JFrame frame;
     JMenuBar menuBar;
     JMenu menu;
     JMenuItem menuItem;
     public TestInvokeLater()
          frame = this;
          setDefaultCloseOperation( EXIT_ON_CLOSE );
          menuBar = new JMenuBar();
          menu = new JMenu("File");
          menuBar.add(menu);
          menuItem = new JMenuItem( new OpenAction() );
          menu.add(menuItem);
          setJMenuBar( menuBar );
          JPanel panel = new JPanel();
          panel.setPreferredSize( new Dimension( 100, 100 ) );
          setContentPane( panel );
     class OpenAction extends AbstractAction
          public OpenAction()
               putValue( Action.NAME, "Open" );
          public void actionPerformed(ActionEvent e)
          repaint();
     SwingUtilities.invokeLater(new Runnable()
     public void run()
          try
               Thread.sleep(3000); // simulate log running task
          catch (Exception e) {}
     public static void main(String[] args)
          JFrame frame = new TestInvokeLater();
          frame.pack();
          frame.show();
}

Thanks for the input, but I still have some confusion -
"invokeLater() simply appends the thread to the end of the dispatch queue, this happens before the event code to hide the file menu gets queued"
This is the part that confuses me. If I understand event driven programming correctly then the code for the MenuItemClicked must complete execution before the next event in the queue can be executed.
If we assume the code for MenuItemClicked is something like:
1) fireActionEvent
2) fireCloseMenuEvent
When MenuItemClicked is finished executing the next event in the queue is the ActionEvent which invokes my ActionPerformed code:
1) I use the Swing invokeLater() method (which means it should be queued "after" the fireCloseMenuEvent
Does this make any sense?

Similar Messages

  • Is it safe to use SwingUtilities.invokeLater(), while updating GUI?

    Hi,
    I am updating GUI components in synchronized block which is runinng on main() thread my application hangs, but if I use SwingUtilities.invokeLater(...) then it runs fine.
    My question is:
    Is it safe to use SwingUtilities.invokeLater(...) in synchronized block.
    Edited by: Amol_Parekh on Nov 1, 2007 1:28 AM

    Paul Hyde in his "Java Thread Programming" (great book!!!) says it is.
    With invokeLater() you say to the Thread Scheduler you want that code to run on the Swing thread. In fact, if that is the only thing you do in the synchronized block I think it is unnecessary.
    Greetings,
    astrognom

  • Why do we have to use SwingUtilities.invokeLater() to update UI status?

    I just don't understand very well why we have to use SwingUtilities.invokeLater() to update UI status. Why not just new a thread in actionPerformed() method and do time consuming tasks in this thread and update UI status in it? Some tutorials say it is not safe to update UI status not in Event Dispatch Thread, I don't understand, why is it not safe? Can anyone provide a scenario for this? I just write an example, a button and a progressbar, click button, progressbar keeps updating value. I just create a new thread to do this, don't find any issue. Thanks.

    [Swing single threaded rule|http://www.lmgtfy.com/?q=swing+single+threaded+rule]
    db

  • Should I use a SwingWorker or SwingUtilities.invokeLater() to update my UI?

    Are there specific situations where you want to use method above the other? This whole swing concurrency is very new to me, and I don't really know where to begin.

    When executing long running code you don't want the GUI to freeze. Therefore you have two things to be concerned about. First, you want the long running task to execute in a separate Thread. Secondly, when you need to update the GUI from this code you need to make sure the code executes on the Event Dispatch Thread (EDT).
    You can code this manually by creating a separate Thread and then use SwingUtilities.invokeLater() when necessary.
    A SwingWorker tries to simplify this process by having a simple API where you can add code that executes on a separate Thread or where you can add code that executes on the EDT.
    So in the case of managing long running tasks, the end result should be the same.
    Hwever, there are times when I know code is already executing on the EDT, but I sometimes use invokeLater(..) to force my code to the end of the EDT. This is used in special situations when code doesn't execute in the order you want.
    For example, I've tried to add a FocusListener to a JFormattedTextField to "select the text" when it gains focus. The problem is the the UI also adds a FocusListener. Because of the way listeners are handled the last listener added to the component executes first. Therefore, using the invokeLater() forces my listener code to execute last.
    You can try this code to see what I mean:
    KeyboardFocusManager.getCurrentKeyboardFocusManager()
         .addPropertyChangeListener("permanentFocusOwner", new PropertyChangeListener()
         public void propertyChange(final PropertyChangeEvent e)
              if (e.getNewValue() instanceof JTextField)
                   //  invokeLater needed for JFormattedTextField
                   SwingUtilities.invokeLater(new Runnable()
                        public void run()
                             JTextField textField = (JTextField)e.getNewValue();
                             textField.selectAll();
    });Edited by: camickr on Mar 5, 2011 2:36 PM

  • How careful do you need to be with SwingUtilities.invokeLater()

    Is it safe to call an SwingUtilities.invokeLater() from within a method that was invoked with SwingUtilites.invokeLater() ?
    I'll give a quick example below.
        public void setWindowLocation(final Point p) {
            //Throw this on to the ETD with a recursive method call.
            if(!SwingUtilities.isEventDispatchThread()){
                SwingUtilities.invokeLater(new Runnable(){
                    public void run() {
                        setWindowLocation(p);
                //don't execute recursive call twice.
                return;
            }// end - EDT section.
            assert EventQueue.isDispatchThread():"Not Event Dispatch Thread";
            frame.setLocation(p);
            someOtherMethodThatCallsInvokeLater();
    public void someOtherMethodThatCallsInvokeLater(){
          //be lazy don't bother to check if already on event dispatch thread.
           Runnable update = new Runnable(){
                public void run(){
                    remoteModeWindow.setTransparency(50);
            SwingUtilities.invokeLater(update);
    }What would happen would when the second method is called that didn't bother to see if it was already on the Event Dispatch thread, and just called invokeLater() anyway. Is that harmless, or can it lead to deadlock, or some other inefficiency?
    The reason I ask, is I've seen some code in one class check and some in a different class that previously was only called from a non-dispatch thread never bothered to check. It is now possible that the "don't bother to check" method could be called in either situation (i.e. from a dispatch thread, or non-dispatch thread).
    Comments appreciated. What is a general guideline for this situation? Too many of the Swing books I've seen only lightly cover a few pages on this topic.
    Edited by: asnyder on Jul 2, 2009 7:14 PM

    Calling invokeLater(...) in this manner is absolutely safe with regards to deadlocks. What happens is that your runnable is enqueued at the end of the event queue. There is a possibility that another runnable has been dispatched in the mean time, so there is no guarantee that your code will be executed immediately:
    1. EDT enters someOtherMethodThatCallsInvokeLater()
    2. Another event (from another thread) triggers a repaint for a component or some other UI operation, which is enqueued
    3. Your runnable is enqueued on the EDT
    So highly theoretically there may be a delay which could be avoided if you immediately executed the runnable:
    public void someOtherMethodThatCallsInvokeLater(){
           Runnable update = new Runnable(){
                public void run(){
                    remoteModeWindow.setTransparency(50);
            if (SwingUtilities.isEventDispatchThread())
                update.run();
            else
                SwingUtilities.invokeLater(update);
    }In my experience though this kind of 'optimization' has no practical implications whatsoever.

  • Why do we have to call SwingUtilities.invokeLater()??

    Hello,
    i am not understanding the concept of SwingUtilities.invokeLater() i read the documentation but still couln't get why it is needed and when it is needed?do we have to call this function everytime some event is generated and some action is performed on component Ex.mouse click on button etc?? Please give me little details regarding it's concept!
    Thanks in advance :)

    (guys correct me if i'm wrong here)Most of the time that's correct, but for some customizations it is necessary to run custom code after all default code contained in the Swing classes has been executed. For example, to request focus be given to a component that would otherwise not be immediately focused, if you omit to enclose that in a invokeLater, it will get the focus but immediately lose it as still-queued events mandate the transfer of focus elsewhere. Moreover, as the event delivery mechanism is asynchronous, the behavior may be inconsistent.
    In general, any customization that may conflict with the normal flow should be wrapped in invokeLater, whether run from the EDT or another thread. The exceptions here are methods which the API declares to be thread safe.
    what you want to do is run that time consuming process in a thread, and when you need to call back to update the GUI, then use SwingUtilities.invokeLater.Or use SwingWorker, that's what it's for.
    cheers, db

  • Good practice to update Swing i SwingUtilities.invokeLater() method?

    Is it a good practice to allways make the updates/changes of Swing components in the SwingUtilities.invokeLater() method in a multithreaded application. Or are there any situations when it´s not?

    There are a number of methods that are thread safe, but they generally say so in the API
    If they aren't then you shouldn't be updating them on the EDT.
    [http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html|http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html]

  • EJB function using  SwingUtilities.invokeLater()  is problm msg publishing

    My problem for JMS using Message publish to group of people , What I did, Server side I am pushing message for each topic , (it could be n number of topic ) I created for Every five topic to as single thread. (Topic will be [ 200 ~2000] ) ,
    Some time this SwingUtilities.invokeLater() function will shown error Message AWT event
    I am using EJB Method for like this.
    new Thread()
    public void run()
         SwingUtilities.invokeLater( new Runnable() {
    public void run() {
         HashMap map=null;
         try
              map=MessagePublish2Group.init(); // to getting connection function .
              InitialContext iniCtx=(InitialContext)map.get("InitialContext");                
                   TopicSession session =(TopicSession) map.get("TopicSession");
                   TextMessage txtmsg = session.createTextMessage();
                   txtmsg.setText(Message);
              for(int i=0;i<userlist.length;i++)
                   try
                   Topic     receiver =(Topic) iniCtx.lookup("topic/"+userlist[i]+"");
              TopicPublisher usertopic = session.createPublisher(receiver);
              usertopic.publish(txtmsg);
              usertopic.close();     
                   catch(Exception gexp)
              close(map); // // to closing connection function .
         catch(Exception exp)
              close(map); // to closing connection function .
    exp.printStackTrace();
    }.start();
    Thanks in advance
    Sasikumar (Sasimsit)

    {color:red}{size:20px}TRIPLE POSTED{size}{color}
    [http://forums.sun.com/thread.jspa?threadID=5333442]
    [http://forums.sun.com/thread.jspa?threadID=5333443]
    [http://forums.sun.com/thread.jspa?threadID=5333445]
    Cross posting is rude.
    db

  • Javax.swing.SwingUtilities.invokeLater make my program slow

    i am writing a program in which i am implementing documentlistener
    to communicating between two frames
    if i write my code with javax.swing.SwingUtilities.invokeLater it makes my program slow
    and if i write without this thread safe quality then this is fast but giving me runtime exception
    what i do to make my program better
    kindly suggest
    public void insertUpdate(DocumentEvent e) {
                updateLog(e, "inserted into");
            public void removeUpdate(DocumentEvent e) {
                updateLog(e, "removed from");
            public void changedUpdate(DocumentEvent e) {
                //Plain text components don't fire these events.
            public void updateLog(DocumentEvent e, String action) {
                Document doc = (Document)e.getDocument();
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
    tf4.setText(lbl.getText());
    }

    If your program is becoming too slow or unresponsive, it means that the operation "tf4.setText(lbl.getText());" is taking too long to execute and is therefore blocking the Swing-thread.
    There is little you can do to make that operation faster, but perhaps you can change how or how often you update the frames.
    Setting the whole text via setText() everytime a change happens seems very wasteful. Imagine you have a text with a million characters, and every time the user adds or changes just one character, you are getting and seting over one million characters. That is not the right approach.
    I'm not familiar with text-operations or class DocumentEvent, but I guess that there should be some kind of delta in DocumentEvent containing only the changes that were made. You could apply only these changes on tf4 instead of setting the whole text. Finding out how to do this would be the best solution. This will also make your program more scalable, as with setText() the performance of your application will continuously decrease as the text length increases.
    Usually when working with documents you have a "viewer" and a "model". If your viewer was a JTextBox and your model was, say a StringBuilder, you could make quick changes to the contents of JTextBox using the StringBuilder.append() or delete() methods without having to modify the whole text. You need to find out how this is done with whatever UI system you're using.
    If you can't find out how to do the above, a workaround would be to reduce how often you call "updateLog()". For example, is it truly necessary to call "updateLog" every time a new update happens? Perhaps it would be better to use a timer and only call "updateLog()" every few seconds.
    But as I said, this should only be a temporary workaround. You really should find out how to perform more efficient updates without using setText(). I recommend you search for tutorials and guides on how to work with text and documents on the internet.

  • A question about SwingUtilities.invokeAndWait

    I have this method in my program:
          * Execute the query and closes the dialog
         private void executeQueryAndClose() {
              String whereClause = (String) queryCbo.getSelectedItem();          
              List<JobFields> jobs = controller.getQueryResult(whereClause);
              controller.getEditWindow().getResultsPane().cleanResults();
              controller.getEditWindow().getResultsPane().displayResults(jobs);
              dispose();
         }this method executes a query to the db, display the results and closes
    the query dialog.
    This method is run in the event dispatcher thread.
    Now I was wondering if I should put the controller.getQueryResults in a different thread and run SwingUtilities.invokeAndWait with the new thread.
    I have to wait for the results from the db to return before I can display them,
    but I accomplish the same thing by running it the way written above.
    What's the difference between retrieving the results from the db in the event dispatcher thread and running them in a seperate thread and waiting for them to return by using invokeAndWait?
    In both ways I wait for the results from the db to return.

    I have this method in my program:
          * Execute the query and closes the dialog
         private void executeQueryAndClose() {
    String whereClause = (String)
    g) queryCbo.getSelectedItem();          
    List<JobFields> jobs =
    = controller.getQueryResult(whereClause);
              controller.getEditWindow().getResultsPane().cleanRes
    ults();
              controller.getEditWindow().getResultsPane().displayR
    esults(jobs);
              dispose();
         }this method executes a query to the db, display the
    results and closes
    the query dialog.
    This method is run in the event dispatcher thread.
    Now I was wondering if I should put the
    controller.getQueryResults in a different thread and
    run SwingUtilities.invokeAndWait with the new
    thread.
    I have to wait for the results from the db to return
    before I can display them,
    but I accomplish the same thing by running it the way
    written above.
    What's the difference between retrieving the results
    from the db in the event dispatcher thread and
    running them in a seperate thread and waiting for
    them to return by using invokeAndWait?
    In both ways I wait for the results from the db to
    return.If you do this work in the Event dispatch Thread, you will block all other event related activity from occurring. For example, if you press a button to retrieve the results, the button may seem stuck in the pressed position while the work occurs. This is one of the primary sources of 'preceived slowness' with Swing applications.
    The proper way to do this is the spawn a Thread to do the work, and then use invokeLater (not invokeAndWait) from this spawned Thread to update the UI. I created an example that exhibits the 'bad' and 'good' way to do this. See this post:
    http://forum.java.sun.com/thread.jspa?threadID=743510

  • InvokeLater() Question

    Hi,
    I have a problem with the invokeLater method of class SwingUtilities. In my program i have a thread that disables a button when clicked. I want to enable the button from another thread that is not started from within the event dispatched thread. When i execute the method it doesn't run until the second time i click the button. Can someone explain to me what is happening?
    Thank you.

    The documentation of SwingUtilities#invokeLater is adequately descriptive and provides a link to the Threading tutorial for the benefit for those who don't understand multithreading. I suggest you go through both the documentation and the tutorial.
    db

  • More JTextPane Questions

    Hi Guys
    I posted this question on the Java Ranch forums yesterday evening, but I haven't received a response yet, so I figured that I'd try these forums as well. You can view the other thread here; http://www.coderanch.com/t/554155/GUI/java/JTextPane-Questions.
    We're trying to build a simple WYSIWYG HTML editor using a JTextPane. I've used Charles Bell's example, available here; http://www.artima.com/forums/flat.jsp?forum=1&thread=1276 as a reference. My biggest gripe with it at the moment is that bullets aren't working as I would expect them to. If I highlight text and click the "Bullet" button, I want a bullet to be placed immediately before the highlighted text, on the same line. If I try to do this, my code is creating bullets, but it moves the selected text one line down. I've gone through the Oracle tutorial on text components, but I couldn't find anything that helped me with this particular issue.
    Also, if I copy and paste text into my JTextPane, the pasted text always appears on a new line (a new paragraph tag in the actual HTML). Is there a way to prevent the JTextPane from creating new paragraphs?
    Lastly, I'm flabbergasted as to why my buttons actually work. I can't see anything that explicitly links my buttons to my HTMLEditorKit or my JTextPane. Short of a little voodoo man living under my keyboard, how on earth do my buttons/actions know that they should update the JTextPane?
    The code is as follows;
    package myhtmleditor;
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Action;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.SwingUtilities;
    import javax.swing.text.StyledEditorKit;
    import javax.swing.text.html.HTML;
    import javax.swing.text.html.HTMLDocument;
    import javax.swing.text.html.HTMLEditorKit;
    public class Main {
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("My HTML Editor");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setSize(500, 500);
                    frame.setLayout(new BorderLayout());
                    JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
                    HTMLDocument document = new HTMLDocument();
                    final JTextPane htmlEditorPane = new JTextPane(document);
                    Action bold = new StyledEditorKit.BoldAction();
                    Action italic = new StyledEditorKit.ItalicAction();
                    Action underline = new StyledEditorKit.UnderlineAction();
                    JButton boldButton = new JButton(bold);
                    boldButton.setText("Bold");
                    buttonsPanel.add(boldButton);
                    JButton italicButton = new JButton(italic);
                    italicButton.setText("Italic");
                    buttonsPanel.add(italicButton);
                    JButton underlineButton = new JButton(underline);
                    underlineButton.setText("Underline");
                    buttonsPanel.add(underlineButton);
                    HTMLEditorKit.InsertHTMLTextAction bulletAction = new HTMLEditorKit.InsertHTMLTextAction("Bullet", "<ul><li> </li></ul>", HTML.Tag.BODY, HTML.Tag.UL);
                    JButton bulletButton = new JButton(bulletAction);
                    bulletButton.setText("Bullet");
                    buttonsPanel.add(bulletButton);
                    JButton printButton = new JButton("Print to Console");
                    printButton.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                            System.out.println(htmlEditorPane.getText());
                    buttonsPanel.add(printButton);
                    htmlEditorPane.setContentType("text/html");
                    HTMLEditorKit editorKit = new HTMLEditorKit();
                    htmlEditorPane.setEditorKit(editorKit);
                    frame.add(buttonsPanel, BorderLayout.NORTH);
                    frame.add(new JScrollPane(htmlEditorPane), BorderLayout.CENTER);
                    frame.setVisible(true);
    }Thank you for your input.
    Cheers,
    rfnel

    See how the bullet action changes HTML (compare getText() result before and after the bullet applying. It seems you need more smart way of adding bullets.
    Answer some questions if user selects whole paragraph should the <p> tag be removed and replaced with <li>? If user selects just one word in the paragraph and pressed bullet should the whole paragraph be bulleted?
    When you copy something you clipboard contains something like this "<html><body> content</body></html>". Try to override read() method of your kit (or Reader) to skip the main tags.
    For components see ObjectView class source.
    In fact when HTMLDocument is created from String components classes are created and stored in attributes of Elements. Then during rendering ComponentView extension (ObjectView) creates components.

  • TextSamplerDemo.java question

    I took the TextSamplerDemo from http://java.sun.com/docs/books/tutorial/uiswing/components/text.html and stripped it down to the one thing I have a question about. Given the code below, how do I implement the toolbar button to make selected text turn bold? I've been beating my head againt this one for a couple of days now and getting nowhere.
    Any help would be deeply appeciated.
    --gary
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*; //for layout managers and more
    import java.awt.event.*; //for action events
    public class TextSamplerDemo extends JPanel
    implements ActionListener {
    private String newline = "\n";
    protected static final String textFieldString = "JTextField";
    public TextSamplerDemo() {
    setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    JToolBar toolBar = buildToolbar();
    add(toolBar);
    //Create a text pane.
    JTextPane textPane = createTextPane();
    JScrollPane paneScrollPane = new JScrollPane(textPane);
    paneScrollPane.setVerticalScrollBarPolicy(
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    paneScrollPane.setPreferredSize(new Dimension(250, 155));
    paneScrollPane.setMinimumSize(new Dimension(10, 10));
    add(textPane);
    public void actionPerformed(ActionEvent e) {
    private JTextPane createTextPane() {
    String[] initString =
    { "This is an editable JTextPane, ",            //regular
    "another ", //italic
    "styled ", //bold
    "text ", //small
    "component, " + newline, //large
    "which supports embedded components..." + newline,//regular
    newline + "JTextPane is a subclass of JEditorPane that " + newline +
    "uses a StyledEditorKit and StyledDocument, and provides " + newline +
    "cover methods for interacting with those objects."
    String[] initStyles =
    { "regular", "italic", "bold", "small", "large",
    "regular", "regular"
    JTextPane textPane = new JTextPane();
    StyledDocument doc = textPane.getStyledDocument();
    addStylesToDocument(doc);
    try {
    for (int i=0; i < initString.length; i++) {
    doc.insertString(doc.getLength(), initString,
    doc.getStyle(initStyles[i]));
    } catch (BadLocationException ble) {
    System.err.println("Couldn't insert initial text into text pane.");
    return textPane;
    protected void addStylesToDocument(StyledDocument doc) {
    //Initialize some styles.
    Style def = StyleContext.getDefaultStyleContext().
    getStyle(StyleContext.DEFAULT_STYLE);
    Style regular = doc.addStyle("regular", def);
    StyleConstants.setFontFamily(def, "SansSerif");
    Style s = doc.addStyle("italic", regular);
    StyleConstants.setItalic(s, true);
    s = doc.addStyle("bold", regular);
    StyleConstants.setBold(s, true);
    s = doc.addStyle("small", regular);
    StyleConstants.setFontSize(s, 10);
    s = doc.addStyle("large", regular);
    StyleConstants.setFontSize(s, 16);
    private JToolBar buildToolbar() {
    JToolBar toolBar = new JToolBar();
    toolBar.setRollover( true );
    toolBar.setFloatable( false );
    JButton boldButton = new JButton("Bold");
    boldButton.setToolTipText( "Set selected text to bold" );
    boldButton.addActionListener( new ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    // code here to make selected text bold
    toolBar.add( boldButton );
    return toolBar;
    * 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("TextSamplerDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new TextSamplerDemo();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //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();

    try this, but im'not sure.
    StyleContext styleContext = StyleContext.getDefaultStyleContext();
    Style def = styleContext.getStyle(StyleContext.DEFAULT_STYLE);
    Style bold = styledDocument.addStyle("bold", def);
    StyleConstants.setBold(bold, true);into the listener of your component insert this:
    int start = getSelectionStart();
    int len = getSelectionEnd() - start;
    styledDocument.setCharacterAttributes(start, len, bold, true);by gino

  • Pass parameter to Runnable invoked by SwingUtil.invokeLater()

    Hi there,
    I just got trapped by a Threading problem in my SwingApplet:
    The Applet parses XML Documents it receives from a Servlet and dynamically creates a GUI from that description, using Swing Components. (actually Applet and Servlet exchange a Queue of JAVA Objects, each representing a fraction of the complete GUI Description or causing the Applet to show a certain URL, for example)
    Getting the XML Documents is done in an extra Thread (not the EventDispatchThread), since that might take a while. For doing the actual update of the Swing Components I use SwingUtilities.invokeLater(Runnable doc).
    doc is my internal Representation of the GUI, doc.run() does the actual Parsing and GUI Updating.
    My Question is: How can I pass doc the Message it has to parse in a way that subsequent calls to invokeLater(doc) (which - as I mentioned - are done in another Thread) cannot disturb the processing of the previous call?
    My actual (pseudo-)code tries it this way:
    Executed in Calling Thread:
    private void callSwing(PWDocumentGui doc)
    try
    Iterator it = fromserver.getInqueue().iterator();
    while (it.hasNext())
    PWMessage msg = (PWMessage) it.next();
    doc.setContent(msg);
    Thread.sleep(2000); // makes it work for the moment - but thats extremely unsafe!!
    it.remove();
    catch (Exception e)
    System.err.println(e);
    Internal Document representing the GUI:
    class PWDocumentGui extends Observable implements Runnable
    private InternalModel internalmodel; // holds internal Model of GUI (Arrays of Swing Components
    private String onemessage; // holds one message to be parsed: VALUE IS THE PROBLEM !
    public void synchronized setContent(String themessage)
    onemessage = themessage; // remeber the Message to be parsed
    SwingUtilities.invokeLater(this) // call this.run() in EventThtead
    // Called in Event Thread
    // value of onemessage in the meantime might be overwritten by subsequent call to setContent().
    public void run()
    // do the parsing into the local and thus update internalmodel
    parse(onemessage);
    // Notify Observers (the Renderers registered as Observers of this) that they should update themselves
    // accordicg to internalmodel
    setChanged()
    notifyObservers();
    public InternalModel getModel() {    return internalmodel;   }
    I suspect that the solution might be easy - for someone more relaxed...
    This might be a question concerning design, not Swing, I think.
    Thanks for any answer!
    Uwe

    Try creating an inner class which implements runnable.
    Give the inner class members to hold the parameters you want to pass.
    Implement the inner class's run() to check the variables and use them.
    When calling invoke later create a new instance of the inner class, initialise the members for the parameter values and pass the inner class instance to invokeLater rather than the object of the main class.
    In this way you get one copy of the parameters for every call to invoke later.

  • Very Basic Question on Threads and Object Manipulation between classes

    I have a feeling this is on the virge of being a stupid question but hey, its the right forum.
    Lets assume I have a class that extends Jframe : Jframe1
    In that frame there is only one Jlabel : Jlabel1
    I want to create a thread that will affect Jlabel1
    The thread will run an endless loop that will.. for example change the color of the label to a random color and then the thread will sleep for a given time. There is no use in this program. Its only meant to help me understand
    I have looked up info and examples on threads. Unfortunately none were useful. Most examples try to illustrate the use of threads with the example of an applet digital clock. But it does not help with my problem, not to mention I dont want to delve into applets at this time.
    I know I have to make a class that extends thread. Does it have to be an inner class?
    How do I get to affect the frame's Jlabel1 from it? It says it doesn't know anything about it.

    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    public class Jframe1 extends JFrame implements Runnable{
      Container con;
      JLabel Jlabel1;
      Random rand;
      Color c;
      public Jframe1(){
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        con = getContentPane();
        rand = new Random();
        Jlabel1 = new JLabel("bspus", JLabel.CENTER);
        Jlabel1.setOpaque(true);
        con.add(Jlabel1, BorderLayout.NORTH);
        setSize(300, 300);
        setVisible(true);
      public void run(){
        while (true){
          try{
            Thread.sleep(1000);
          catch (InterruptedException e){
            break;
          int n = rand.nextInt(16777216);
          c = new Color(n);
          SwingUtilities.invokeLater(new Runnable(){
            public void run(){
              Jlabel1.setBackground(c);
      public static void main(String[] args){
        Jframe1 jf = new Jframe1();
        new Thread(jf).start(); // you don't need to create a new thread
      }                         // because this Main thread is just
                                // another thread.
                                // here, only for demonstration purpose,
    }                           // we make a new separate thread.

Maybe you are looking for