Java Code Examples for javax.swing.SwingUtilities

The following are top voted examples for showing how to use javax.swing.SwingUtilities. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: SetShapeTest.java   Source Code and License 27 votes vote down vote up
public static void main(String[] args) throws Exception {
    createUI();
    Robot robot = new Robot();
    robot.waitForIdle();
    Rectangle rect = window.getBounds();
    rect.x += rect.width - 10;
    rect.y += rect.height - 10;
    robot.delay(1000);
    Color c = robot.getPixelColor(rect.x, rect.y);
    try {
        if (!c.equals(Color.RED)) {
            throw new RuntimeException("Test Failed");
        }
    } finally {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                background.dispose();
                window.dispose();
            }
        });
    }
}
 
Example 2
Project: incubator-netbeans   File: BaseActionProviderTest.java   Source Code and License 7 votes vote down vote up
@Test
public void testOverridenGetTargetNames() throws Exception {
    assertNotNull(ap);
    final Logger log = Logger.getLogger(ActionProviderSupport.class.getName());
    final Level origLevel = log.getLevel();
    final MockHandler handler = new MockHandler();
    log.setLevel(Level.FINE);
    log.addHandler(handler);
    try {
        SwingUtilities.invokeAndWait(() -> {
            ap.invokeAction(ActionProvider.COMMAND_CLEAN, Lookup.EMPTY);
        });
        assertEquals("1", handler.props.get("a"));      //NOI18N
        assertEquals("2", handler.props.get("b"));      //NOI18N
    } finally {
        log.setLevel(origLevel);
        log.removeHandler(handler);
    }
}
 
Example 3
Project: incubator-netbeans   File: ShortcutAndMenuKeyEventProcessor.java   Source Code and License 7 votes vote down vote up
public boolean postProcessKeyEvent(KeyEvent ev) {
    if (ev.isConsumed())
        return false;

    if (processShortcut(ev))
        return true;

    Window w = SwingUtilities.windowForComponent(ev.getComponent());        
    if (w instanceof Dialog && !WindowManagerImpl.isSeparateWindow(w))
        return false;
    
    JFrame mw = (JFrame)WindowManagerImpl.getInstance().getMainWindow();
    if (w == mw) {
        return false;
    }

    JMenuBar mb = mw.getJMenuBar();
    if (mb == null)
        return false;
    boolean pressed = (ev.getID() == KeyEvent.KEY_PRESSED);        
    boolean res = invokeProcessKeyBindingsForAllComponents(ev, mw, pressed);
    
    if (res)
        ev.consume();
    return res;
}
 
Example 4
Project: incubator-netbeans   File: MacrosPanel.java   Source Code and License 6 votes vote down vote up
private void tMacrosTableChanged(final TableModelEvent evt) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            if (evt.getType() == TableModelEvent.INSERT) {
                tMacros.getSelectionModel().setSelectionInterval(evt.getFirstRow(), evt.getFirstRow());
            } else if (evt.getType() == TableModelEvent.DELETE) {
                // try the next row after the deleted one
                int tableRow = evt.getLastRow();
                if (tableRow < tMacros.getModel().getRowCount()) {
                    tMacros.getSelectionModel().setSelectionInterval(tableRow, tableRow);
                } else {
                    // try the previous row
                    tableRow = evt.getFirstRow() - 1;
                    if (tableRow >= 0) {
                        tMacros.getSelectionModel().setSelectionInterval(tableRow, tableRow);
                    } else {
                        tMacros.getSelectionModel().clearSelection();
                    }
                }
            }
        }
    });
}
 
Example 5
Project: incubator-netbeans   File: HgProjectUtils.java   Source Code and License 6 votes vote down vote up
public static void selectAndExpandProject( final Project p ) {
    if( p == null) return;
    
    // invoke later to select the being opened project if the focus is outside ProjectTab
    SwingUtilities.invokeLater(new Runnable() {
        
        final ExplorerManager.Provider ptLogial = findDefault(ProjectTab_ID_LOGICAL);
        
        public void run() {
            Node root = ptLogial.getExplorerManager().getRootContext();
            // Node projNode = root.getChildren ().findChild( p.getProjectDirectory().getName () );
            Node projNode = root.getChildren().findChild( ProjectUtils.getInformation( p ).getName() );
            if ( projNode != null ) {
                try {
                    ptLogial.getExplorerManager().setSelectedNodes( new Node[] { projNode } );
                } catch (Exception ignore) {
                    // may ignore it
                }
            }
        }
    });
}
 
Example 6
Project: openjdk-jdk10   File: WaitForIdleSyncroizedOnString.java   Source Code and License 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    CountDownLatch go = new CountDownLatch(1);
    Robot r = new Robot();
    SwingUtilities.invokeLater(() -> System.out.println("some work"));
    Thread t = new Thread(() -> {
        synchronized (WAIT_LOCK) {
            go.countDown();
            try {
                Thread.sleep(30000);
                passed = false;
            } catch (InterruptedException e) {
                System.out.println("e = " + e);
            }
        }
    });
    t.start();
    go.await();
    r.waitForIdle();
    t.interrupt();
    if (!passed) {
        throw new RuntimeException("Test failed");
    }
}
 
Example 7
Project: incubator-netbeans   File: ClassMethodSelector.java   Source Code and License 6 votes vote down vote up
void init() {
    isInitialized = true;
    
    fileListModel.clear();
    fileList.setEnabled(!isInitialized);
    
    if (isInitialized) {
        PROCESSOR.post(new Runnable() {
            public void run() {
                SessionStorage _storage = getStorage();
                final Collection<FileObject> files = getFiles(_storage);
                
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        fileList.setEnabled(true);
                        for (FileObject fo : files) fileListModel.addElement(fo);
                    }
                });
            }
        });
    }
}
 
