Example usage for javax.swing Timer Timer

List of usage examples for javax.swing Timer Timer

Introduction

In this page you can find the example usage for javax.swing Timer Timer.

Prototype

public Timer(int delay, ActionListener listener) 

Source Link

Document

Creates a Timer and initializes both the initial delay and between-event delay to delay milliseconds.

Usage

From source file:org.jfree.chart.demo.CyclicXYPlotDemo.java

/**
 * A demonstration application showing an XY plot, with a cyclic axis and renderer
 *
 * @param title  the frame title./*from  w ww. ja  va  2 s .  co  m*/
 */
public CyclicXYPlotDemo(final String title) {

    super(title);

    this.series = new XYSeries("Random Data");
    this.series.setMaximumItemCount(50); // Only 50 items are visible at the same time. 
                                         // Keep more as a mean to test this.
    final XYSeriesCollection data = new XYSeriesCollection(this.series);

    final JFreeChart chart = ChartFactory.createXYLineChart("Cyclic XY Plot Demo", "X", "Y", data,
            PlotOrientation.VERTICAL, true, true, false);

    final XYPlot plot = chart.getXYPlot();
    plot.setDomainAxis(new CyclicNumberAxis(10, 0));
    plot.setRenderer(new CyclicXYItemRenderer());

    final NumberAxis axis = (NumberAxis) plot.getRangeAxis();
    axis.setAutoRangeIncludesZero(false);
    axis.setAutoRangeMinimumSize(1.0);

    final ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(400, 300));
    final JPanel content = new JPanel(new BorderLayout());
    content.add(chartPanel, BorderLayout.CENTER);

    final JButton button1 = new JButton("Start");
    button1.addActionListener(new ActionListener() {
        public void actionPerformed(final ActionEvent e) {
            timer.start();
        }
    });

    final JButton button2 = new JButton("Stop");
    button2.addActionListener(new ActionListener() {
        public void actionPerformed(final ActionEvent e) {
            timer.stop();
        }
    });

    final JButton button3 = new JButton("Step by step");
    button3.addActionListener(new ActionListener() {
        public void actionPerformed(final ActionEvent e) {
            CyclicXYPlotDemo.this.actionPerformed(null);
        }
    });

    final JPanel buttonPanel = new JPanel(new FlowLayout());
    buttonPanel.add(button1);
    buttonPanel.add(button2);
    buttonPanel.add(button3);

    content.add(buttonPanel, BorderLayout.SOUTH);
    setContentPane(content);

    this.timer = new Timer(200, this);
}

From source file:de.wusel.partyplayer.gui.PartyPlayer.java

@Override
protected void ready() {

    readSettingsFile(PathUtil.getSettingsFile());
    checkBinaries();/*  w w  w  .  j  a  v a 2s .  com*/
    this.statusbar.init();
    readBackupFile(PathUtil.getLibraryFile());

    timer = new Timer(settings.getFolderCheckInterval(), new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (!started) {
                started = true;
                getContext().getTaskService()
                        .execute(new CheckAvailableSongsTask(getInstance(), playerModel, settings));
                getContext().getTaskService()
                        .execute(new CheckSearchDirectoryTask(getInstance(), playerModel, settings));
                started = false;
            }
        }
    });
    timer.setInitialDelay(0);
    timer.start();
}

From source file:WindowEventDemo.java

public void windowClosing(WindowEvent e) {
    displayMessage("WindowListener method called: windowClosing.");

    //A pause so user can see the message before
    //the window actually closes.
    ActionListener task = new ActionListener() {
        boolean alreadyDisposed = false;

        public void actionPerformed(ActionEvent e) {
            if (!alreadyDisposed) {
                alreadyDisposed = true;/*w  w  w  .j a  v a 2 s. c  om*/
                frame.dispose();
            } else { //make sure the program exits
                System.exit(0);
            }
        }
    };
    Timer timer = new Timer(500, task); //fire every half second
    timer.setInitialDelay(2000); //first delay 2 seconds
    timer.start();
}

From source file:org.gdms.usm.view.ProgressFrame.java

