Example usage for javax.swing JLabel JLabel

List of usage examples for javax.swing JLabel JLabel

Introduction

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

Prototype

public JLabel(Icon image) 

Source Link

Document

Creates a JLabel instance with the specified image.

Usage

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;
        }/*from www  .jav  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:CombinationFormatter.java

public static void main(String argv[]) {
    // a demo main() to show how CombinationFormatter could be used
    int comb1[] = { 35, 11, 19 };
    int comb2[] = { 10, 20, 30 };

    final JFormattedTextField field1 = new JFormattedTextField(new CombinationFormatter());
    field1.setValue(comb1);/*from  w w  w .j  a  v  a  2s  . co  m*/

    final JFormattedTextField field2 = new JFormattedTextField(new CombinationFormatter());
    field2.setValue(comb2);

    JPanel pan = new JPanel();
    pan.add(new JLabel("Change the combination from"));
    pan.add(field1);
    pan.add(new JLabel("to"));
    pan.add(field2);

    JButton b = new JButton("Submit");
    b.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent ae) {
            try {
                field1.commitEdit(); // make sure current edit (if any) gets
                // committed
                field2.commitEdit();
            } catch (java.text.ParseException pe) {
            }
            int oldc[] = (int[]) field1.getValue();
            int newc[] = (int[]) field2.getValue();
            //
            // code to validate oldc[] and change to newc[] goes here
            //
        }
    });
    pan.add(b);

    JFrame f = new JFrame("CombinationFormatter Demo");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setContentPane(pan);
    f.setSize(360, 100);
    f.setVisible(true);
}

From source file:ComponentTree.java

/**
 * This main() method demonstrates the use of the ComponentTree class: it
 * puts a ComponentTree component in a Frame, and uses the ComponentTree to
 * display its own GUI hierarchy. It also adds a TreeSelectionListener to
 * display additional information about each component as it is selected
 */// www  . ja  va  2s  . co  m
public static void main(String[] args) {
    // Create a frame for the demo, and handle window close requests
    JFrame frame = new JFrame("ComponentTree Demo");
    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });

    // Create a scroll pane and a "message line" and add them to the
    // center and bottom of the frame.
    JScrollPane scrollpane = new JScrollPane();
    final JLabel msgline = new JLabel(" ");
    frame.getContentPane().add(scrollpane, BorderLayout.CENTER);
    frame.getContentPane().add(msgline, BorderLayout.SOUTH);

    // Now create the ComponentTree object, specifying the frame as the
    // component whose tree is to be displayed. Also set the tree's font.
    JTree tree = new ComponentTree(frame);
    tree.setFont(new Font("SansSerif", Font.BOLD, 12));

    // Only allow a single item in the tree to be selected at once
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

    // Add an event listener for notifications when
    // the tree selection state changes.
    tree.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent e) {
            // Tree selections are referred to by "path"
            // We only care about the last node in the path
            TreePath path = e.getPath();
            Component c = (Component) path.getLastPathComponent();
            // Now we know what component was selected, so
            // display some information about it in the message line
            if (c.isShowing()) {
                Point p = c.getLocationOnScreen();
                msgline.setText("x: " + p.x + "  y: " + p.y + "  width: " + c.getWidth() + "  height: "
                        + c.getHeight());
            } else {
                msgline.setText("component is not showing");
            }
        }
    });

    // Now that we've set up the tree, add it to the scrollpane
    scrollpane.setViewportView(tree);

    // Finally, set the size of the main window, and pop it up.
    frame.setSize(600, 400);
    frame.setVisible(true);
}

From source file:de.codesourcery.geoip.Main.java