Example 8
Project: incubator-netbeans   File: WizardStepProgressSupport.java   Source Code and License 6 votes vote down vote up
public void startProgress() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            ProgressHandle progress = getProgressHandle(); // NOI18N
            JComponent bar = ProgressHandleFactory.createProgressComponent(progress);
            stopButton = new JButton(org.openide.util.NbBundle.getMessage(RepositoryStep.class, "BK2022")); // NOI18N
            stopButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    cancel();
                }
            });
            progressComponent = new JPanel();
            progressComponent.setLayout(new BorderLayout(6, 0));
            progressLabel = new JLabel();
            progressLabel.setText(getDisplayName());
            progressComponent.add(progressLabel, BorderLayout.NORTH);
            progressComponent.add(bar, BorderLayout.CENTER);
            progressComponent.add(stopButton, BorderLayout.LINE_END);
            WizardStepProgressSupport.super.startProgress();
            panel.setVisible(true);
            panel.add(progressComponent);
            panel.revalidate();
        }
    });                                                
}
 
Example 9
Project: openjdk-jdk10   File: TestJInternalFrameDispose.java   Source Code and License 6 votes vote down vote up
private static void executeTest() throws Exception {

        Point point = Util.getCenterPoint(menu);
        performMouseOperations(point);
        point = Util.getCenterPoint(menuItem);
        performMouseOperations(point);
        point = Util.getCenterPoint(menu);
        performMouseOperations(point);
        point = Util.getCenterPoint(menuItem);
        performMouseOperations(point);
        SwingUtilities.invokeAndWait(new Runnable() {

            @Override
            public void run() {
                internalFrame = desktopPane.getSelectedFrame();
                internalFrame.doDefaultCloseAction();
                internalFrame = desktopPane.getSelectedFrame();
            }
        });

        robot.delay(2000);
        if (internalFrame == null) {
            dispose();
            throw new RuntimeException("Test Failed");
        }
    }
 
Example 10
Project: openjdk-jdk10   File: SynthScrollbarThumbPainterTest.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Create Robot
    testRobot = new Robot();

    // Create test UI
    String lookAndFeelString = "javax.swing.plaf.nimbus.NimbusLookAndFeel";
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            try {
                constructTestUI(lookAndFeelString);
            } catch (Exception ex) {
                throw new RuntimeException("Exception creating test UI");
            }
        }
    });

    testRobot.waitForIdle();
    testRobot.delay(200);

    // Run test method
    testScrollBarThumbPainter();

    // Dispose test UI
    disposeTestUI();
}
 
Example 11
Project: openjdk-jdk10   File: TestDisabledToolTipBorder.java   Source Code and License 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);

    test = new TestUI(latch);
    SwingUtilities.invokeAndWait(() -> {
        try {
            test.createUI();
        } catch (Exception ex) {
            throw new RuntimeException("Exception while creating UI");
        }
    });

    boolean status = latch.await(2, TimeUnit.MINUTES);
    if (!status) {
        System.out.println("Test timed out.");
    }

    if (test.testResult == false) {
        disposeUI();
        throw new RuntimeException("Test Failed.");
    }
}
 
Example 12
Project: geomapapp   File: WWMap.java   Source Code and License 6 votes vote down vote up
public void doZoom(Point2D p, double factor) {
	LatLon dest = new LatLon(Angle.fromDegrees(p.getY()), Angle.fromDegrees(p.getX()));
	double wwzoom = 2785 * Math.pow(factor, -.8311) * 10000;

	final OrbitView view = (OrbitView) wwd.getView();

	FlyToOrbitViewAnimator fto = 
		FlyToOrbitViewAnimator.createFlyToOrbitViewAnimator(
			view,
			view.getCenterPosition(), new Position(dest, 0),
			view.getHeading(), Angle.fromDegrees(0),
			view.getPitch(), Angle.fromDegrees(0),
			view.getZoom(), wwzoom,
			5000, WorldWind.CONSTANT); //was true

	view.addAnimator(fto);

	SwingUtilities.invokeLater(new Runnable() {
		public void run() {
			((MapApp)getApp()).getFrame().toFront();
			view.firePropertyChange(AVKey.VIEW,  null, view);
		}
	});
}
 
Example 13
Project: marathonv5   File: SwingInterop.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        public void run() {
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
            } catch (Exception e) {}
            
            JFrame frame = new JFrame("JavaFX 2.0 in Swing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            JApplet applet = new SwingInterop();
            applet.init();

            frame.setContentPane(applet.getContentPane());

            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);

            applet.start();
        }
    });
}
 
Example 14
Project: jaer   File: SimpleIPotSliderTextControl.java   Source Code and License 6 votes vote down vote up
/** called when Observable changes (pot changes) */
@Override
public void update(final Observable observable, final Object obj) {
	if (observable instanceof IPot) {
		// log.info("observable="+observable);
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				// don't do the following - it sometimes prevents display updates or results in double updates
				// slider.setValueIsAdjusting(true); // try to prevent a new event from the slider
				updateAppearance();
			}
		});
	}
}
 
Example 15
Project: VISNode   File: InputEditor.java   Source Code and License 6 votes vote down vote up
/**
 * Builds the specific fields for the selected input method
 */