public ProgressFrame(Step s, boolean modifyThresholds) {
    super("Progress");
    simulation = s;/* www . ja  v a 2 s. c o  m*/
    s.registerStepListener(this);
    stepSeconds = new LinkedList<Integer>();

    s.getManager().setModifyThresholds(modifyThresholds);
    s.getManager().setAdvisor(this);

    JPanel statusPanel = new JPanel(new BorderLayout());
    JPanel globalPanel = new JPanel(new SpringLayout());

    //Time elapsed panel
    JPanel timePanel = new JPanel(new BorderLayout(5, 5));
    final JLabel timeLabel = new JLabel("00:00:00", SwingConstants.CENTER);
    timeLabel.setFont(new Font("Serif", Font.BOLD, 45));
    timePanel.add(timeLabel, BorderLayout.SOUTH);
    JLabel elapsed = new JLabel("Time Elapsed :", SwingConstants.CENTER);
    timePanel.add(elapsed, BorderLayout.NORTH);
    statusPanel.add(timePanel, BorderLayout.NORTH);

    ActionListener timerListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            totalSeconds++;
            int hours = totalSeconds / 3600;
            String hourss;
            if (hours < 10) {
                hourss = "0" + hours;
            } else {
                hourss = "" + hours;
            }
            int minutes = (totalSeconds % 3600) / 60;
            String minutess;
            if (minutes < 10) {
                minutess = "0" + minutes;
            } else {
                minutess = "" + minutes;
            }
            int seconds = totalSeconds % 60;
            String secondss;
            if (seconds < 10) {
                secondss = "0" + seconds;
            } else {
                secondss = seconds + "";
            }
            timeLabel.setText(hourss + ":" + minutess + ":" + secondss);
        }
    };
    timer = new Timer(1000, timerListener);
    timer.start();

    //Turn progress panel
    JPanel turnPanel = new JPanel(new BorderLayout(5, 5));
    JLabel turnLabel = new JLabel("Current Step :", SwingConstants.CENTER);
    turnPanel.add(turnLabel, BorderLayout.NORTH);
    currentTurn = new JLabel("Init", SwingConstants.CENTER);
    currentTurn.setFont(new Font("Serif", Font.BOLD, 30));
    turnPanel.add(currentTurn, BorderLayout.SOUTH);
    globalPanel.add(turnPanel);

    //Movers panel
    JPanel moversPanel = new JPanel(new BorderLayout(5, 5));
    JLabel moversLabel = new JLabel("Last movers count :", SwingConstants.CENTER);
    moversPanel.add(moversLabel, BorderLayout.NORTH);
    lastMoversCount = new JLabel("Init", SwingConstants.CENTER);
    lastMoversCount.setFont(new Font("Serif", Font.BOLD, 30));
    moversPanel.add(lastMoversCount, BorderLayout.SOUTH);
    globalPanel.add(moversPanel);

    //Initial population panel
    JPanel initPopPanel = new JPanel(new BorderLayout(5, 5));
    JLabel initialPopulationLabel = new JLabel("Initial population :", SwingConstants.CENTER);
    initPopPanel.add(initialPopulationLabel, BorderLayout.NORTH);
    initialPopulationCount = new JLabel("Init", SwingConstants.CENTER);
    initialPopulationCount.setFont(new Font("Serif", Font.BOLD, 30));
    initPopPanel.add(initialPopulationCount, BorderLayout.SOUTH);
    globalPanel.add(initPopPanel);

    //Current population panel
    JPanel curPopPanel = new JPanel(new BorderLayout(5, 5));
    JLabel currentPopulationLabel = new JLabel("Current population :", SwingConstants.CENTER);
    curPopPanel.add(currentPopulationLabel, BorderLayout.NORTH);
    currentPopulation = new JLabel("Init", SwingConstants.CENTER);
    currentPopulation.setFont(new Font("Serif", Font.BOLD, 30));
    curPopPanel.add(currentPopulation, BorderLayout.SOUTH);
    globalPanel.add(curPopPanel);

    //Dead panel
    JPanel deadPanel = new JPanel(new BorderLayout(5, 5));
    JLabel deadLabel = new JLabel("Last death toll :", SwingConstants.CENTER);
    deadPanel.add(deadLabel, BorderLayout.NORTH);
    lastDeathToll = new JLabel("Init", SwingConstants.CENTER);
    lastDeathToll.setFont(new Font("Serif", Font.BOLD, 30));
    deadPanel.add(lastDeathToll, BorderLayout.SOUTH);
    globalPanel.add(deadPanel);

    //Newborn panel
    JPanel newbornPanel = new JPanel(new BorderLayout(5, 5));
    JLabel newbornLabel = new JLabel("Last newborn count :", SwingConstants.CENTER);
    newbornPanel.add(newbornLabel, BorderLayout.NORTH);
    lastNewbornCount = new JLabel("Init", SwingConstants.CENTER);
    lastNewbornCount.setFont(new Font("Serif", Font.BOLD, 30));
    newbornPanel.add(lastNewbornCount, BorderLayout.SOUTH);
    globalPanel.add(newbornPanel);

    SpringUtilities.makeCompactGrid(globalPanel, 3, 2, 5, 5, 20, 10);
    statusPanel.add(globalPanel, BorderLayout.SOUTH);

    add(statusPanel, BorderLayout.WEST);

    //Graph tabbed pane
    JTabbedPane tabbedPane = new JTabbedPane();
    timeChart = new XYSeries("Step time", true, false);
    tabbedPane.addTab("Step time", createChartPanel("Step time", timeChart));
    currentPopulationChart = new XYSeries("Population", true, false);
    tabbedPane.addTab("Population", createChartPanel("Population", currentPopulationChart));
    deathTollChart = new XYSeries("Deaths", true, false);
    tabbedPane.addTab("Deaths", createChartPanel("Deaths", deathTollChart));
    newbornCountChart = new XYSeries("Newborn", true, false);
    tabbedPane.addTab("Newborn", createChartPanel("Newborn", newbornCountChart));
    moversCountChart = new XYSeries("Movers", true, false);
    tabbedPane.addTab("Movers", createChartPanel("Movers", moversCountChart));
    add(tabbedPane, BorderLayout.EAST);

    getRootPane().setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 10));
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    pack();
    setLocationRelativeTo(null);
    setVisible(true);
}

