Search Results

Search found 72 results on 3 pages for 'swingutilities'.

Page 1/3 | 1 2 3  | Next Page >

  • Java - Difference between SwingWorker and SwingUtilities.invokeLater()

    - by Yatendra Goel
    SwingWorker is used for the following purposes: For running long-running tasks in a different thread so as to prevent the GUI from being unresponsive For updating GUI with the results produced by the long-running task at the end of the task through done() method. For updating GUI from time to time with the intermediate results produced and published by the task with the help of publish() and process() methods. SwingUtilities.invokeLater() can perform the above tasks as follows: Instead of executing SwingWorker.execute() method from the EDT, we can execute ExecutorService.submit(new MyRunnable()) as it will also create another thread which can execute long-running task. For updating GUI at the end of the task, we can put code (written in done() method of case1) SwingUtilites.invokeLater(new RunnableToExecuteDoneMethodCode()) at the end of the task. For updating GUI in the middle of the task, we can put code (written in process() method of case1) SwingUtilites.invokeLater(new RunnableToExecuteProcessMethodCode()) at the place where we called publish() method in case1. I am asking this question because the problem specified in question http://stackoverflow.com/questions/2797483/java-swingworker-can-we-call-one-swingworker-from-other-swingworker-instead-o/2824306#2824306 can be solved by SwingUtilities.invokeLater() but can't be solved with SwingWorker

    Read the article

  • DefaultStyledDocument.styleChanged(Style style) may not run in a timely manner?

    - by Paul Reiners
    I'm experiencing an intermittent problem with a class that extends javax.swing.text.DefaultStyledDocument. This document is being sent to a printer. Most of the time the formatting of the document looks correct, but once in a while it doesn't. It looks like some of the changes in the formatting have not been applied. I took a look at the DefaultStyledDocument.styleChanged(Style style) code: /** * Called when any of this document's styles have changed. * Subclasses may wish to be intelligent about what gets damaged. * * @param style The Style that has changed. */ protected void styleChanged(Style style) { // Only propagate change updated if have content if (getLength() != 0) { // lazily create a ChangeUpdateRunnable if (updateRunnable == null) { updateRunnable = new ChangeUpdateRunnable(); } // We may get a whole batch of these at once, so only // queue the runnable if it is not already pending synchronized(updateRunnable) { if (!updateRunnable.isPending) { SwingUtilities.invokeLater(updateRunnable); updateRunnable.isPending = true; } } } } /** * When run this creates a change event for the complete document * and fires it. */ class ChangeUpdateRunnable implements Runnable { boolean isPending = false; public void run() { synchronized(this) { isPending = false; } try { writeLock(); DefaultDocumentEvent dde = new DefaultDocumentEvent(0, getLength(), DocumentEvent.EventType.CHANGE); dde.end(); fireChangedUpdate(dde); } finally { writeUnlock(); } } } Does the fact that SwingUtilities.invokeLater(updateRunnable) is called, rather than invokeAndWait(updateRunnable), mean that I can't count on my formatting changes appearing in the document before it is rendered? If that is the case, is there a way to ensure that I don't proceed with rendering until the updates have occurred?

    Read the article

  • Why Look and feel is not getting updated properly?

    - by swift
    I’m developing a swing application in which I have an option to change the Look and feel of the application on click of a button. Now my problem is when I click the button to change the theme it’s not properly updating the L&F of my app, say my previous theme is “noire” and I choose “MCWin” after it, but the style of the noire theme is still there Here is sample working code: package whiteboard; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import javax.swing.JFrame; import javax.swing.JLayeredPane; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.WindowConstants; public class DiscussionBoard extends JFrame implements ComponentListener,ActionListener { // Variables declaration private JMenuItem audioMenuItem; private JMenuItem boardMenuItem; private JMenuItem exitMenuItem; private JMenuItem clientsMenuItem; private JMenuItem acryl; private JMenuItem hifi; private JMenuItem aero; private JMenuItem aluminium; private JMenuItem bernstein; private JMenuItem fast; private JMenuItem graphite; private JMenuItem luna; private JMenuItem mcwin; private JMenuItem noire; private JMenuItem smart; private JMenuBar boardMenuBar; private JMenuItem messengerMenuItem; private JMenu openMenu; private JMenu saveMenu; private JMenu themesMenu; private JMenuItem saveMessengerMenuItem; private JMenuItem saveWhiteboardMenuItem; private JMenu userMenu; JLayeredPane layerpane; /** Creates new form discussionBoard * @param connection */ public DiscussionBoard() { initComponents(); setLocationRelativeTo(null); addComponentListener(this); } private void initComponents() { boardMenuBar = new JMenuBar(); openMenu = new JMenu(); themesMenu = new JMenu(); messengerMenuItem = new JMenuItem(); boardMenuItem = new JMenuItem(); audioMenuItem = new JMenuItem(); saveMenu = new JMenu(); saveMessengerMenuItem = new JMenuItem(); saveWhiteboardMenuItem = new JMenuItem(); userMenu = new JMenu(); clientsMenuItem = new JMenuItem(); exitMenuItem = new JMenuItem(); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(new GridBagLayout()); setResizable(false); setTitle("Discussion Board"); openMenu.setText("Open"); saveMenu.setText("Save"); themesMenu.setText("Themes"); acryl = new JMenuItem("Acryl"); hifi = new JMenuItem("HiFi"); aero = new JMenuItem("Aero"); aluminium = new JMenuItem("Aluminium"); bernstein = new JMenuItem("Bernstein"); fast = new JMenuItem("Fast"); graphite = new JMenuItem("Graphite"); luna = new JMenuItem("Luna"); mcwin = new JMenuItem("MCwin"); noire = new JMenuItem("Noire"); smart = new JMenuItem("Smart"); hifi.addActionListener(this); acryl.addActionListener(this); aero.addActionListener(this); aluminium.addActionListener(this); bernstein.addActionListener(this); fast.addActionListener(this); graphite.addActionListener(this); luna.addActionListener(this); mcwin.addActionListener(this); noire.addActionListener(this); smart.addActionListener(this); messengerMenuItem.setText("Messenger"); openMenu.add(messengerMenuItem); openMenu.add(boardMenuItem); audioMenuItem.setText("Audio Messenger"); openMenu.add(audioMenuItem); exitMenuItem.setText("Exit"); exitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { exitMenuItemActionPerformed(evt); } }); openMenu.add(exitMenuItem); boardMenuBar.add(openMenu); saveMessengerMenuItem.setText("Messenger"); saveMenu.add(saveMessengerMenuItem); saveWhiteboardMenuItem.setText("Whiteboard"); saveMenu.add(saveWhiteboardMenuItem); boardMenuBar.add(saveMenu); userMenu.setText("Users"); clientsMenuItem.setText("Current Session"); userMenu.add(clientsMenuItem); themesMenu.add(acryl); themesMenu.add(hifi); themesMenu.add(aero); themesMenu.add(aluminium); themesMenu.add(bernstein); themesMenu.add(fast); themesMenu.add(graphite); themesMenu.add(luna); themesMenu.add(mcwin); themesMenu.add(noire); themesMenu.add(smart); boardMenuBar.add(userMenu); boardMenuBar.add(themesMenu); saveMessengerMenuItem.setEnabled(false); saveWhiteboardMenuItem.setEnabled(false); setJMenuBar(boardMenuBar); setSize(1024, 740); setVisible(true); } protected void exitMenuItemActionPerformed(ActionEvent evt) { System.exit(0); } @Override public void componentHidden(ComponentEvent arg0) { } @Override public void componentMoved(ComponentEvent e) { } @Override public void componentResized(ComponentEvent arg0) { } @Override public void componentShown(ComponentEvent arg0) { } @Override public void actionPerformed(ActionEvent e) { try { if(e.getSource()==hifi) { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.hifi.HiFiLookAndFeel"); enableTheme(); hifi.setEnabled(false); } else if(e.getSource()==acryl) { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.acryl.AcrylLookAndFeel"); enableTheme(); acryl.setEnabled(false); } else if(e.getSource()==aero) { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.aero.AeroLookAndFeel"); enableTheme(); aero.setEnabled(false); } else if(e.getSource()==aluminium) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.aluminium.AluminiumLookAndFeel"); enableTheme(); aluminium.setEnabled(false); } else if(e.getSource()==bernstein) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.bernstein.BernsteinLookAndFeel"); enableTheme(); bernstein.setEnabled(false); } else if(e.getSource()==fast) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.fast.FastLookAndFeel"); enableTheme(); fast.setEnabled(false); } else if(e.getSource()==graphite) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.graphite.GraphiteLookAndFeel"); enableTheme(); graphite.setEnabled(false); } else if(e.getSource()==luna) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.luna.LunaLookAndFeel"); enableTheme(); luna.setEnabled(false); } else if(e.getSource()==mcwin) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.mcwin.McWinLookAndFeel"); enableTheme(); mcwin.setEnabled(false); } else if(e.getSource()==noire) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.noire.NoireLookAndFeel"); enableTheme(); noire.setEnabled(false); } else if(e.getSource()==smart) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.smart.SmartLookAndFeel"); enableTheme(); smart.setEnabled(false); } SwingUtilities.updateComponentTreeUI(getRootPane()); } catch (Exception ex) { ex.printStackTrace(); } } private void enableTheme() { acryl.setEnabled(true); hifi.setEnabled(true); aero.setEnabled(true); aluminium.setEnabled(true); bernstein.setEnabled(true); fast.setEnabled(true); graphite.setEnabled(true); luna.setEnabled(true); mcwin.setEnabled(true); noire.setEnabled(true); smart.setEnabled(true); } public static void main(String []ar) { try { UIManager.setLookAndFeel("com.jtattoo.plaf.acryl.AcrylLookAndFeel"); } catch (Exception e) { e.printStackTrace(); } new DiscussionBoard(); } } What’s the problem here? why its not getting updated? There is a demo application here which is exactly doing what i want but i cant get a clear idea of it.

    Read the article

  • Check if thread is EDT is necessary?

    - by YuppieNetworking
    Hello, I have an UI implemented with Swing. One component does some work that may take some time, so I use SwingUtilities.invokeLater. However, I was reading some old code and found this in an ActionListener: if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { // code X } }); } else { // code X } I thought that it made sense since it separates code X from the EDT. However, I found it error-prone since I have used it a couple of times and both times I forgot the else part. The question is: is the SwingUtilities.isEventDispatchThread() checking necessary? Or could I assume that I am not in the EDT and always use invokeLater? Thanks a lot.

    Read the article

  • Java's Swing Threading

    - by nevets1219
    My understanding is that if I start up another thread to perform some actions, I would need to SwingUtilities.invokeAndWait or SwingUtilities.invokeLater to update the GUI while I'm in said thread. Please correct me if I'm wrong. What I'm trying to accomplish is relatively straightforward: when the user clicks submit, I want to (before performing any actions) disable the submit button, perform the action, and at the end of the action re-enable the button. My method to perform the action updates the GUI directly (displays results) when it gets the results back. This action basically queries a server and gets some results back. What I have so far is: boolean isRunning = false; synchronized handleButtonClick() { if ( isRunning == false ) { button.setEnabled( false ); isRunning = true; doAction(); } } doAction() { new Thread() { try { doAction(); // Concern A } catch ( ... ) { displayStackTrace( ... ); // Concern B } finally { SwingUtilities.invokeLater ( /* simple Runnable to enable button */ ); isRunning = false; } } } For both of my concerns above, do I would have to use SwingUtilities.invokeAndWait since they both will update the GUI? All GUI updates revolve around updating JTextPane. Do I need to in my thread check if I'm on EDT and if so I can call my code (regardless of whether it updates the GUI or not) and NOT use SwingUtilities.invokeAndWait?

    Read the article

  • Can it be done in a more elegant way with the Swing Timer?

    - by Roman
    Bellow is the code for the simplest GUI countdown. Can the same be done in a shorter and more elegant way with the usage of the Swing timer? import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; public class CountdownNew { static JLabel label; // Method which defines the appearance of the window. public static void showGUI() { JFrame frame = new JFrame("Simple Countdown"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); label = new JLabel("Some Text"); frame.add(label); frame.pack(); frame.setVisible(true); } // Define a new thread in which the countdown is counting down. public static Thread counter = new Thread() { public void run() { for (int i=10; i>0; i=i-1) { updateGUI(i,label); try {Thread.sleep(1000);} catch(InterruptedException e) {}; } } }; // A method which updates GUI (sets a new value of JLabel). private static void updateGUI(final int i, final JLabel label) { SwingUtilities.invokeLater( new Runnable() { public void run() { label.setText("You have " + i + " seconds."); } } ); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { showGUI(); counter.start(); } }); } }

    Read the article

  • How can I remove a JPanel from a JFrame?

    - by Roman
    Recently I asked here how to add a new JPanel to JFrame. The answer helped me to get a working code. But not I have a related question: "How can I remove an old JPanel". I need that because of the following problem. A new JPanel appears appears when I want (either time limit is exceeded or user press the "Submit" button). But in several seconds some element of the old JPanel appears together with the component of the new JPanel. I do not understand why it happens. I thought that it is because I have to other threads which update the window. But the first thread just add the old panel once (so, it should be finished). And in the second thread I have a loop which is broken (so, it also should be finished). Here is my code: private Thread controller = new Thread() { public void run() { // First we set the initial pane (for the selection of partner). SwingUtilities.invokeLater(new Runnable() { public void run() { frame.getContentPane().add(generatePartnerSelectionPanel()); frame.invalidate(); frame.validate(); } }); // Update the pane for the selection of the parnter. for (int i=40; i>0; i=i-1) { final int sec = i; SwingUtilities.invokeLater(new Runnable() { public void run() { timeLeftLabel.setText(sec + " seconds left."); } }); try {Thread.sleep(1000);} catch (InterruptedException e) {} if (partnerSubmitted) {break;} } // For the given user the selection phase is finished (either the time is over or form was submitted). SwingUtilities.invokeLater(new Runnable() { public void run() { frame.getContentPane().add(generateWaitForGamePanel()); frame.invalidate(); frame.validate(); } }); } };

    Read the article

  • Swing modal dialog refuses to close - sometimes!

    - by Zarkonnen
    // This is supposed to show a modal dialog and then hide it again. In practice, // this works about 75% of the time, and the other 25% of the time, the dialog // stays visible. // This is on Ubuntu 10.10, running: // OpenJDK Runtime Environment (IcedTea6 1.9) (6b20-1.9-0ubuntu1) // This always prints // setVisible(true) about to happen // setVisible(false) about to happen // setVisible(false) has just happened // even when the dialog stays visible. package modalproblemdemo; import java.awt.Frame; import javax.swing.JDialog; import javax.swing.SwingUtilities; public class Main { public static void main(String[] args) { final Dialogs d = new Dialogs(); new Thread() { @Override public void run() { d.show(); d.hide(); } }.start(); } static class Dialogs { final JDialog dialog; public Dialogs() { dialog = new JDialog((Frame) null, "Hello World", /*modal*/ true); dialog.setSize(400, 200); } public void show() { SwingUtilities.invokeLater(new Runnable() { public void run() { dialog.setLocationRelativeTo(null); System.out.println("setVisible(true) about to happen"); dialog.setVisible(true); }}); } public void hide() { SwingUtilities.invokeLater(new Runnable() { public void run() { System.out.println("setVisible(false) about to happen"); dialog.setVisible(false); System.out.println("setVisible(false) has just happened"); }}); } } }

    Read the article

  • Is it a good way to close a thread?

    - by Roman
    I have a short version of the question: I start a thread like that: counter.start();, where counter is a thread. At the point when I want to stop the thread I do that: counter.interrupt() In my thread I periodically do this check: Thread.interrupted(). If it gives true I return from the thread and, as a consequence, it stops. And here are some details, if needed: If you need more details, they are here. From the invent dispatch thread I start a counter thread in this way: public static void start() { SwingUtilities.invokeLater(new Runnable() { public void run() { showGUI(); counter.start(); } }); } where the thread is defined like that: public static Thread counter = new Thread() { public void run() { for (int i=4; i>0; i=i-1) { updateGUI(i,label); try {Thread.sleep(1000);} catch(InterruptedException e) {}; } // The time for the partner selection is over. SwingUtilities.invokeLater(new Runnable() { public void run() { frame.remove(partnerSelectionPanel); frame.add(selectionFinishedPanel); frame.invalidate(); frame.validate(); } }); } }; The thread performs countdown in the "first" window (it shows home much time left). If time limit is over, the thread close the "first" window and generate a new one. I want to modify my thread in the following way: public static Thread counter = new Thread() { public void run() { for (int i=4; i>0; i=i-1) { if (!Thread.interrupted()) { updateGUI(i,label); } else { return; } try {Thread.sleep(1000);} catch(InterruptedException e) {}; } // The time for the partner selection is over. if (!Thread.interrupted()) { SwingUtilities.invokeLater(new Runnable() { public void run() { frame.remove(partnerSelectionPanel); frame.add(selectionFinishedPanel); frame.invalidate(); frame.validate(); } }); } else { return; } } };

    Read the article

  • Swing: what to do when a GUI update takes too long and freezes other GUI elements?

    - by java.is.for.desktop
    Hello, everyone! I know that GUI code in Java Swing must be put inside SwingUtilities.invokeAndWait or SwingUtilities.invokeLater. This way threading works fine. Sadly, in my situation, the GUI update it that thing which takes much longer than background thread(s). More specific: I update a JTree with about just 400 entries, nesting depth is maximum 4, so should be nothing scary, right? But it takes sometimes one second! I need to ensure that the user is able to type in a JTextPane without delays. Well, guess what, the slow JTree updates do cause delays for JTextPane during input. It refreshes only as soon as the tree gets updated. I am using Netbeans and know empirically that a Java app can update lots of information without freezing the rest of the UI. How can it be done? NOTE 1: All those DefaultMutableTreeNodes are prepared outside the invokeAndWait. NOTE 2: When I replace invokeAndWait with invokeLater the tree doesn't get updated.

    Read the article

  • How does the event dispatch thread work?

    - by Roman
    With the help of people on stackoverflow I was able to get the following working code of the simples GUI countdown (it just displays a window counting down seconds). My main problem with this code is the invokeLater stuff. As far as I understand the invokeLater send a task to the event dispatching thread (EDT) and then the EDT execute this task whenever it "can" (whatever it means). Is it right? To my understanding the code works like that: In the main method we use invokeLater to show the window (showGUI method). In other words, the code displaying the window will be executed in the EDT. In the main method we also start the counter and the counter (by construction) is executed in another thread (so it is not in the event dispatching thread). Right? The counter is executed in a separate thread and periodically it calls updateGUI. The updateGUI is supposed to update GUI. And GUI is working in the EDT. So, updateGUI should also be executed in the EDT. It is why the code for the updateGUI is inclosed in the invokeLater. Is it right? What is not clear to me is why we call the counter from the EDT. Anyway it is not executed in the EDT. It starts immediately a new thread and the counter is executed there. So, why we cannot call the counter in the main method after the invokeLater block? import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; public class CountdownNew { static JLabel label; // Method which defines the appearance of the window. public static void showGUI() { JFrame frame = new JFrame("Simple Countdown"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); label = new JLabel("Some Text"); frame.add(label); frame.pack(); frame.setVisible(true); } // Define a new thread in which the countdown is counting down. public static Thread counter = new Thread() { public void run() { for (int i=10; i>0; i=i-1) { updateGUI(i,label); try {Thread.sleep(1000);} catch(InterruptedException e) {}; } } }; // A method which updates GUI (sets a new value of JLabel). private static void updateGUI(final int i, final JLabel label) { SwingUtilities.invokeLater( new Runnable() { public void run() { label.setText("You have " + i + " seconds."); } } ); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { showGUI(); counter.start(); } }); } }

    Read the article

  • calling invokeAndWait from the EDT

    - by Aly
    Hi, I have a problem following from my previous problem. I also have the code SwingUtillities.invokeAndWait somewhere else in the code base, but when I remove this the gui does not refresh. If I dont remove it the error I get is: Exception in thread "AWT-EventQueue-0" java.lang.Error: Cannot call invokeAndWait from the event dispatcher thread at java.awt.EventQueue.invokeAndWait(Unknown Source) at javax.swing.SwingUtilities.invokeAndWait(Unknown Source) at game.player.humanplayer.model.HumanPlayer.act(HumanPlayer.java:69) The code in HumanPlayer.act is: public Action act(final Action[] availiableActions) { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { gui.update(availiableActions); } }); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } synchronized(performedAction){ while(!hasPerformedAction()){ try { performedAction.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } setPerformedAction(false); } return getActionPerfomed(); }

    Read the article

  • Swing: How do I run a job from AWT thread, but after a window was layed out?

    - by java.is.for.desktop
    My complete GUI runs inside the AWT thread, because I start the main window using SwingUtilities.invokeAndWait(...). Now I have a JDialog which has just to display a JLabel, which indicates that a certain job is in progress, and close that dialog after the job was finished. The problem is: the label is not displayed. That job seems to be started before JDialog was fully layed-out. When I just let the dialog open without waiting for a job and closing, the label is displayed. The last thing the dialog does in its ctor is setVisible(true). Things such as revalidate(), repaint(), ... don't help either. Even when I start a thread for the monitored job, and wait for it using someThread.join() it doesn't help, because the current thread (which is the AWT thread) is blocked by join, I guess. Replacing JDialog with JFrame doesn't help either. So, is the concept wrong in general? Or can I manage it to do certain job after it is ensured that a JDialog (or JFrame) is fully layed-out? Simplified algorithm of what I'm trying to achieve: Create a subclass of JDialog Ensure that it and its contents are fully layed-out Start a process and wait for it to finish (threaded or not, doesn't matter) Close the dialog I managed to write a reproducible test case: EDIT Problem from an answer is now addressed: This use case does display the label, but it fails to close after the "simulated process", because of dialog's modality. import java.awt.*; import javax.swing.*; public class _DialogTest2 { public static void main(String[] args) throws Exception { SwingUtilities.invokeAndWait(new Runnable() { final JLabel jLabel = new JLabel("Please wait..."); @Override public void run() { JFrame myFrame = new JFrame("Main frame"); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.setSize(750, 500); myFrame.setLocationRelativeTo(null); myFrame.setVisible(true); JDialog d = new JDialog(myFrame, "I'm waiting"); d.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); d.add(jLabel); d.setSize(300, 200); d.setLocationRelativeTo(null); d.setVisible(true); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { Thread.sleep(3000); // simulate process jLabel.setText("Done"); } catch (InterruptedException ex) { } } }); d.setVisible(false); d.dispose(); myFrame.setVisible(false); myFrame.dispose(); } }); } }

    Read the article

  • Swing invokeLater never shows up, invokeAndWait throws error. What can I do?

    - by Geo
    I have this code: try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { try { dialog.handleDownload(); } catch (IOException io) { io.printStackTrace(); } } }); } catch(Exception io) { io.printStackTrace(); } in the handleDownload I'm reading an inputstream, calculating a progress bar's value, and setting it to that. So, when I click a button, a new JFrame opens up and does all the stuff I wrote above. If I have the dialog.handleDownload by itself ( in no SwingUtilities method ), it freezes until the operation is finished. If I add it in a invokeLater it's closed very fast ( I can't see anything, and the operation is not finished ). If I add it in a invokeAndWait I get the invokeAndWait cannot be called from the event dispatcher thread error. What should I do?

    Read the article

  • Java/Swing: JTable.rowAtPoint doesn't work correctly for points outside the table?

    - by Jason S
    I have this code to get a row from a JTable that is generated by a DragEvent for a DropTarget in some component C which may or may not be the JTable: public int getRowFromDragEvent(DropTargetDragEvent event) { Point p = event.getLocation(); if (event.getSource() != this.table) { SwingUtilities.convertPointToScreen(p, event.getDropTargetContext().getComponent()); SwingUtilities.convertPointFromScreen(p, this.table); if (!this.table.contains(p)) { System.out.println("outside table, would be row "+this.table.rowAtPoint(p)); } } return this.table.rowAtPoint(p); } The System.out.println is just a hack right now. What I'm wondering, is why the System.out.println doesn't always print "row -1". When the table is empty it does, but if I drag something onto the table's header row, I get the println with "row 0". This seems like a bug... or am I not understanding how rowAtPoint() works?

    Read the article

  • How to unicode Myanmar texts on Java? [closed]

    - by Spacez Ly Wang
    I'm just beginner of Java. I'm trying to unicode (display) correctly Myanmar texts on Java GUI ( Swing/Awt ). I have four TrueType fonts which support Myanmar unicode texts. There are Myanmar3, Padauk, Tharlon, Myanmar Text ( Window 8 built-in ). You may need the fonts before the code. Google the fonts, please. Each of the fonts display on Java GUI differently and incorrectly. Here is the code for GUI Label displaying myanmar texts: ++++++++++++++++++++++++ package javaapplication1; import javax.swing.JFrame; import javax.swing.JTextField; public class CusFrom { private static void createAndShowGUI() { JFrame frame = new JFrame("Hello World Swing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); String s = "\u1015\u102F \u103C\u1015\u102F"; JLabel label = new JLabel(s); label.setFont(new java.awt.Font("Myanmar3", 0, 20));// font insert here, Myanmar Text, Padauk, Myanmar3, Tharlon frame.getContentPane().add(label); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } } ++++++++++++++++++++++++ Outputs vary. See the pictures: Myanmar3 IMG Padauk IMG Tharlon IMG Myanmar Text IMG What is the correct form? (on notepad) Well, next is the code for GUI Textfield inputting Myanmar texts: ++++++++++++++++++++++++ package javaapplication1; import javax.swing.JFrame; import javax.swing.JTextField; public class XusForm { private static void createAndShowGUI() { JFrame frame = new JFrame("Frame Title"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTextField textfield = new JTextField(); textfield.setFont(new java.awt.Font("Myanmar3", 0, 20)); frame.getContentPane().add(textfield); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } } ++++++++++++++++++++++++ Outputs vary when I input keys( unicode text ) on keyboards. Myanmar Text Output IMG Padauk Output IMG Myanmar3 Output IMG Tharlon Output IMG Those fonts work well on Linux when opening text files with Text Editor application. My Question is how to unicode Myanmar texts on Java GUI. Do I need additional codes left to display well? Or Does Java still have errors? The fonts display well on Web Application (HTML, CSS) but I'm not sure about displaying on Java Web Application.

    Read the article

  • Problems with X11GraphicsDevice on Suse 11

    - by Daniel
    Hi, On servers running Suse 11 I'm experiencing hangups in sun.awt.X11GraphicsDevice.getDoubleBufferVisuals(Native Method) when connecting via Citrix (and setting DISPLAY to localhost:11.0). Running exactly the same code in exactly the same environment, excepth through Exceed (with DISPLAY set to my workstation's IP) it runs like clockwork. The error is not intermittent, it happens every time Reinstalling the OS does not help Can not reproduce it on Suse 10 This is what the main thread stack looks like: [junit] "main" prio=10 tid=0x0000000040112000 nid=0x6acc runnable [0x00002b9f909ae000] [junit] java.lang.Thread.State: RUNNABLE [junit] at sun.awt.X11GraphicsDevice.getDoubleBufferVisuals(Native Method) [junit] at sun.awt.X11GraphicsDevice.makeDefaultConfiguration(X11GraphicsDevice.java:208) [junit] at sun.awt.X11GraphicsDevice.getDefaultConfiguration(X11GraphicsDevice.java:182) [junit] - locked <0x00002b9fed6b8e70 (a java.lang.Object) [junit] at sun.awt.X11.XToolkit.(XToolkit.java:92) [junit] at java.lang.Class.forName0(Native Method) [junit] at java.lang.Class.forName(Class.java:169) [junit] at java.awt.Toolkit$2.run(Toolkit.java:834) [junit] at java.security.AccessController.doPrivileged(Native Method) [junit] at java.awt.Toolkit.getDefaultToolkit(Toolkit.java:826) [junit] - locked <0x00002b9f94b8ada0 (a java.lang.Class for java.awt.Toolkit) [junit] at java.awt.Toolkit.getEventQueue(Toolkit.java:1676) [junit] at java.awt.EventQueue.invokeLater(EventQueue.java:954) [junit] at javax.swing.SwingUtilities.invokeLater(SwingUtilities.java:1264) ... Has anyone experienced something similar? Could this be a problem in Suse 11's display handling? I'm thankful for any input at this point - I'm fresh out of ideas :)

    Read the article

  • Error when creating JFrame from JFrame

    - by Aly
    Hi, I have an application that is works fine and the JFrame for it is launched in the constructor of a GameInitializer class which takes in some config parameters. I have tried to create a GUI in which allows the user to specify these config parameters and then click submit. When the user clicks submit a new GameInitializer object is created. The error I am getting is: Exception in thread "AWT-EventQueue-0" java.lang.Error: Cannot call invokeAndWait from the event dispatcher thread at java.awt.EventQueue.invokeAndWait(Unknown Source) at javax.swing.SwingUtilities.invokeAndWait(Unknown Source) at game.player.humanplayer.view.HumanView.update(HumanView.java:43) once submit is called this code is executed: values assigned to parames... new GameInitializer(userName, player, Constants.BLIND_STRUCTURE_FILES.get(blindStructure), handState); Then code in the GameInitializer constructor is: public GameInitializer(String playerName, AbstractPlayer opponent, String blindStructureConfig, AbstractHandState handState){ beginGame(playerName, opponent, blindStructureConfig, handState); } public static void beginGame(String playerName, AbstractPlayer opponent, String blindStructureConfig, AbstractHandState handState){ AbstractDealer dealer; BlindStructure.initialize(blindStructureConfig); AbstractPlayer humanPlayer = new HumanPlayer(playerName, handState); AbstractPlayer[] players = new AbstractPlayer[2]; players[0] = humanPlayer; players[1] = opponent; handState.setTableLayout(players); for(AbstractPlayer player : players){ player.initialize(); } dealer = new Dealer(players, handState); dealer.beginGame(); } It basically cascades down and eventually calls this piece of code in the HumanView class: public void update(final Event event, final ReadableHandState handState, final AbstractPlayer player) { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { gamePanel.update(event, handState, player); validate(); } }); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } if(event.equals(Event.HAND_ENDING)){ try { if(handState.wonByShowdown() || handState.isSplitPot()){ Thread.sleep(3500); } else{ Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } } } Do you have any idea why?

    Read the article

  • JDK-7 SwingWorker deadlocks?

    - by kd304
    I have a small image processing application which does multiple things at once using SwingWorker. However, if I run the following code (oversimplified excerpt), it just hangs on JDK 7 b70 (windows) but works in 6u16. It starts a new worker within another worker and waits for its result (the real app runs multiple sub-workers and waits for all this way). Did I use some wrong patterns here (as mostly there is 3-5 workers in the swingworker-pool, which has limit of 10 I think)? import javax.swing.SwingUtilities; import javax.swing.SwingWorker; public class Swing { static SwingWorker<String, Void> getWorker2() { return new SwingWorker<String, Void>() { @Override protected String doInBackground() throws Exception { return "Hello World"; } }; } static void runWorker() { SwingWorker<String, Void> worker = new SwingWorker<String, Void>() { @Override protected String doInBackground() throws Exception { SwingWorker<String, Void> sw2 = getWorker2(); sw2.execute(); return sw2.get(); } }; worker.execute(); try { System.out.println(worker.get()); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { runWorker(); } }); } }

    Read the article

  • Why I cannot add a JPanel to JFrame?

    - by Roman
    Here is the code: import javax.swing.SwingUtilities; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JLabel; import java.awt.event.*; import java.awt.*; public class GameWindow { private String[] players; private JFrame frame; // Constructor. public GameWindow(String[] players) { this.players = players; } // Start the window in the EDT. public void start() { SwingUtilities.invokeLater(new Runnable() { public void run() { showWindow(); controller.start(); } }); } // Defines the general properties of and starts the window. public void showWindow() { frame = new JFrame("Game"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(600,400); frame.setVisible(true); } // The thread controlling changes of panels in the main window. private Thread controller = new Thread() { public void run() { frame.add(generatePartnerSelectionPanel()); frame.invalidate(); frame.validate(); } }; // Generate the panel for the selection of a partner. private JPanel generatePartnerSelectionPanel() { JPanel panel = new JPanel(); panel.add(new JLabel("Pleas select a partner:")); return panel; } } I should see "Pleas select the partner" and I don't. Why? I suppose that it's because I do not see frame from the run method of the Thread.

    Read the article

  • Java Swing Threading with Updatable JProgressBar

    - by Anthony Sparks
    First off I've been working with Java's Concurency package quite a bit lately but I have found an issue that I am stuck on. I want to have and Application and the Application can have a SplashScreen with a status bar and the loading of other data. So I decided to use SwingUtilities.invokeAndWait( call the splash component here ). The SplashScreen then appears with a JProgressBar and runs a group of threads. But I can't seem to get a good handle on things. I've looked over SwingWorker and tried using it for this purpose but the thread just returns. Here is a bit of sudo-code. and the points I'm trying to achieve. Have an Application that has a SplashScreen that pauses while loading info Be able to run multiple threads under the SplashScreen Have the progress bar of the SplashScreen Update-able yet not exit until all threads are done. Launching splash screen try { SwingUtilities.invokeAndWait( SplashScreen ); } catch (InterruptedException e) { } catch (InvocationTargetException e) { } Splash screen construction SplashScreen extends JFrame implements Runnable{ public void run() { //run threads //while updating status bar } } I have tried many things including SwingWorkers, Threads using CountDownLatch's, and others. The CountDownLatch's actually worked in the manner I wanted to do the processing but I was unable to update the GUI. When using the SwingWorkers either the invokeAndWait was basically nullified (which is their purpose) or it wouldn't update the GUI still even when using a PropertyChangedListener. If someone else has a couple ideas it would be great to hear them. Thanks in advance.

    Read the article

  • Swing: what to do when a JTree update takes too long and freezes other GUI elements?

    - by java.is.for.desktop
    Hello, everyone! I know that GUI code in Java Swing must be put inside SwingUtilities.invokeAndWait or SwingUtilities.invokeLater. This way threading works fine. Sadly, in my situation, the GUI update it that thing which takes much longer than background thread(s). More specific: I update a JTree with about just 400 entries, nesting depth is maximum 4, so should be nothing scary, right? But it takes sometimes one second! I need to ensure that the user is able to type in a JTextPane without delays. Well, guess what, the slow JTree updates do cause delays for JTextPane during input. It refreshes only as soon as the tree gets updated. I am using Netbeans and know empirically that a Java app can update lots of information without freezing the rest of the UI. How can it be done? NOTE 1: All those DefaultMutableTreeNodes are prepared outside the invokeAndWait. NOTE 2: When I replace invokeAndWait with invokeLater the tree doesn't get updated. NOTE 3: Fond out that recursive tree expansion takes far the most time. NOTE 4: I'm using custom tree cell renderer, will try without and report. NOTE 4a: My tree cell renderer uses a map to cache and reuse created JTextComponents, depending on tree node (as a key). CLUE 1: Wow! Without setting custom cell renderer it's 10 times faster. I think, I'll need few good tutorials on writing custom tree cell renderers.

    Read the article

  • Why is my GUI unresponsive while a SwingWorker thread runs?

    - by Starchy
    Hello, I have a SwingWorker thread with an IOBound task which is totally locking up the interface while it runs. Swapping out the normal workload for a counter loop has the same result. The SwingWorker looks basically like this: public class BackupWorker extends SwingWorker<String, String> { private static String uname = null; private static String pass = null; private static String filename = null; static String status = null; BackupWorker (String uname, String pass, String filename) { this.uname = uname; this.pass = pass; this.filename = filename; } @Override protected String doInBackground() throws Exception { BackupObject bak = newBackupObject(uname,pass,filename); return "Done!"; } } The code that kicks it off lives in a class that extends JFrame: public void actionPerformed(ActionEvent event) { String cmd = event.getActionCommand(); if (BACKUP.equals(cmd)) { SwingUtilities.invokeLater(new Runnable() { public void run() { final StatusFrame statusFrame = new StatusFrame(); statusFrame.setVisible(true); SwingUtilities.invokeLater(new Runnable() { public void run () { statusFrame.beginBackup(uname,pass,filename); } }); } }); } } Here's the interesting part of StatusFrame: public void beginBackup(final String uname, final String pass, final String filename) { worker = new BackupWorker(uname, pass, filename); worker.execute(); try { System.out.println(worker.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } So far as I can see, everything "long-running" is handled by the worker, and everything that touches the GUI on the EDT. Have I tangled things up somewhere, or am I expecting too much of SwingWorker?

    Read the article

  • Why my object sees variables which were not given to it in the constructor?

    - by Roman
    I have the following code. Which is "correct" and which I do not understand: private static void updateGUI(final int i, final JLabel label) { SwingUtilities.invokeLater( new Runnable() { public void run() { label.setText("You have " + i + " seconds."); } } ); } I create a new instance of the Runnable class and then in the run method of this instance I use variables label and i. It works, but I do not understand why it work. Why the considered object sees values of these variables. According to my understanding the code should look like that (and its wrong): private static void updateGUI(final int i, final JLabel label) { SwingUtilities.invokeLater(new Runnable(i,label) { public Runnable(int i, JLabel label) { this.i = i; this.label = label; } public void run() { label.setText("You have " + i + " seconds."); } }); } So, I would give the i and label variables to the constructor so the object can access them... By the way, in the updateGUI I use final before the i and label. I think I used final because compiler wanted that. But I do not understand why.

    Read the article

1 2 3  | Next Page >