private synchronized void buildSpecificFields() {
    SwingUtilities.invokeLater(() -> {
        if (findId("editor") != null) {
            remove((java.awt.Component) findId("editor"));
        }
        Component editor = null;
        if (input == null) {
            editor = Panels.create();
        } else {
            if (input instanceof MultiFileInput) {
                editor = buildMultiFile();
            }
            if (input instanceof WebcamInput) {
                editor = Panels.create();
            }
        }
        put(editor.id("editor"));
        revalidate();
    });
}
 
Example 16
Project: gate-core   File: MainFrame.java   Source Code and License 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
  Runnable runner = new Runnable() {
    @Override
    public void run() {
      TreePath[] paths = resourcesTree.getSelectionPaths();
      for(TreePath path : paths) {
        final Object value = ((DefaultMutableTreeNode)
          path.getLastPathComponent()).getUserObject();
        if(value instanceof Handle) {
          SwingUtilities.invokeLater(new Runnable() { @Override
          public void run() {
            new CloseViewAction((Handle)value).actionPerformed(null);
          }});
        }
      }
    }
  };
  Thread thread = new Thread(runner,
    "CloseViewsForSelectedResourcesAction");
  thread.setPriority(Thread.MIN_PRIORITY);
  thread.start();
}
 
Example 17
Project: etomica   File: ControllerSpeciesSelection.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args){
	
	SwingUtilities.invokeLater(new Runnable() {
		public void run() {
			ModelSpeciesSelection modelSpeciesSelection = new ModelSpeciesSelection();
			ModelSelectedSpecies modelSelectedSpecies = new ModelSelectedSpecies();
			ViewSpeciesSelection s = new ViewSpeciesSelection(modelSpeciesSelection,modelSelectedSpecies);
			ControllerSpeciesSelection sa = new ControllerSpeciesSelection(s,modelSpeciesSelection,modelSelectedSpecies);
			JFrame frame = new JFrame();
			frame.add(s);
			frame.setVisible(true);
			frame.setResizable(true);
			frame.setMinimumSize(new Dimension(750,700));
			frame.setBounds(0, 0,750, 700);
			
		}
	});
	


}
 
Example 18
Project: jdk8u-jdk   File: Test4177735.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    JColorChooser chooser = new JColorChooser();
    AbstractColorChooserPanel[] panels = chooser.getChooserPanels();
    chooser.setChooserPanels(new AbstractColorChooserPanel[] { panels[1] });

    JDialog dialog = show(chooser);
    pause(DELAY);

    dialog.dispose();
    pause(DELAY);

    Test4177735 test = new Test4177735();
    SwingUtilities.invokeAndWait(test);
    if (test.count != 0) {
        throw new Error("JColorChooser leaves " + test.count + " threads running");
    }
}
 
Example 19
Project: MaxSim   File: ServerPanel.java   Source Code and License 6 votes vote down vote up
private void updateServer() {
    int curPort = Integer.parseInt(Settings.get().get(Settings.PORT, Settings.PORT_DEFAULT));
    if (curPort != port) {
        port = curPort;
        if (server != null) {
            server.shutdown();
        }
        server = Server.start(callback, port);
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                updateLabel();
            }
        });
    }
}
 
Example 20
Project: incubator-netbeans   File: TemplatesPanel.java   Source Code and License 6 votes vote down vote up
public void select(String path) {
    Node nodeToSelect = getTemplateNode(path);
    if (nodeToSelect != null) {
        try {
            manager.setSelectedNodes (new Node[]{ nodeToSelect });
            view.expandNode(nodeToSelect);
        } catch (PropertyVetoException ex) {
            Logger.getLogger(TemplatesPanel.class.getName()).log(Level.FINE, ex.getLocalizedMessage (), ex);
        }
    }
    SwingUtilities.invokeLater (new Runnable () {
        @Override public void run() {
            view.requestFocus ();
        }
    });
}
 
Example 21
Project: ramus   File: Area.java   Source Code and License 6 votes vote down vote up
public int addTabFrame(TabFrame tabFrame) {
    addTab(tabFrame.getTitleText(), tabFrame);
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            revalidate();
            repaint();
            int c = getTabCount();
            setSelectedIndex(c - 1);

        }
    });
    int i = getTabCount() - 1;
    setTabComponentAt(i, new ButtonTabComponent(this, menu));
    closeOthers.setEnabled(getTabCount() > 1);
    return i;
}
 
Example 22
Project: incubator-netbeans   File: AddWebServiceDlg.java   Source Code and License 6 votes vote down vote up
private void checkServicesModel() {
    if (SaasServicesModel.getInstance().getState() != State.READY) {
        setErrorMessage(NbBundle.getMessage(AddWebServiceDlg.class, "INIT_WEB_SERVICES_MANAGER"));
        disableAllControls();
        RequestProcessor.getDefault().post(new Runnable() {
            @Override
            public void run() {
                SaasServicesModel.getInstance().initRootGroup();
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        enableAllControls();
                        enableControls();
                        checkValues();
                    }
                });
            }
        });
    }
}
 
Example 23
Project: marathonv5   File: JFileChooserJavaElementTest.java   Source Code and License 6 votes vote down vote up
@BeforeMethod public void showDialog() throws Throwable {
    JavaElementFactory.add(JFileChooser.class, JFileChooserJavaElement.class);
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override public void run() {
            frame = new JFrame(JFileChooserJavaElementTest.class.getSimpleName());
            frame.setName("frame-" + JFileChooserJavaElementTest.class.getSimpleName());
            frame.getContentPane().add(new FileChooserDemo(), BorderLayout.CENTER);
            frame.pack();
            frame.setVisible(true);
            frame.setAlwaysOnTop(true);
            File file = new File(System.getProperty("java.home"));
            System.setProperty("marathon.project.dir", file.getPath());
        }
    });
    driver = new JavaAgent();
}
 