From source file:eu.delving.sip.Application.java

private Application(final File storageDir) throws StorageException {
    GroovyCodeResource groovyCodeResource = new GroovyCodeResource(getClass().getClassLoader());
    final ImageIcon backgroundIcon = new ImageIcon(getClass().getResource("/delving-background.png"));
    desktop = new JDesktopPane() {
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(backgroundIcon.getImage(), 0, 0, desktop);
        }//from  w ww. j ava2s  .  c  o  m
    };
    desktop.setMinimumSize(new Dimension(MINIMUM_DESKTOP_SIZE));
    resizeTimer = new Timer(DEFAULT_RESIZE_INTERVAL, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            resizeTimer.stop();
            for (JInternalFrame frame : desktop.getAllFrames()) {
                if (frame instanceof FrameBase) {
                    ((FrameBase) frame).ensureOnScreen();
                }
            }
        }
    });
    desktop.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent componentEvent) {
            resizeTimer.restart();
        }
    });
    Preferences preferences = Preferences.userNodeForPackage(SipModel.class);
    feedback = new VisualFeedback(home, desktop, preferences);
    HttpClient httpClient = createHttpClient(storageDir);
    SchemaRepository schemaRepository;
    try {
        schemaRepository = new SchemaRepository(new SchemaFetcher(httpClient));
    } catch (IOException e) {
        throw new StorageException("Unable to create Schema Repository", e);
    }
    ResolverContext context = new ResolverContext();
    Storage storage = new StorageImpl(storageDir, schemaRepository, new CachedResourceResolver(context));
    context.setStorage(storage);
    context.setHttpClient(httpClient);
    sipModel = new SipModel(desktop, storage, groovyCodeResource, feedback, preferences);
    CultureHubClient cultureHubClient = isStandalone(storageDir) ? null
            : new CultureHubClient(sipModel, httpClient);
    if (cultureHubClient != null)
        uploadAction = new UploadAction(sipModel, cultureHubClient);
    expertMenu = new ExpertMenu(desktop, sipModel, cultureHubClient, allFrames);
    statusPanel = new StatusPanel(sipModel);
    home = new JFrame(titleString());
    home.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent componentEvent) {
            allFrames.getViewSelector().refreshView();
        }
    });
    JPanel content = (JPanel) home.getContentPane();
    content.setFocusable(true);
    FrameBase dataSetFrame = cultureHubClient != null ? new DataSetHubFrame(sipModel, cultureHubClient)
            : new DataSetStandaloneFrame(sipModel, schemaRepository);
    LogFrame logFrame = new LogFrame(sipModel);
    feedback.setLog(logFrame.getLog());
    allFrames = new AllFrames(sipModel, content, dataSetFrame, logFrame);
    desktop.setBackground(new Color(190, 190, 200));
    content.add(desktop, BorderLayout.CENTER);
    sipModel.getMappingModel().addChangeListener(new MappingModel.ChangeListener() {
        @Override
        public void lockChanged(MappingModel mappingModel, final boolean locked) {
            sipModel.exec(new Swing() {
                @Override
                public void run() {
                    unlockMappingAction.setEnabled(locked);
                }
            });
        }

        @Override
        public void functionChanged(MappingModel mappingModel, MappingFunction function) {
        }

        @Override
        public void nodeMappingChanged(MappingModel mappingModel, RecDefNode node, NodeMapping nodeMapping,
                NodeMappingChange change) {
        }

        @Override
        public void nodeMappingAdded(MappingModel mappingModel, RecDefNode node, NodeMapping nodeMapping) {
        }

        @Override
        public void nodeMappingRemoved(MappingModel mappingModel, RecDefNode node, NodeMapping nodeMapping) {
        }

        @Override
        public void populationChanged(MappingModel mappingModel, RecDefNode node) {
        }
    });
    importAction = new ImportAction(desktop, sipModel);
    attachAccelerator(importAction, home);
    validateAction = new ValidateAction(sipModel, allFrames.prepareForInvestigation(desktop));
    unlockMappingAction = new UnlockMappingAction(sipModel);
    attachAccelerator(unlockMappingAction, home);
    selectAnotherMappingAction = new SelectAnotherMappingAction(sipModel);
    attachAccelerator(selectAnotherMappingAction, home);
    content.add(createStatePanel(), BorderLayout.SOUTH);
    content.add(allFrames.getSidePanel(), BorderLayout.WEST);
    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
    screen.height -= 30;
    home.setSize(screen);
    home.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    ImageIcon logo = new ImageIcon(getClass().getResource("/sip-creator-logo.png"));
    home.setIconImage(logo.getImage());
    home.setJMenuBar(createMenuBar());
    home.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent windowEvent) {
            quit();
        }
    });
    home.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    sipModel.getDataSetModel().addListener(new DataSetModel.SwingListener() {
        @Override
        public void stateChanged(DataSetModel model, DataSetState state) {
            statusPanel.setState(state);
            switch (state) {
            case ABSENT:
                sipModel.exec(new Work() {
                    @Override
                    public void run() {
                        sipModel.getDataSetFacts().set(null);
                        sipModel.getStatsModel().setStatistics(null);
                    }

                    @Override
                    public Job getJob() {
                        return Job.CLEAR_FACTS_STATS;
                    }
                });
                home.setTitle(titleString());
                sipModel.seekReset();
                break;
            default:
                DataSetModel dataSetModel = sipModel.getDataSetModel();
                home.setTitle(String.format(titleString() + " - [%s -> %s]",
                        dataSetModel.getDataSet().getSpec(), dataSetModel.getPrefix().toUpperCase()));
                sipModel.getReportFileModel().refresh();
                break;
            }
        }
    });
    attachAccelerator(new QuitAction(), home);
    attachAccelerator(statusPanel.getButtonAction(), home);
}

