Example usage for java.awt.event ActionListener ActionListener

List of usage examples for java.awt.event ActionListener ActionListener

Introduction

In this page you can find the example usage for java.awt.event ActionListener ActionListener.

Prototype

ActionListener

Source Link

Usage

From source file:ListProperties.java

public static void main(String args[]) {
    final JFrame frame = new JFrame("List Properties");

    final CustomTableModel model = new CustomTableModel();
    model.uiDefaultsUpdate(UIManager.getDefaults());
    TableSorter sorter = new TableSorter(model);

    JTable table = new JTable(sorter);
    TableHeaderSorter.install(sorter, table);

    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

    UIManager.LookAndFeelInfo looks[] = UIManager.getInstalledLookAndFeels();

    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            final String lafClassName = actionEvent.getActionCommand();
            Runnable runnable = new Runnable() {
                public void run() {
                    try {
                        UIManager.setLookAndFeel(lafClassName);
                        SwingUtilities.updateComponentTreeUI(frame);
                        // Added
                        model.uiDefaultsUpdate(UIManager.getDefaults());
                    } catch (Exception exception) {
                        JOptionPane.showMessageDialog(frame, "Can't change look and feel", "Invalid PLAF",
                                JOptionPane.ERROR_MESSAGE);
                    }//from w  w w.  j a va2 s.co  m
                }
            };
            SwingUtilities.invokeLater(runnable);
        }
    };

    JToolBar toolbar = new JToolBar();
    for (int i = 0, n = looks.length; i < n; i++) {
        JButton button = new JButton(looks[i].getName());
        button.setActionCommand(looks[i].getClassName());
        button.addActionListener(actionListener);
        toolbar.add(button);
    }

    Container content = frame.getContentPane();
    content.add(toolbar, BorderLayout.NORTH);
    JScrollPane scrollPane = new JScrollPane(table);
    content.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(400, 400);
    frame.setVisible(true);
}

From source file:flow.visibility.FlowMain.java