Example 24
Project: openjdk-jdk10   File: CloseOnMouseClickPropertyTest.java   Source Code and License 6 votes vote down vote up
private static Point getClickPoint(boolean parent) throws Exception {
    Point points[] = new Point[1];

    SwingUtilities.invokeAndWait(() -> {

        JComponent comp = parent ? menu : menu.getItem(0);

        Point point = comp.getLocationOnScreen();
        Rectangle bounds = comp.getBounds();
        point.x += bounds.getWidth() / 2;
        point.y += bounds.getHeight() / 2;

        points[0] = point;
    });

    return points[0];
}
 
Example 25
Project: marathonv5   File: TumbleItem.java   Source Code and License 6 votes vote down vote up
public void init() {
    loadAppletParameters();

    // Execute a job on the event-dispatching thread:
    // creating this applet's GUI.
    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                createGUI();
            }
        });
    } catch (Exception e) {
        System.err.println("createGUI didn't successfully complete");
    }

    // Set up timer to drive animation events.
    timer = new Timer(speed, this);
    timer.setInitialDelay(pause);
    timer.start();

    // Start loading the images in the background.
    worker.execute();
}
 
Example 26
Project: gate-core   File: DocumentExportMenu.java   Source Code and License 6 votes vote down vote up
@Override
public void resourceUnloaded(CreoleEvent e) {
  final Resource res = e.getResource();

  if(res instanceof DocumentExporter) {
    SwingUtilities.invokeLater(new Runnable() {
      
      @Override
      public void run() {
        // TODO Auto-generated method stub
        JMenuItem item = itemByResource.get(res);

        if(item != null) {
          remove(item);
          itemByResource.remove(res);
        }
        
        if(getItemCount() == 2) {
          remove(1);
        }
      }
    });     
  }    
}
 
Example 27
Project: incubator-netbeans   File: PropertiesFlushTest.java   Source Code and License 6 votes vote down vote up
public void testNullChangePerformedAndReflectedInPropertySheet() throws Exception {
    System.err.println(".testNullChangePerformedAndReflectedInPropertySheet");
    int count = ps.table.getRowCount();
    assertTrue("Property sheet should contain three rows ", count==3);
    L l = new L();
    tn.addPropertyChangeListener(l);
    
    SwingUtilities.invokeAndWait(new Runnable() {
        public void run() {
            tn.replaceProps();
        }
    });
    Thread.sleep(500);
    //        SwingUtilities.invokeAndWait (new Runnable(){public void run() {System.currentTimeMillis();}});
    
    l.assertEventReceived();
    
    assertTrue("Should only be one property", tn.getPropertySets()[0].getProperties().length == 1);
    sleep();
    ensurePainted(ps);
    int rc = ps.table.getRowCount();
    assertTrue("Property sheet should now only show 2 rows, not " + rc, rc == 2);
}
 
Example 28
Project: openjdk-jdk10   File: MetalHiDPISliderThumbTest.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        SwingUtilities.invokeAndWait(() -> {

            try {
                UIManager.setLookAndFeel(new MetalLookAndFeel());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            if (!testSliderThumb(true)) {
                throw new RuntimeException("Horizontal Slider Thumb is not scaled!");
            }

            if (!testSliderThumb(false)) {
                throw new RuntimeException("Vertical Slider Thumb is not scaled!");
            }
        });
    }
 
Example 29
Project: incubator-netbeans   File: BuildOptionsPanel.java   Source Code and License 6 votes vote down vote up
@Override
public void run() {
    if (SwingUtilities.isEventDispatchThread()) {
        Map<String, String> userDefinedBuildArgs = component.getBuildArgs();
        // Submit changes iff user haven't start filling arguments table yet.
        if (userDefinedBuildArgs == null || userDefinedBuildArgs.isEmpty()) {
            Map<String, String> filtered = filterMacros(dockerfileDetail.getBuildArgs());
            component.setBuildArgs(filtered);
            wizard.putProperty(BuildImageWizard.BUILD_ARGUMENTS_PROPERTY, filtered);
        }
    } else {
        try {
            // null is OK
            DockerInstance instance = (DockerInstance) wizard.getProperty(BuildImageWizard.INSTANCE_PROPERTY);
            dockerfileDetail = new DockerAction(instance).getDetail(fo);
            SwingUtilities.invokeLater(this);
        } catch (IOException ex) {
            Logger.getLogger(BuildOptionsPanel.class.getName()).log(Level.INFO, "Can't parse dockerfile: {0}", ex.toString());
        }
    }
}
 
Example 30
Project: Logisim   File: SplashScreen.java   Source Code and License 6 votes vote down vote up
public void setProgress(int markerId) {
	final Marker marker = markers == null ? null : markers[markerId];
	if (marker != null) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				progress.setString(marker.message);
				progress.setValue(marker.count);
			}
		});
		if (PRINT_TIMES) {
			System.err.println((System.currentTimeMillis() - startTime) // OK
					+ " " + marker.message);
		}
	} else {
		if (PRINT_TIMES) {
			System.err.println((System.currentTimeMillis() - startTime) + " ??"); // OK
		}
	}
}
 