From source file:cs.cirg.cida.CIDAView.java

public CIDAView(SingleFrameApplication app) {
    super(app);//from  ww  w .  j  ava  2 s.  c o  m

    exceptionController = new ExceptionController();
    experimentController = new ExperimentController(this,
            new ExperimentAnalysisModel(((CIDAApplication) app).getStartupDirectory()));
    tableConstructionController = new TableConstructionController(this, experimentController.getModel());

    userSelectedRows = new ArrayList<Integer>();
    userSelectedColumns = new ArrayList<Integer>();

    initComponents();

    // status bar initialization - message timeout, idle icon and busy animation, etc
    ResourceMap resourceMap = getResourceMap();
    int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
    messageTimer = new Timer(messageTimeout, new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            statusMessageLabel.setText("");
        }
    });
    messageTimer.setRepeats(false);
    int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
    for (int i = 0; i < busyIcons.length; i++) {
        busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
    }
    busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
            statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
        }
    });
    idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
    statusAnimationLabel.setIcon(idleIcon);
    progressBar.setVisible(false);

    // connecting action tasks to status bar via TaskMonitor
    TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
    taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

        public void propertyChange(java.beans.PropertyChangeEvent evt) {
            String propertyName = evt.getPropertyName();
            if ("started".equals(propertyName)) {
                if (!busyIconTimer.isRunning()) {
                    statusAnimationLabel.setIcon(busyIcons[0]);
                    busyIconIndex = 0;
                    busyIconTimer.start();
                }
                progressBar.setVisible(true);
                progressBar.setIndeterminate(true);
            } else if ("done".equals(propertyName)) {
                busyIconTimer.stop();
                statusAnimationLabel.setIcon(idleIcon);
                progressBar.setVisible(false);
                progressBar.setValue(0);
            } else if ("message".equals(propertyName)) {
                String text = (String) (evt.getNewValue());
                statusMessageLabel.setText((text == null) ? "" : text);
                messageTimer.restart();
            } else if ("progress".equals(propertyName)) {
                int value = (Integer) (evt.getNewValue());
                progressBar.setVisible(true);
                progressBar.setIndeterminate(false);
                progressBar.setValue(value);
            }
        }
    });
}