public static void main(String[] args) throws Exception {

    /************************************************************** 
     * Creating the Main GUI /*from w  w  w .j  a  v a  2s  .  com*/
     **************************************************************/

    final JDesktopPane desktop = new JDesktopPane();

    final JMenuBar mb = new JMenuBar();
    JMenu menu;

    /** Add File Menu to Open File and Save Result */

    menu = new JMenu("File");
    JMenuItem Open = new JMenuItem("Open");
    JMenuItem Save = new JMenuItem("Save");
    menu.add(Open);
    menu.add(Save);

    menu.addSeparator();
    JMenuItem Exit = new JMenuItem("Exit");
    menu.add(Exit);
    Exit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    });

    mb.add(menu);

    /** Add Control Menu to Start and Stop Capture */

    menu = new JMenu("Control");
    JMenuItem Start = new JMenuItem("Start Capture");
    JMenuItem Stop = new JMenuItem("Stop Capture");
    menu.add(Start);
    Start.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            FlowDumper.main(false);
        }
    });

    menu.add(Stop);
    Stop.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            FlowDumper.main(true);
        }
    });

    mb.add(menu);

    /** Add Configuration Menu for Tapping and Display */

    menu = new JMenu("Configuration");
    JMenuItem Tapping = new JMenuItem("Tapping Configuration");
    JMenuItem Display = new JMenuItem("Display Configuration");
    menu.add(Tapping);
    Tapping.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            FlowTapping.main(null);
        }
    });
    menu.add(Display);

    mb.add(menu);

    /** Add Detail Menu for NetGrok Visualization and JEthereal Inspection */

    menu = new JMenu("Flow Detail");
    JMenuItem FlowVisual = new JMenuItem("Flow Visualization");
    JMenuItem FlowInspect = new JMenuItem("Flow Inspections");
    menu.add(FlowVisual);
    FlowVisual.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            NetworkView.main(null);
        }
    });
    menu.add(FlowInspect);
    FlowInspect.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Ethereal.main(null);
        }
    });
    mb.add(menu);

    /** Add Help Menu for Software Information */
    menu = new JMenu("Help");
    JMenuItem About = new JMenuItem("About");
    menu.add(About);
    About.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "OF@TEIN Flow Visibility Tools @ 2015 by GIST",
                    "About the Software", JOptionPane.PLAIN_MESSAGE);
        }
    });
    mb.add(menu);

    /** Creating the main frame */
    JFrame frame = new JFrame("OF@TEIN Flow Visibility Tools");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());
    frame.add(desktop);
    frame.setJMenuBar(mb);
    frame.setSize(1215, 720);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    /**Add Blank three (3) Internal Jframe*/

    /**Internal Frame from Flow Summary Chart*/
    JInternalFrame FlowStatistic = new JInternalFrame("Flow Statistic", true, true, true, true);
    FlowStatistic.setBounds(0, 0, 600, 330);
    ChartPanel chartPanel = new ChartPanel(createChart(null));
    chartPanel.setMouseZoomable(true, false);
    FlowStatistic.add(chartPanel);
    FlowStatistic.setVisible(true);
    desktop.add(FlowStatistic);

    /**Internal Frame from Flow Summary Text*/
    JInternalFrame FlowSummary = new JInternalFrame("Flow Summary", true, true, true, true);
    FlowSummary.setBounds(0, 331, 600, 329);
    JTextArea textArea = new JTextArea(50, 10);
    JScrollPane scrollPane = new JScrollPane(textArea);
    FlowSummary.add(scrollPane);
    FlowSummary.setVisible(true);
    desktop.add(FlowSummary);

    //JInternalFrame FlowInspection = new JInternalFrame("Flow Inspection", true, true, true, true);
    //FlowInspection.setBounds(601, 0, 600, 660);
    //JTextArea textArea2 = new JTextArea(50, 10);
    //JScrollPane scrollPane2 = new JScrollPane(textArea2);
    //FlowInspection.add(scrollPane2);
    //FlowInspection.setVisible(true);
    //desktop.add(FlowInspection);

    /**Internal Frame from Printing the Packet Sequence*/
    JInternalFrame FlowSequence = new JInternalFrame("Flow Sequence", true, true, true, true);
    FlowSequence.setBounds(601, 0, 600, 660);
    JTextArea textArea3 = new JTextArea(50, 10);
    JScrollPane scrollPane3 = new JScrollPane(textArea3);
    FlowSequence.add(scrollPane3);
    FlowSequence.setVisible(true);
    desktop.add(FlowSequence);

    /************************************************************** 
     * Update the Frame Regularly
     **************************************************************/

    /** Regularly update the Frame Content every 3 seconds */

    for (;;) {

        desktop.removeAll();
        desktop.add(FlowProcess.FlowStatistic());
        desktop.add(FlowProcess.FlowSummary());
        //desktop.add(FlowProcess.FlowInspection());
        desktop.add(FlowProcess.FlowSequence());
        desktop.revalidate();
        Thread.sleep(10000);

    }

}

From source file:ToggleSample.java

public static void main(String args[]) {
    JFrame frame = new JFrame("JToggleButtonMenuItem Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JMenuBar bar = new JMenuBar();
    JMenu file = new JMenu("File");
    file.setMnemonic('f');
    JMenuItem newItem = new JMenuItem("New", 'N');
    file.add(newItem);/*from   ww w .  j a  va  2 s . c o  m*/
    JMenuItem openItem = new JMenuItem("Open", 'O');
    file.add(openItem);
    JMenuItem closeItem = new JMenuItem("Close", 'C');
    file.add(closeItem);
    file.addSeparator();
    JMenuItem saveItem = new JMenuItem("Save", 'S');
    file.add(saveItem);
    file.addSeparator();
    JMenuItem exitItem = new JMenuItem("Exit", 'X');
    file.add(exitItem);
    bar.add(file);
    JMenu edit = new JMenu("Edit");
    JMenuItem cutItem = new JMenuItem("Cut", 'T');
    cutItem.setAccelerator(KeyStroke.getKeyStroke('X', Event.CTRL_MASK));
    edit.add(cutItem);
    JMenuItem copyItem = new JMenuItem("Copy", 'C');
    copyItem.setAccelerator(KeyStroke.getKeyStroke('C', Event.CTRL_MASK));
    edit.add(copyItem);
    JMenuItem pasteItem = new JMenuItem("Paste", 'P');
    pasteItem.setAccelerator(KeyStroke.getKeyStroke('V', Event.CTRL_MASK));
    pasteItem.setEnabled(false);
    edit.add(pasteItem);
    edit.addSeparator();
    JMenuItem findItem = new JMenuItem("Find", 'F');
    findItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0));
    edit.add(findItem);
    edit.setMnemonic('e');
    Icon atIcon = new ImageIcon("at.gif");
    JMenu findOptions = new JMenu("Options");
    findOptions.setIcon(atIcon);
    findOptions.setMnemonic('O');
    ButtonGroup directionGroup = new ButtonGroup();
    JRadioButtonMenuItem forward = new JRadioButtonMenuItem("Forward", true);
    findOptions.add(forward);
    directionGroup.add(forward);
    JRadioButtonMenuItem backward = new JRadioButtonMenuItem("Backward");
    findOptions.add(backward);
    directionGroup.add(backward);
    findOptions.addSeparator();
    JCheckBoxMenuItem caseItem = new JCheckBoxMenuItem("Case Insensitive");
    findOptions.add(caseItem);
    edit.add(findOptions);
    JToggleButtonMenuItem toggleItem = new JToggleButtonMenuItem("Ballon Help");
    toggleItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("Selected");
        }
    });
    edit.add(toggleItem);
    bar.add(edit);
    frame.setJMenuBar(bar);
    frame.setSize(350, 250);
    frame.setVisible(true);
}