Example 31
Project: incubator-netbeans   File: SwingBrowserTest.java   Source Code and License 6 votes vote down vote up
public @Override int getResponseCode() throws IOException {
            System.out.println("connecting "+toString()+" ... isEDT = "+SwingUtilities.isEventDispatchThread());
//            Thread.dumpStack();
            if (sIn != null) {
                try {
                    sIn.acquire();
                    if (sOut != null) {
                        sOut.release();
                    }
                    System.out.println("aquired in lock, released out "+toString());
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                    fail(ex.getMessage());
                }
                sIn.release();
            }
            System.out.println("... connected "+toString());
            
            return super.getResponseCode();
        }
 
Example 32
Project: JWT4B   File: JWTInterceptTab.java   Source Code and License 6 votes vote down vote up
public void updateSetView(final boolean reset) {
	SwingUtilities.invokeLater(new Runnable() {
		public void run() {
			if(!jwtArea.getText().equals(jwtIM.getJWTJSON())){
				jwtArea.setText(jwtIM.getJWTJSON());
			}
			keyField.setText(jwtIM.getJWTKey());
			if(reset){
				rdbtnDontModifySignature.setSelected(true);
				keyField.setText("");
				keyField.setEnabled(false);
			}
			jwtArea.setCaretPosition(0);
			lblProblem.setText(jwtIM.getProblemDetail());
			
			if(jwtIM.getcFW().isCookie()){
				lblCookieFlags.setText(jwtIM.getcFW().toHTMLString());
			}else{
				lblCookieFlags.setText("");
			}
			lbRegisteredClaims.setText(jwtIM.getTimeClaimsAsText());
		}
	});
}
 
Example 33
Project: openjdk-jdk10   File: JButtonPaintNPE.java   Source Code and License 6 votes vote down vote up
public static void main(final String[] args)
        throws InvocationTargetException, InterruptedException {
    SwingUtilities.invokeAndWait(() -> {
        frame = new JFrame();
        frame.add(new JButton() {
            @Override
            protected void paintComponent(final Graphics g) {
                Graphics gg = new BufferedImage(getWidth(), getHeight(),
                              BufferedImage.TYPE_INT_ARGB).createGraphics();
                super.paintComponent(gg);
                gg.dispose();
            }
        });
        frame.setSize(300, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    });
    sleep();
    SwingUtilities.invokeAndWait(() -> {
        if (frame != null) {
            frame.dispose();
        }
    });
}
 
Example 34
Project: s-store   File: CatalogViewer.java   Source Code and License 6 votes vote down vote up
/**
     * @param args
     */
    public static void main(final String[] vargs) throws Exception {
        final ArgumentsParser args = ArgumentsParser.load(vargs);
        args.require(ArgumentsParser.PARAM_CATALOG);
        
//        Procedure catalog_proc = args.catalog_db.getProcedures().get("slev");
//        Statement catalog_stmt = catalog_proc.getStatements().get("GetStockCount");
//        String jsonString = Encoder.hexDecodeToString(catalog_stmt.getMs_fullplan());
//        JSONObject jsonObject = new JSONObject(jsonString);
//        System.err.println(jsonObject.toString(2));
        
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                CatalogViewer viewer = new CatalogViewer(args);
                viewer.setVisible(true);
            } // RUN
         });
    }
 
Example 35
Project: incubator-netbeans   File: WhereUsedPanelPackage.java   Source Code and License 6 votes vote down vote up
@Override
void initialize(final Element element, CompilationController info) {
    final String labelText = UIUtilities.createHeader((PackageElement) element, info.getElements().isDeprecated(element), false, false, true);
    final Icon labelIcon = ElementIcons.getElementIcon(element.getKind(), element.getModifiers());
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            Dimension preferredSize = label.getPreferredSize();
            label.setText(labelText);
            label.setIcon(labelIcon);
            label.setPreferredSize(preferredSize);
            label.setMinimumSize(preferredSize);
        }
    });
}
 
Example 36
Project: automatic-variants   File: WizSetTool.java   Source Code and License 6 votes vote down vote up
void displaySwitch(final int stage) {
SwingUtilities.invokeLater(new Runnable() {

    public void run() {
	if (stage == 0) {
	    setQuestionText("Analyze textures to narrow down profile options.");
	}
	if (stage == 2) {
	    setQuestionText("Pick profiles that makes sense for your variant.");
	}
	textures.setVisible(stage == 0);
	analyze.setVisible(stage == 0);
	progress.setVisible(stage == 1);
	progressLabel.setVisible(stage == 1);
	targetProfiles.setVisible(stage == 2);
	potentialProfiles.setVisible(stage == 2);
	exception.setVisible(stage == 3);
	partialMatch.setVisible(stage == 2);
    }
});
   }
 
Example 37
Project: Equella   File: ImportPage.java   Source Code and License 6 votes vote down vote up
private List<ItemDef> getCollections()
{
	try
	{
		final List<ItemDef> collections = data.getSoapSession().getContributableCollections();
		final List<ItemDef> filteredCollections = new ArrayList<ItemDef>();

		for( ItemDef collection : collections )
		{
			if( !collection.isSystem() )
			{
				filteredCollections.add(collection);
			}
		}
		Collections.sort(filteredCollections, new NumberStringComparator<ItemDef>());
		return filteredCollections;
	}
	catch( Exception e )
	{
		JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this),
			"Error retrieving Item Definitions from the server.", "Error", JOptionPane.ERROR_MESSAGE);
		e.printStackTrace();
	}
	return null;
}
 