From source file:com.vgi.mafscaling.LogPlay.java

private void initialize() {
    lastRow = logDataTable.getRowCount() - 1;
    playNext = new AtomicInteger(1);
    playIcon = new ImageIcon(getClass().getResource("/play.png"));
    pauseIcon = new ImageIcon(getClass().getResource("/pause.png"));
    zeroInsets.put("Button.contentMargins", insets0);
    timer = new Timer(timerDelay, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            progressBar.setValue(progressBar.getValue() + playNext.get());
        }/*from   ww  w  .j  a v a 2s. c o  m*/
    });

    JPanel dataPanel = new JPanel();
    GridBagLayout gbl_dataPanel = new GridBagLayout();
    gbl_dataPanel.columnWidths = new int[] { 0 };
    gbl_dataPanel.rowHeights = new int[] { 0, 1 };
    gbl_dataPanel.columnWeights = new double[] { 1.0 };
    gbl_dataPanel.rowWeights = new double[] { 0.0, 1.0 };
    dataPanel.setLayout(gbl_dataPanel);
    getContentPane().add(dataPanel);

    createSelectionPanel(dataPanel);
    createPlayer(dataPanel);

    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            timer.stop();
            synchronized (lock) {
                for (TableHolder t : tables)
                    t.table.dispose();
                tables.clear();
            }
            logView.disposeLogView();
        }
    });

    pack();
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setIconImage((new ImageIcon(getClass().getResource("/player.png"))).getImage());
    setResizable(false);
    setLocationRelativeTo(SwingUtilities.windowForComponent(logView));
    setVisible(true);
}

From source file:events.WindowEventDemo.java

public void windowClosing(WindowEvent e) {
    displayMessage("WindowListener method called: windowClosing.");
    //A pause so user can see the message before
    //the window actually closes.
    ActionListener task = new ActionListener() {
        boolean alreadyDisposed = false;

        public void actionPerformed(ActionEvent e) {
            if (frame.isDisplayable()) {
                alreadyDisposed = true;// w w  w .jav a  2s . c  om
                frame.dispose();
            }
        }
    };
    Timer timer = new Timer(500, task); //fire every half second
    timer.setInitialDelay(2000); //first delay 2 seconds
    timer.setRepeats(false);
    timer.start();
}

From source file:components.MenuSelectionManagerDemo.java