From source file:ModifyModelSample.java

public static void main(String args[]) {
    JFrame frame = new JFrame("Modifying Model");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    // Fill model
    final DefaultListModel model = new DefaultListModel();
    for (int i = 0, n = labels.length; i < n; i++) {
        model.addElement(labels[i]);/*from w  w  w  .ja v a  2s . c o m*/
    }
    JList jlist = new JList(model);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    contentPane.add(scrollPane1, BorderLayout.WEST);

    final JTextArea textArea = new JTextArea();
    textArea.setEditable(false);
    JScrollPane scrollPane2 = new JScrollPane(textArea);
    contentPane.add(scrollPane2, BorderLayout.CENTER);

    ListDataListener listDataListener = new ListDataListener() {
        public void contentsChanged(ListDataEvent listDataEvent) {
            appendEvent(listDataEvent);
        }

        public void intervalAdded(ListDataEvent listDataEvent) {
            appendEvent(listDataEvent);
        }

        public void intervalRemoved(ListDataEvent listDataEvent) {
            appendEvent(listDataEvent);
        }

        private void appendEvent(ListDataEvent listDataEvent) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            switch (listDataEvent.getType()) {
            case ListDataEvent.CONTENTS_CHANGED:
                pw.print("Type: Contents Changed");
                break;
            case ListDataEvent.INTERVAL_ADDED:
                pw.print("Type: Interval Added");
                break;
            case ListDataEvent.INTERVAL_REMOVED:
                pw.print("Type: Interval Removed");
                break;
            }
            pw.print(", Index0: " + listDataEvent.getIndex0());
            pw.print(", Index1: " + listDataEvent.getIndex1());
            DefaultListModel theModel = (DefaultListModel) listDataEvent.getSource();
            Enumeration elements = theModel.elements();
            pw.print(", Elements: ");
            while (elements.hasMoreElements()) {
                pw.print(elements.nextElement());
                pw.print(",");
            }
            pw.println();
            textArea.append(sw.toString());
        }
    };

    model.addListDataListener(listDataListener);

    // Setup buttons
    JPanel jp = new JPanel(new GridLayout(2, 1));
    JPanel jp1 = new JPanel(new FlowLayout(FlowLayout.CENTER, 1, 1));
    JPanel jp2 = new JPanel(new FlowLayout(FlowLayout.CENTER, 1, 1));
    jp.add(jp1);
    jp.add(jp2);
    JButton jb = new JButton("add F");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.add(0, "First");
        }
    });
    jb = new JButton("addElement L");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.addElement("Last");
        }
    });
    jb = new JButton("insertElementAt M");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            model.insertElementAt("Middle", size / 2);
        }
    });
    jb = new JButton("set F");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.set(0, "New First");
        }
    });
    jb = new JButton("setElementAt L");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.setElementAt("New Last", size - 1);
        }
    });
    jb = new JButton("load 10");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            for (int i = 0, n = labels.length; i < n; i++) {
                model.addElement(labels[i]);
            }
        }
    });
    jb = new JButton("clear");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.clear();
        }
    });
    jb = new JButton("remove F");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.remove(0);
        }
    });
    jb = new JButton("removeAllElements");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.removeAllElements();
        }
    });
    jb = new JButton("removeElement 'Last'");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.removeElement("Last");
        }
    });
    jb = new JButton("removeElementAt M");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.removeElementAt(size / 2);
        }
    });
    jb = new JButton("removeRange FM");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.removeRange(0, size / 2);
        }
    });
    contentPane.add(jp, BorderLayout.SOUTH);
    frame.setSize(640, 300);
    frame.setVisible(true);
}