Example 38
Project: incubator-netbeans   File: HtmlBrowserComponent.java   Source Code and License 6 votes vote down vote up
@Override
protected void componentActivated () {
    if( null != browserComponent ) {
        HtmlBrowser.Impl impl = browserComponent.getBrowserImpl();
        if( null != impl ) {
            Component c = impl.getComponent();
            if( null != c )
                c.requestFocusInWindow();
        }
    }
    super.componentActivated ();
    SwingUtilities.invokeLater( new Runnable() {

        @Override
        public void run() {
            setEnableHome(enableHome);
            setEnableLocation(enableLocation);
            setToolbarVisible(toolbarVisible);
            setStatusLineVisible(statusVisible);
            if( null != urlToLoad ) {
                setURL(urlToLoad);
            }
            urlToLoad = null;
        }
    });
}
 
Example 39
Project: incubator-netbeans   File: EditorPaneTesting.java   Source Code and License 6 votes vote down vote up
public static void setCaretOffset(Context context, final int offset) throws Exception {
    final JEditorPane pane = context.getInstance(JEditorPane.class);
    StringBuilder sb = null;
    if (context.isLogOp()) {
        sb = context.logOpBuilder();
        sb.append("SET_CARET_OFFSET: ").append(pane.getCaretPosition()).append(" => ").append(offset).append("\n");
    }
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            pane.setCaretPosition(offset);
        }
    });
    if (context.isLogOp()) {
        debugCaret(sb, pane);
        context.logOp(sb);
    }
}
 
Example 40
Project: rapidminer   File: PanningManager.java   Source Code and License 6 votes vote down vote up
@Override
public void eventDispatched(AWTEvent e) {
	if (e instanceof MouseEvent) {
		MouseEvent me = (MouseEvent) e;
		if (!SwingUtilities.isDescendingFrom(me.getComponent(), target)) {
			return;
		}
		if (me.getID() == MouseEvent.MOUSE_RELEASED) {
			// stop when mouse released
			mouseOnScreenPoint = null;
			if (timer.isRunning()) {
				timer.stop();
			}
		} else if (me.getID() == MouseEvent.MOUSE_DRAGGED && me.getComponent() == target) {
			mouseOnScreenPoint = me.getLocationOnScreen();
		} else if (me.getID() == MouseEvent.MOUSE_PRESSED && me.getComponent() == target) {
			mouseOnScreenPoint = me.getLocationOnScreen();
			timer.start();
		}
	}
}
 
Example 41
Project: openjdk-jdk10   File: EditPadTest.java   Source Code and License 6 votes vote down vote up
private Future<?> doActions(Runnable... actions) {
    return getExecutor().submit(() -> {
        try {
            waitForIdle();
            SwingUtilities.invokeLater(this::seekElements);
            waitForIdle();
            for (Runnable act : actions) {
                act.run();
            }
        } catch (Throwable e) {
            shutdownEditor();
            if (e instanceof AssertionError) {
                throw (AssertionError) e;
            }
            throw new RuntimeException(e);
        }
    });
}
 
Example 42
Project: marathonv5   File: JScrollBarTest.java   Source Code and License 5 votes vote down vote up
@BeforeMethod public void showDialog() throws Throwable {
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override public void run() {
            frame = new JFrame(JScrollBarTest.class.getSimpleName());
            frame.setSize(320, 350);
            frame.setName("frame-" + JScrollBarTest.class.getSimpleName());
            frame.getContentPane().add(new ScrollDemo(), BorderLayout.CENTER);
            // frame.pack();
            frame.setAlwaysOnTop(true);
            frame.setVisible(true);
        }
    });
}
 
Example 43
Project: marathonv5   File: RSpinnerTest.java   Source Code and License 5 votes vote down vote up
@AfterMethod public void disposeDriver() throws Throwable {
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override public void run() {
            frame.setVisible(false);
            frame.dispose();
        }
    });
}
 
Example 44
Project: openjdk-jdk10   File: bug8031109.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    SwingUtilities.invokeAndWait(new Runnable() {

        @Override
        public void run() {
            JEditorPane editorPane = new JEditorPane();
            editorPane.setEditable(false);
            EditorKit defaultHtmlEditor = JEditorPane
                    .createEditorKitForContentType(TEXT_HTML);
            editorPane.setEditorKitForContentType(TEXT_HTML, defaultHtmlEditor);
            editorPane.setContentType(TEXT_HTML);
            editorPane.getDocument().putProperty("IgnoreCharsetDirective",
                    Boolean.TRUE);
            URL url = generateHtmlFile();
            String html = "<html>"
                    + "<frameset rows=\"120px, 120 PX ,  * , 10 *\">\n"
                    + "   <frame name=\"top\" src=\"" + url + "\" />\n"
                    + "   <frame name=\"center\" src=\"" + url + "\" />\n"
                    + "   <frame name=\"main\" src=\"" + url + "\" />\n"
                    + "   <noframes>\n"
                    + "   <body>\n"
                    + "      Your browser does not support frames.\n"
                    + "   </body>\n"
                    + "   </noframes>\n"
                    + "</frameset>";
            editorPane.setText(html);
            JScrollPane scrollPane = new JScrollPane(editorPane);

            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(scrollPane);
            frame.setSize(500, 500);
            frame.setVisible(true);
        }
    });
}
 