public JMenuBar createMenuBar() {
    JMenuBar menuBar;/*from w  w w .j av a  2  s  .com*/
    JMenu menu, submenu;
    JMenuItem menuItem;
    JRadioButtonMenuItem rbMenuItem;
    JCheckBoxMenuItem cbMenuItem;

    //Create the menu bar.
    menuBar = new JMenuBar();

    //Build the first menu.
    menu = new JMenu("A Menu");
    menu.setMnemonic(KeyEvent.VK_A);
    menu.getAccessibleContext().setAccessibleDescription("The only menu in this program that has menu items");
    menuBar.add(menu);

    //a group of JMenuItems
    menuItem = new JMenuItem("A text-only menu item", KeyEvent.VK_T);
    //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
    menuItem.getAccessibleContext().setAccessibleDescription("This doesn't really do anything");
    menuItem.addActionListener(this);
    menu.add(menuItem);

    ImageIcon icon = createImageIcon("images/middle.gif");
    menuItem = new JMenuItem("Both text and icon", icon);
    menuItem.setMnemonic(KeyEvent.VK_B);
    menuItem.addActionListener(this);
    menu.add(menuItem);

    menuItem = new JMenuItem(icon);
    menuItem.setMnemonic(KeyEvent.VK_D);
    menuItem.addActionListener(this);
    menu.add(menuItem);

    //a group of radio button menu items
    menu.addSeparator();
    ButtonGroup group = new ButtonGroup();

    rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
    rbMenuItem.setSelected(true);
    rbMenuItem.setMnemonic(KeyEvent.VK_R);
    group.add(rbMenuItem);
    rbMenuItem.addActionListener(this);
    menu.add(rbMenuItem);

    rbMenuItem = new JRadioButtonMenuItem("Another one");
    rbMenuItem.setMnemonic(KeyEvent.VK_O);
    group.add(rbMenuItem);
    rbMenuItem.addActionListener(this);
    menu.add(rbMenuItem);

    //a group of check box menu items
    menu.addSeparator();
    cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
    cbMenuItem.setMnemonic(KeyEvent.VK_C);
    cbMenuItem.addItemListener(this);
    menu.add(cbMenuItem);

    cbMenuItem = new JCheckBoxMenuItem("Another one");
    cbMenuItem.setMnemonic(KeyEvent.VK_H);
    cbMenuItem.addItemListener(this);
    menu.add(cbMenuItem);

    //a submenu
    menu.addSeparator();
    submenu = new JMenu("A submenu");
    submenu.setMnemonic(KeyEvent.VK_S);

    menuItem = new JMenuItem("An item in the submenu");
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.ALT_MASK));
    menuItem.addActionListener(this);
    submenu.add(menuItem);

    menuItem = new JMenuItem("Another item");
    menuItem.addActionListener(this);
    submenu.add(menuItem);
    menu.add(submenu);

    //Build second menu in the menu bar.
    menu = new JMenu("Another Menu");
    menu.setMnemonic(KeyEvent.VK_N);
    menu.getAccessibleContext().setAccessibleDescription("This menu does nothing");
    menuBar.add(menu);

    Timer timer = new Timer(ONE_SECOND, new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            MenuElement[] path = MenuSelectionManager.defaultManager().getSelectedPath();
            for (int i = 0; i < path.length; i++) {
                if (path[i].getComponent() instanceof javax.swing.JMenuItem) {
                    JMenuItem mi = (JMenuItem) path[i].getComponent();
                    if ("".equals(mi.getText())) {
                        output.append("ICON-ONLY MENU ITEM > ");
                    } else {
                        output.append(mi.getText() + " > ");
                    }
                }
            }
            if (path.length > 0)
                output.append(newline);
        }
    });
    timer.start();
    return menuBar;
}

From source file:me.mayo.telnetkek.MainPanel.java

private void writeToConsoleImmediately(final ConsoleMessage message, final boolean isTelnetError) {
    SwingUtilities.invokeLater(() -> {
        if (isTelnetError && chkIgnoreErrors.isSelected()) {
            return;
        }// ww  w.j av a2 s  . com

        final StyledDocument styledDocument = mainOutput.getStyledDocument();

        int startLength = styledDocument.getLength();

        try {
            styledDocument.insertString(styledDocument.getLength(),
                    message.getMessage() + System.lineSeparator(),
                    StyleContext.getDefaultStyleContext().addAttribute(SimpleAttributeSet.EMPTY,
                            StyleConstants.Foreground, message.getColor()));
        } catch (BadLocationException ex) {
            throw new RuntimeException(ex);
        }

        if (MainPanel.this.chkAutoScroll.isSelected() && MainPanel.this.mainOutput.getSelectedText() == null) {
            final JScrollBar vScroll = mainOutputScoll.getVerticalScrollBar();

            if (!vScroll.getValueIsAdjusting()) {
                if (vScroll.getValue() + vScroll.getModel().getExtent() >= (vScroll.getMaximum() - 50)) {
                    MainPanel.this.mainOutput.setCaretPosition(startLength);

                    final Timer timer = new Timer(10, (ActionEvent ae) -> {
                        vScroll.setValue(vScroll.getMaximum());
                    });
                    timer.setRepeats(false);
                    timer.start();
                }
            }
        }
    });
}