From source file:NumericTextField.java

public static void main(String[] args) {
    try {//from   ww w  .  j  a  v  a 2s.  co m
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {
    }

    DecimalFormat format = new DecimalFormat("#,###.###");
    format.setGroupingUsed(true);
    format.setGroupingSize(3);
    format.setParseIntegerOnly(false);

    JFrame f = new JFrame("Numeric Text Field Example");
    final NumericTextField tf = new NumericTextField(10, format);

    tf.setValue((double) 123456.789);

    JLabel lbl = new JLabel("Type a number: ");
    f.getContentPane().add(tf, "East");
    f.getContentPane().add(lbl, "West");

    tf.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            try {
                tf.normalize();
                Long l = tf.getLongValue();
                System.out.println("Value is (Long)" + l);
            } catch (ParseException e1) {
                try {
                    Double d = tf.getDoubleValue();
                    System.out.println("Value is (Double)" + d);
                } catch (ParseException e2) {
                    System.out.println(e2);
                }
            }
        }
    });
    f.pack();
    f.setVisible(true);
}

From source file:DragDropTreeExample.java

public static void main(String[] args) {
    try {//from www. j a v a 2 s.c o m
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {
    }

    final JFrame f = new JFrame("FileTree Drop and Drop Example");
    try {
        final FileTree tree = new FileTree("D:\\");

        // Add a drop target to the FileTree
        FileTreeDropTarget target = new FileTreeDropTarget(tree);

        // Add a drag source to the FileTree
        FileTreeDragSource source = new FileTreeDragSource(tree);

        tree.setEditable(true);

        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent evt) {
                System.exit(0);
            }
        });

        JPanel panel = new JPanel();
        final JCheckBox editable = new JCheckBox("Editable");
        editable.setSelected(true);
        panel.add(editable);
        editable.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                tree.setEditable(editable.isSelected());
            }
        });

        final JCheckBox enabled = new JCheckBox("Enabled");
        enabled.setSelected(true);
        panel.add(enabled);
        enabled.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                tree.setEnabled(enabled.isSelected());
            }
        });

        f.getContentPane().add(new JScrollPane(tree), BorderLayout.CENTER);
        f.getContentPane().add(panel, BorderLayout.SOUTH);
        f.setSize(500, 400);
        f.setVisible(true);
    } catch (Exception e) {
        System.out.println("Failed to build GUI: " + e);
    }
}

From source file:ParenMatcher.java

public static void main(String[] args) {
    JFrame frame = new JFrame("ParenMatcher");

    final ParenMatcher matcher = new ParenMatcher();
    matcher.setText("int fact(int n) {\n" + "  if (n <= 1) return 1;\n" + "  return(n * fact(n-1));\n" + "}\n");
    frame.getContentPane().add(new JScrollPane(matcher), BorderLayout.CENTER);

    JButton matchButton = new JButton("match parens");
    matchButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            matcher.run();/*w  ww.  ja v a 2 s  .c o m*/
        }
    });
    frame.getContentPane().add(matchButton, BorderLayout.SOUTH);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200, 150);
    frame.setVisible(true);
}

From source file:SimpleMenu.java

/** A simple test program for the above code */
public static void main(String[] args) {
    // Get the locale: default, or specified on command-line
    Locale locale;/*w ww  .  j  a v a 2  s. com*/
    if (args.length == 2)
        locale = new Locale(args[0], args[1]);
    else
        locale = Locale.getDefault();

    // Get the resource bundle for that Locale. This will throw an
    // (unchecked) MissingResourceException if no bundle is found.
    ResourceBundle bundle = ResourceBundle.getBundle("com.davidflanagan.examples.i18n.Menus", locale);

    // Create a simple GUI window to display the menu with
    final JFrame f = new JFrame("SimpleMenu: " + // Window title
            locale.getDisplayName(Locale.getDefault()));
    JMenuBar menubar = new JMenuBar(); // Create a menubar.
    f.setJMenuBar(menubar); // Add menubar to window

    // Define an action listener for that our menu will use.
    ActionListener listener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String s = e.getActionCommand();
            Component c = f.getContentPane();
            if (s.equals("red"))
                c.setBackground(Color.red);
            else if (s.equals("green"))
                c.setBackground(Color.green);
            else if (s.equals("blue"))
                c.setBackground(Color.blue);
        }
    };

    // Now create a menu using our convenience routine with the resource
    // bundle and action listener we've created
    JMenu menu = SimpleMenu.create(bundle, "colors", new String[] { "red", "green", "blue" }, listener);

    // Finally add the menu to the GUI, and pop it up
    menubar.add(menu); // Add the menu to the menubar
    f.setSize(300, 150); // Set the window size.
    f.setVisible(true); // Pop the window up.
}