Example 45
Project: poi-visualizer   File: POITopMenuBar.java   Source Code and License 5 votes vote down vote up
@PostConstruct
public void init() {
   	if (isInit) {
   		return;
   	}
   	isInit = true;

   	menuFileOpen = new JMenuItem("Open ...", KeyEvent.VK_O);
   	menuFileOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
   	menuFileOpen.addActionListener(e -> loadNewFile());
   	
   	menuFileClose = new JMenuItem("Exit", KeyEvent.VK_Q);
   	menuFileClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
	menuFileClose.addActionListener(e -> fireClose());
   	
   	JMenu menuFile = new JMenu("File");
   	menuFile.add(menuFileOpen);
   	menuFile.add(menuFileClose);

   	menuEditIndent = new JMenuItem("Indent", KeyEvent.VK_I);
   	menuEditIndent.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.CTRL_MASK));
   	menuEditIndent.addActionListener(e -> editIndentXml());
   	
   	menuEditApply = new JMenuItem("Apply Changes", KeyEvent.VK_A);
   	menuEditApply.addActionListener(e -> editApply());
   	
   	JMenu menuEdit = new JMenu("Edit");
   	menuEdit.add(menuEditIndent);
   	menuEdit.add(menuEditApply);
   	
	add(menuFile);
	add(menuEdit);

	treeObservable.addObserver((o,arg) -> SwingUtilities.invokeLater(() -> contentChanged()));
	
	workingDir = new File(".");
}
 
Example 46
Project: incubator-netbeans   File: ButtonPopupSwitcher.java   Source Code and License 5 votes vote down vote up
/**
 * Clean up listners and hide popup.
 */
private synchronized void hideCurrentPopup() {
    pTable.removeMouseListener(this);
    pTable.removeMouseMotionListener(this);
    pTable.getSelectionModel().removeListSelectionListener( this );
    displayer.getModel().removeComplexListDataListener( this );
    Toolkit.getDefaultToolkit().removeAWTEventListener(this);
    if (invokingComponent != null) {
        invokingComponent.removeMouseListener(this);
        invokingComponent.removeMouseMotionListener(this);
        invokingComponent = null;
    }
    if (popup != null) {
        popup.removePopupMenuListener( this );
        final JPopupMenu popupToHide = popup;
        SwingUtilities.invokeLater( new Runnable() {
            @Override
            public void run() {
                if( popupToHide.isVisible() )
                    popupToHide.setVisible( false );
            }
        });
        popup.setVisible( false );
        popup = null;
        shown = false;
        currentSwitcher = null;
    }
}
 
Example 47
Project: Progetto-J   File: ControlPanel.java   Source Code and License 5 votes vote down vote up
/**
 * Aggiunge i pulsanti delle azioni consentite
 * @param allowedActions le azioni consentite
 */
public void act(Set<ActionSet> allowedActions) {
    SwingUtilities.invokeLater(new Runnable() 
    {
        @Override
        public void run() {
            removeAll();
            if (allowedActions.contains(ActionSet.CHECK)) 
            {
                add(checkButton);
            }
            if (allowedActions.contains(ActionSet.CALL)) 
            {
                add(callButton);
            }
            if (allowedActions.contains(ActionSet.BET)) 
            {
                add(betButton);
            }
            if (allowedActions.contains(ActionSet.RAISE)) 
            {
                add(raiseButton);
            }
            if (allowedActions.contains(ActionSet.FOLD)) 
            {
                add(foldButton);
            }
            repaint();
            validate();
        }
    });
}
 
Example 48
Project: vrwiimote   File: MainGUI.java   Source Code and License 5 votes vote down vote up
public WiimotePreview() {
	Timer timer = new Timer();
	WiimotePreview test = this;
	timer.scheduleAtFixedRate(new TimerTask() {
		@Override
		public void run() {
			SwingUtilities.invokeLater(new Runnable() {
				@Override
				public void run() {
					test.repaint();
				}
			});
		}
	}, 0, 16);
}
 
Example 49
Project: incubator-netbeans   File: SnapshotsWindow.java   Source Code and License 5 votes vote down vote up
public void showStandalone() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            SnapshotsWindowUI ui = getUI(true);
            ui.open();
            ui.requestActive();
        }
    });
}
 
Example 50
Project: incubator-netbeans   File: RunOffEDTTest.java   Source Code and License 5 votes vote down vote up
public void testContinueBeforeCanceledOperationFinished() throws Exception {
    final R r = new R();
    r.l = new CountDownLatch(1);

    KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener(new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            Window w = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
            if (w != null) {
                w.setVisible(false);
            }
        }
    });
    SwingUtilities.invokeAndWait(new Runnable() {

        public void run() {
            ProgressUtils.runOffEventDispatchThread(r, "Test", new AtomicBoolean(false), false, 10, 100);
        }
    });

    final AtomicBoolean finished = new AtomicBoolean(false);
    SwingUtilities.invokeAndWait(new Runnable() {

        public void run() {
            finished.set(true);
        }
    });
    assertTrue("Should be finished", finished.get());
    r.l.countDown();
    SwingUtilities.invokeAndWait(new Runnable() {

        public void run() {
        }
    });
    assertEquals("Should run once", 1, r.runCount);
}
 
Example 51
Project: marathonv5   File: RSplitPaneTest.java   Source Code and License 5 votes vote down vote up
@BeforeMethod public void showDialog() throws Throwable {
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override public void run() {
            frame = new JFrame(RSplitPaneTest.class.getSimpleName());
            frame.setName("frame-" + RSplitPaneTest.class.getSimpleName());
            frame.getContentPane().add(new SplitPaneDemo().getSplitPane(), BorderLayout.CENTER);
            frame.pack();
            frame.setVisible(true);
        }
    });
}
 