public static void main(String[] args) throws Exception {
    final IGeoLocator<StringSubject> locator = createGeoLocator();

    final JFrame frame = new JFrame("GeoIP");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(java.awt.event.WindowEvent e) {
            try {
                locator.dispose();//from   w w  w.  j  a  v a2s  .  c  o  m
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        };
    });

    final MapImage image = MapImage.getRobinsonWorldMap(); // MapImage.getMillerWorldMap();      
    final MapCanvas canvas = new MapCanvas(image);

    for (GeoLocation<StringSubject> loc : locator.locate(getSpammers())) {
        if (loc.hasValidCoordinates()) {
            canvas.addCoordinate(PointRenderer.createPoint(loc, Color.YELLOW));
        }
    }

    //      canvas.addCoordinate( PointRenderer.createPoint( ZERO , Color.YELLOW ) );
    //      canvas.addCoordinate( PointRenderer.createPoint( WELLINGTON , Color.RED ) );
    //      canvas.addCoordinate( PointRenderer.createPoint( MELBOURNE , Color.RED ) );
    //      canvas.addCoordinate( PointRenderer.createPoint( HAMBURG , Color.RED ) );

    final double heightToWidth = image.height() / (double) image.width(); // preserve aspect ratio of map
    canvas.setPreferredSize(new Dimension(640, (int) Math.round(640 * heightToWidth)));

    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());

    panel.add(new JLabel("Scale-X"));
    final JTextField scaleX = new JTextField(Double.toString(image.getScaleX()));
    scaleX.setColumns(5);

    final JTextField scaleY = new JTextField(Double.toString(image.getScaleY()));
    scaleY.setColumns(5);

    final ActionListener listener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            double x = Double.parseDouble(scaleX.getText());
            double y = Double.parseDouble(scaleY.getText());
            image.setScale(x, y);
            canvas.repaint();
        }
    };
    scaleX.addActionListener(listener);
    scaleY.addActionListener(listener);

    panel.add(new JLabel("Scale-X"));
    panel.add(scaleX);

    panel.add(new JLabel("Scale-Y"));
    panel.add(scaleY);

    final JTextField ipAddress = new JTextField("www.kickstarter.com");
    ipAddress.setColumns(20);

    final ActionListener ipListener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final String destinationIP = ipAddress.getText();
            if (StringUtils.isBlank(destinationIP)) {
                return;
            }

            /*
             * Perform traceroute.
             */
            final List<String> hops;
            try {
                if (TracePath.isPathTracingAvailable()) {
                    hops = TracePath.trace(destinationIP);
                } else {
                    System.err.println("tracepath not available.");
                    if (TracePath.isValidAddress(destinationIP)) {
                        hops = new ArrayList<>();
                        hops.add(destinationIP);
                    } else {
                        System.err.println(destinationIP + " is no valid IP");
                        return;
                    }
                }
            } catch (Exception ex) {
                System.err.println("Failed to trace " + destinationIP);
                ex.printStackTrace();
                return;
            }

            System.out.println("Trace contains " + hops.size() + " IPs");

            /*
             * Gather locations.
             */
            final List<StringSubject> subjects = new ArrayList<>();
            for (String ip : hops) {
                subjects.add(new StringSubject(ip));
            }

            final List<GeoLocation<StringSubject>> locations;
            try {
                long time = -System.currentTimeMillis();
                locations = locator.locate(subjects);
                time += System.currentTimeMillis();

                System.out.println("Locating hops for " + destinationIP + " returned " + locations.size()
                        + " valid locations ( time: " + time + " ms)");
                System.out.flush();

            } catch (Exception e2) {
                e2.printStackTrace();
                return;
            }

            /*
             * Weed-out invalid/unknown locations.
             */
            {
                GeoLocation<StringSubject> previous = null;
                for (Iterator<GeoLocation<StringSubject>> it = locations.iterator(); it.hasNext();) {
                    final GeoLocation<StringSubject> location = it.next();
                    if (!location.hasValidCoordinates()
                            || (previous != null && previous.coordinate().equals(location.coordinate()))) {
                        it.remove();
                        System.err.println("Ignoring invalid/duplicate location for " + location);
                    } else {
                        previous = location;
                    }
                }
            }

            /*
             * Populate chart.
             */

            System.out.println("Adding " + locations.size() + " hops to chart");
            System.out.flush();

            canvas.removeAllCoordinates();

            if (locations.size() == 1) {
                canvas.addCoordinate(
                        PointRenderer.createPoint(locations.get(0), getLabel(locations.get(0)), Color.BLACK));
            } else if (locations.size() > 1) {
                GeoLocation<StringSubject> previous = locations.get(0);
                MapPoint previousPoint = PointRenderer.createPoint(previous, getLabel(previous), Color.BLACK);
                final int len = locations.size();
                for (int i = 1; i < len; i++) {
                    final GeoLocation<StringSubject> current = locations.get(i);
                    //                  final MapPoint currentPoint = PointRenderer.createPoint( current , getLabel( current ) , Color.BLACK );
                    final MapPoint currentPoint = PointRenderer.createPoint(current, Color.BLACK);

                    //                  canvas.addCoordinate( LineRenderer.createLine( previousPoint , currentPoint , Color.RED ) );
                    canvas.addCoordinate(CurvedLineRenderer.createLine(previousPoint, currentPoint, Color.RED));

                    previous = locations.get(i);
                    previousPoint = currentPoint;
                }
            }
            System.out.println("Finished adding");
            System.out.flush();
            canvas.repaint();
        }
    };
    ipAddress.addActionListener(ipListener);

    panel.add(new JLabel("IP"));
    panel.add(ipAddress);

    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(panel, BorderLayout.NORTH);
    frame.getContentPane().add(canvas, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
}

From source file:SaveImage.java

public static void main(String s[]) {
    JFrame f = new JFrame("Save Image Sample");
    f.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);/*from ww  w  . j  a  va2s  .  co m*/
        }
    });
    SaveImage si = new SaveImage();
    f.add("Center", si);
    JComboBox choices = new JComboBox(si.getDescriptions());
    choices.setActionCommand("SetFilter");
    choices.addActionListener(si);
    JComboBox formats = new JComboBox(si.getFormats());
    formats.setActionCommand("Formats");
    formats.addActionListener(si);
    JPanel panel = new JPanel();
    panel.add(choices);
    panel.add(new JLabel("Save As"));
    panel.add(formats);
    f.add("South", panel);
    f.pack();
    f.setVisible(true);
}

From source file:Main.java

public static JLabel newJLabel(String label) {
    JLabel ret = new JLabel(label);
    ret.setHorizontalAlignment(SwingConstants.RIGHT);
    return ret;//from  ww w.j  a  v a 2  s  . co m
}

From source file:Main.java

static Component newLabel(String text) {
    return new JLabel(text);
}

From source file:MainClass.java

static void addIt(JTabbedPane tabbedPane, String text) {
    JLabel label = new JLabel(text);
    JButton button = new JButton(text);
    JPanel panel = new JPanel();
    panel.add(label);//from  w  w w  . j a  v  a 2 s.c  om
    panel.add(button);
    tabbedPane.addTab(text, panel);
}

From source file:Main.java

private static JSpinner addLabeledSpinner(String label, SpinnerModel model, boolean b) {
    JLabel l = new JLabel(label);
    //c.add(l);/*from   ww w. j  av a 2 s  . co m*/

    JSpinner spinner = new JSpinner(model);
    l.setLabelFor(spinner);
    //c.add(spinner);

    return spinner;
}

From source file:GridLayoutDemo.java

private static JComponent createComponent(String s) {
    JLabel l = new JLabel(s);
    l.setBorder(BorderFactory.createMatteBorder(5, 5, 5, 5, Color.DARK_GRAY));
    l.setHorizontalAlignment(JLabel.CENTER);
    return l;//w w w  .  ja  v  a2s .  c  o  m
}