From source file:com.amazonaws.services.kinesis.leases.impl.LeaseCoordinatorExerciser.java

public static void main(String[] args) throws InterruptedException, DependencyException, InvalidStateException,
        ProvisionedThroughputException, IOException {

    int numCoordinators = 9;
    int numLeases = 73;
    int leaseDurationMillis = 10000;
    int epsilonMillis = 100;

    AWSCredentialsProvider creds = new DefaultAWSCredentialsProviderChain();
    AmazonDynamoDBClient ddb = new AmazonDynamoDBClient(creds);

    ILeaseManager<KinesisClientLease> leaseManager = new KinesisClientLeaseManager("nagl_ShardProgress", ddb);

    if (leaseManager.createLeaseTableIfNotExists(10L, 50L)) {
        LOG.info("Waiting for newly created lease table");
        if (!leaseManager.waitUntilLeaseTableExists(10, 300)) {
            LOG.error("Table was not created in time");
            return;
        }//www.  j  a v a 2 s .  com
    }

    CWMetricsFactory metricsFactory = new CWMetricsFactory(creds, "testNamespace", 30 * 1000, 1000);
    final List<LeaseCoordinator<KinesisClientLease>> coordinators = new ArrayList<LeaseCoordinator<KinesisClientLease>>();
    for (int i = 0; i < numCoordinators; i++) {
        String workerIdentifier = "worker-" + Integer.toString(i);

        LeaseCoordinator<KinesisClientLease> coord = new LeaseCoordinator<KinesisClientLease>(leaseManager,
                workerIdentifier, leaseDurationMillis, epsilonMillis, metricsFactory);

        coordinators.add(coord);
    }

    leaseManager.deleteAll();

    for (int i = 0; i < numLeases; i++) {
        KinesisClientLease lease = new KinesisClientLease();
        lease.setLeaseKey(Integer.toString(i));
        lease.setCheckpoint(new ExtendedSequenceNumber("checkpoint"));
        leaseManager.createLeaseIfNotExists(lease);
    }

    final JFrame frame = new JFrame("Test Visualizer");
    frame.setPreferredSize(new Dimension(800, 600));
    final JPanel panel = new JPanel(new GridLayout(coordinators.size() + 1, 0));
    final JLabel ticker = new JLabel("tick");
    panel.add(ticker);
    frame.getContentPane().add(panel);

    final Map<String, JLabel> labels = new HashMap<String, JLabel>();
    for (final LeaseCoordinator<KinesisClientLease> coord : coordinators) {
        JPanel coordPanel = new JPanel();
        coordPanel.setLayout(new BoxLayout(coordPanel, BoxLayout.X_AXIS));
        final Button button = new Button("Stop " + coord.getWorkerIdentifier());
        button.setMaximumSize(new Dimension(200, 50));
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                if (coord.isRunning()) {
                    coord.stop();
                    button.setLabel("Start " + coord.getWorkerIdentifier());
                } else {
                    try {
                        coord.start();
                    } catch (LeasingException e) {
                        LOG.error(e);
                    }
                    button.setLabel("Stop " + coord.getWorkerIdentifier());
                }
            }

        });
        coordPanel.add(button);

        JLabel label = new JLabel();
        coordPanel.add(label);
        labels.put(coord.getWorkerIdentifier(), label);
        panel.add(coordPanel);
    }

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    new Thread() {

        // Key is lease key, value is green-ness as a value from 0 to 255.
        // Great variable name, huh?
        private Map<String, Integer> greenNesses = new HashMap<String, Integer>();

        // Key is lease key, value is last owning worker
        private Map<String, String> lastOwners = new HashMap<String, String>();

        @Override
        public void run() {
            while (true) {
                for (LeaseCoordinator<KinesisClientLease> coord : coordinators) {
                    String workerIdentifier = coord.getWorkerIdentifier();

                    JLabel label = labels.get(workerIdentifier);

                    List<KinesisClientLease> asgn = new ArrayList<KinesisClientLease>(coord.getAssignments());
                    Collections.sort(asgn, new Comparator<KinesisClientLease>() {

                        @Override
                        public int compare(KinesisClientLease arg0, KinesisClientLease arg1) {
                            return arg0.getLeaseKey().compareTo(arg1.getLeaseKey());
                        }

                    });

                    StringBuilder builder = new StringBuilder();
                    builder.append("<html>");
                    builder.append(workerIdentifier).append(":").append(asgn.size()).append("          ");

                    for (KinesisClientLease lease : asgn) {
                        String leaseKey = lease.getLeaseKey();
                        String lastOwner = lastOwners.get(leaseKey);

                        // Color things green when they switch owners, decay the green-ness over time.
                        Integer greenNess = greenNesses.get(leaseKey);
                        if (greenNess == null || lastOwner == null
                                || !lastOwner.equals(lease.getLeaseOwner())) {
                            greenNess = 200;
                        } else {
                            greenNess = Math.max(0, greenNess - 20);
                        }
                        greenNesses.put(leaseKey, greenNess);
                        lastOwners.put(leaseKey, lease.getLeaseOwner());

                        builder.append(String.format("<font color=\"%s\">%03d</font>",
                                String.format("#00%02x00", greenNess), Integer.parseInt(leaseKey))).append(" ");
                    }
                    builder.append("</html>");

                    label.setText(builder.toString());
                    label.revalidate();
                    label.repaint();
                }

                if (ticker.getText().equals("tick")) {
                    ticker.setText("tock");
                } else {
                    ticker.setText("tick");
                }

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                }
            }
        }

    }.start();

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

    for (LeaseCoordinator<KinesisClientLease> coord : coordinators) {
        coord.start();
    }
}