Example 52
Project: incubator-netbeans   File: ModuleChangeHandler.java   Source Code and License 5 votes vote down vote up
private void addGroup (String groupName) {
    if (DEBUG) Debug.log(ModuleChangeHandler.class, "addGroup group:" + groupName);
    WindowManagerParser wmParser = PersistenceManager.getDefault().getWindowManagerParser();
    final GroupConfig groupConfig = wmParser.addGroup(groupName);
    if (groupConfig != null) {
        // #37529 WindowsAPI to be called from AWT thread only.
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                WindowManagerImpl.getInstance().getPersistenceObserver().groupConfigAdded(groupConfig);
            }
        });
    }
}
 
Example 53
Project: dead-code-detector   File: ParametersController.java   Source Code and License 5 votes vote down vote up
void actionRun(final Parameters parameters) {
	progressBar.setVisible(true);
	onProgress(0);
	final FileTable table = fileTable;
	thread = new Thread("DCD") { // NOPMD
		@Override
		public void run() {
			try {
				final DeadCodeDetector dcd = new DeadCodeDetector(parameters);
				dcd.setProgressListener(ParametersController.this);
				dcd.run();
			} catch (final Exception e) {
				DcdUiHelper.handleException(e, table);
			} finally {
				thread = null;
				SwingUtilities.invokeLater(new Runnable() { // NOPMD
					@Override
					public void run() {
						progressBar.setVisible(false);
					}
				});
			}
		}
	};
	thread.setDaemon(true);
	thread.start();
}
 
Example 54
Project: incubator-netbeans   File: WizardStepProgressSupport.java   Source Code and License 5 votes vote down vote up
protected void finnishProgress() {        
    WizardStepProgressSupport.super.finnishProgress();
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {                
            panel.remove(progressComponent);
            panel.revalidate();
            panel.repaint();
            panel.setVisible(false);
            setEditable(true);
        }
    });                
}
 
Example 55
Project: freecol   File: MapEditorController.java   Source Code and License 5 votes vote down vote up
/**
 * Reload the main panel when done with the map editor.
 */
private void reloadMainPanel () {
    SwingUtilities.invokeLater(() -> {
            getGUI().closeMainPanel();
            getGUI().showMainPanel(null);
            getSoundController().playSound("sound.intro.general");
        });
}
 
Example 56
Project: object-recognition-tensorflow   File: Recognizer.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new Recognizer().setVisible(true);

        }
    });
}
 
Example 57
Project: incubator-netbeans   File: LifecycleTest.java   Source Code and License 5 votes vote down vote up
private final void dosleep() {
    try {
        Thread.sleep(200);
        SwingUtilities.invokeAndWait (new Runnable() {
            public void run() {
                System.currentTimeMillis();
            }
        });
        Thread.sleep(200);
    } catch (Exception e) {
        fail (e.getMessage());
    }
}
 
Example 58
Project: marathonv5   File: DragAndDropTest.java   Source Code and License 5 votes vote down vote up
@BeforeMethod public void showDialog() throws Throwable {
    SwingUtilities.invokeAndWait(new Runnable() {

        @Override public void run() {
            frame = DropDemo.createAndShowGUI();
            frame.setAlwaysOnTop(true);
        }
    });
    EventQueueWait.waitTillShown(frame);
}
 
Example 59
Project: SQLNavigator   File: SQL_Create.java   Source Code and License 5 votes vote down vote up
private void createScene() {
    Platform.runLater(() -> {


            WebView view = new WebView();
            //view.setContextMenuEnabled(false);
            System.out.println("This happened");
            engine = view.getEngine();
            System.out.println("So did this");
            FXPanel.setScene(new Scene(view));
            engine.load(path+"SQLNavigator/Create/home.html");
            engine.getLoadWorker().stateProperty().addListener((ObservableValue<? extends Worker.State> ov,Worker.State oldState, Worker.State newState) -> {  
                        if (newState == Worker.State.SUCCEEDED) {
                            exec.use_db(dblist.dblist.get(0).database);
                            dbinfo.removeAllElements();
                            fetch_dbinfo();
                            JSObject win =  (JSObject) engine.executeScript("window");
                            win.setMember("DB", dblist);
                            win.setMember("SQL", exec);
                            engine.executeScript("run()");
                        }
                        //engine.executeScript("run()");
                    }
            );
            engine.titleProperty().addListener(new ChangeListener<String>() {
                @Override
                public void changed(ObservableValue<? extends String> observable, String oldValue, final String newValue) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            SQL_Create.this.setTitle(newValue);
                        }
                    });
                }
            });
    });
}
 
Example 60
Project: jdk8u-jdk   File: LWCheckboxPeer.java   Source Code and License 5 votes vote down vote up
@Override
public void itemStateChanged(final ItemEvent e) {
    // group.setSelectedCheckbox() will repaint the component
    // to let LWCheckboxPeer correctly handle it we should call it
    // after the current event is processed
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            boolean postEvent = true;
            final CheckboxGroup group = getTarget().getCheckboxGroup();
            if (group != null) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    if (group.getSelectedCheckbox() != getTarget()) {
                        group.setSelectedCheckbox(getTarget());
                    } else {
                        postEvent = false;
                    }
                } else {
                    postEvent = false;
                    if (group.getSelectedCheckbox() == getTarget()) {
                        // Don't want to leave the group with no selected
                        // checkbox.
                        getTarget().setState(true);
                    }
                }
            } else {
                getTarget().setState(e.getStateChange()
                                     == ItemEvent.SELECTED);
            }
            if (postEvent) {
                postEvent(new ItemEvent(getTarget(),
                                        ItemEvent.ITEM_STATE_CHANGED,
                                        getTarget().getLabel(),
                                        e.getStateChange()));
            }
        }
    });
}