From source file:Graph_with_jframe_and_arduino.java

public static void main(String[] args) {

    // create and configure the window
    JFrame window = new JFrame();
    window.setTitle("Sensor Graph GUI");
    window.setSize(600, 400);/*from w  ww  .  j a v  a2s. c o m*/
    window.setLayout(new BorderLayout());
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // create a drop-down box and connect button, then place them at the top of the window
    JComboBox<String> portList_combobox = new JComboBox<String>();
    Dimension d = new Dimension(300, 100);
    portList_combobox.setSize(d);
    JButton connectButton = new JButton("Connect");
    JPanel topPanel = new JPanel();
    topPanel.add(portList_combobox);
    topPanel.add(connectButton);
    window.add(topPanel, BorderLayout.NORTH);
    //pause button
    JButton Pause_btn = new JButton("Start");

    // populate the drop-down box
    SerialPort[] portNames;
    portNames = SerialPort.getCommPorts();
    //check for new port available
    Thread thread_port = new Thread() {
        @Override
        public void run() {
            while (true) {
                SerialPort[] sp = SerialPort.getCommPorts();
                if (sp.length > 0) {
                    for (SerialPort sp_name : sp) {
                        int l = portList_combobox.getItemCount(), i;
                        for (i = 0; i < l; i++) {
                            //check port name already exist or not
                            if (sp_name.getSystemPortName().equalsIgnoreCase(portList_combobox.getItemAt(i))) {
                                break;
                            }
                        }
                        if (i == l) {
                            portList_combobox.addItem(sp_name.getSystemPortName());
                        }

                    }

                } else {
                    portList_combobox.removeAllItems();

                }
                portList_combobox.repaint();

            }

        }

    };
    thread_port.start();
    for (SerialPort sp_name : portNames)
        portList_combobox.addItem(sp_name.getSystemPortName());

    //for(int i = 0; i < portNames.length; i++)
    //   portList.addItem(portNames[i].getSystemPortName());

    // create the line graph
    XYSeries series = new XYSeries("line 1");
    XYSeries series2 = new XYSeries("line 2");
    XYSeries series3 = new XYSeries("line 3");
    XYSeries series4 = new XYSeries("line 4");
    for (int i = 0; i < 100; i++) {
        series.add(x, 0);
        series2.add(x, 0);
        series3.add(x, 0);
        series4.add(x, 10);
        x++;
    }

    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(series);
    dataset.addSeries(series2);
    XYSeriesCollection dataset2 = new XYSeriesCollection();
    dataset2.addSeries(series3);
    dataset2.addSeries(series4);

    //create jfree chart
    JFreeChart chart = ChartFactory.createXYLineChart("Sensor Readings", "Time (seconds)", "Arduino Reading",
            dataset);
    JFreeChart chart2 = ChartFactory.createXYLineChart("Sensor Readings", "Time (seconds)", "Arduino Reading 2",
            dataset2);

    //color render for chart 1
    XYLineAndShapeRenderer r1 = new XYLineAndShapeRenderer();
    r1.setSeriesPaint(0, Color.RED);
    r1.setSeriesPaint(1, Color.GREEN);
    r1.setSeriesShapesVisible(0, false);
    r1.setSeriesShapesVisible(1, false);

    XYPlot plot = chart.getXYPlot();
    plot.setRenderer(0, r1);
    plot.setRenderer(1, r1);

    plot.setBackgroundPaint(Color.WHITE);
    plot.setDomainGridlinePaint(Color.DARK_GRAY);
    plot.setRangeGridlinePaint(Color.blue);

    //color render for chart 2
    XYLineAndShapeRenderer r2 = new XYLineAndShapeRenderer();
    r2.setSeriesPaint(0, Color.BLUE);
    r2.setSeriesPaint(1, Color.ORANGE);
    r2.setSeriesShapesVisible(0, false);
    r2.setSeriesShapesVisible(1, false);

    XYPlot plot2 = chart2.getXYPlot();
    plot2.setRenderer(0, r2);
    plot2.setRenderer(1, r2);

    ChartPanel cp = new ChartPanel(chart);
    ChartPanel cp2 = new ChartPanel(chart2);

    //multiple graph container
    JPanel graph_container = new JPanel();
    graph_container.setLayout(new BoxLayout(graph_container, BoxLayout.X_AXIS));
    graph_container.add(cp);
    graph_container.add(cp2);

    //add chart panel in main window
    window.add(graph_container, BorderLayout.CENTER);
    //window.add(cp2, BorderLayout.WEST);

    window.add(Pause_btn, BorderLayout.AFTER_LAST_LINE);
    Pause_btn.setEnabled(false);
    //pause btn action
    Pause_btn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (Pause_btn.getText().equalsIgnoreCase("Pause")) {

                if (chosenPort.isOpen()) {
                    try {
                        Output.write(0);
                    } catch (IOException ex) {
                        Logger.getLogger(Graph_with_jframe_and_arduino.class.getName()).log(Level.SEVERE, null,
                                ex);
                    }
                }

                Pause_btn.setText("Start");
            } else {
                if (chosenPort.isOpen()) {
                    try {
                        Output.write(1);
                    } catch (IOException ex) {
                        Logger.getLogger(Graph_with_jframe_and_arduino.class.getName()).log(Level.SEVERE, null,
                                ex);
                    }
                }

                Pause_btn.setText("Pause");
            }
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    });

    // configure the connect button and use another thread to listen for data
    connectButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            if (connectButton.getText().equals("Connect")) {
                // attempt to connect to the serial port
                chosenPort = SerialPort.getCommPort(portList_combobox.getSelectedItem().toString());
                chosenPort.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
                if (chosenPort.openPort()) {
                    Output = chosenPort.getOutputStream();
                    connectButton.setText("Disconnect");
                    Pause_btn.setEnabled(true);
                    portList_combobox.setEnabled(false);
                }

                // create a new thread that listens for incoming text and populates the graph
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        Scanner scanner = new Scanner(chosenPort.getInputStream());
                        while (scanner.hasNextLine()) {
                            try {
                                String line = scanner.nextLine();
                                int number = Integer.parseInt(line);
                                series.add(x, number);
                                series2.add(x, number / 2);
                                series3.add(x, number / 1.5);
                                series4.add(x, number / 5);

                                if (x > 100) {
                                    series.remove(0);
                                    series2.remove(0);
                                    series3.remove(0);
                                    series4.remove(0);
                                }

                                x++;
                                window.repaint();
                            } catch (Exception e) {
                            }
                        }
                        scanner.close();
                    }
                };
                thread.start();
            } else {
                // disconnect from the serial port
                chosenPort.closePort();
                portList_combobox.setEnabled(true);
                Pause_btn.setEnabled(false);
                connectButton.setText("Connect");

            }
        }
    });

    // show the window
    window.setVisible(true);
}