Example usage for java.awt Button addActionListener

List of usage examples for java.awt Button addActionListener

Introduction

In this page you can find the example usage for java.awt Button addActionListener.

Prototype

public synchronized void addActionListener(ActionListener l) 

Source Link

Document

Adds the specified action listener to receive action events from this button.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gs = ge.getDefaultScreenDevice();

    Button btn = new Button("OK");
    btn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            gs.setFullScreenWindow(null);
        }//from  w ww.j  a v a2  s.c  o m
    });
    Frame frame = new Frame(gs.getDefaultConfiguration());
    Window win = new Window(frame);
    win.add(btn, BorderLayout.CENTER);
    try {
        gs.setFullScreenWindow(win);
        win.validate();
    } finally {
        gs.setFullScreenWindow(null);
    }
}

From source file:MediumPopupMenuSample.java

public static void main(String args[]) {
    // Define ActionListener
    ActionListener aListener = new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            System.out.println("Selected: " + event.getActionCommand());
        }/*  w  ww  .  j  a va  2 s. c o m*/
    };

    // Define PopupMenuListener
    PopupMenuListener pListener = new PopupMenuListener() {
        public void popupMenuCanceled(PopupMenuEvent event) {
            System.out.println("Canceled");
        }

        public void popupMenuWillBecomeInvisible(PopupMenuEvent event) {
            System.out.println("Becoming Invisible");
        }

        public void popupMenuWillBecomeVisible(PopupMenuEvent event) {
            System.out.println("Becoming Visible");
        }
    };

    // Define
    JFrame frame = new JFrame("Popup Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPopupMenu.setDefaultLightWeightPopupEnabled(false);

    // Create popup menu, attach popup menu listener
    final JPopupMenu popupMenu = new JPopupMenu();
    popupMenu.addPopupMenuListener(pListener);

    // Cut
    JMenuItem cutItem = new JMenuItem("Cut");
    cutItem.addActionListener(aListener);
    popupMenu.add(cutItem);

    // Copy
    JMenuItem copyItem = new JMenuItem("Copy");
    copyItem.addActionListener(aListener);
    popupMenu.add(copyItem);

    // Paste
    JMenuItem pasteItem = new JMenuItem("Paste");
    pasteItem.addActionListener(aListener);
    pasteItem.setEnabled(false);
    popupMenu.add(pasteItem);

    // Separator
    popupMenu.addSeparator();

    // Find
    JMenuItem findItem = new JMenuItem("Find");
    findItem.addActionListener(aListener);
    popupMenu.add(findItem);

    // Enable showing
    MouseListener mouseListener = new JPopupMenuShower(popupMenu);
    frame.addMouseListener(mouseListener);

    Button button = new Button("Label");
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println(popupMenu.isLightWeightPopupEnabled());
        }
    });
    frame.getContentPane().add(button, BorderLayout.SOUTH);

    frame.setSize(350, 250);
    frame.setVisible(true);
}

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;
        }//  ww  w.  j  a  v  a  2s . c  o m
    }

    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:MainClass.java

MainClass() {
    super("MainClass");
    setSize(200, 200);//from  w  w w  . j  av  a2  s  .c o m

    fc = new FileDialog(this, "Choose a file", FileDialog.LOAD);
    fc.setDirectory("C:\\");

    Button b;
    add(b = new Button("Browse...")); // Create and add a Button
    b.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            fc.setVisible(true);
            String fn = fc.getFile();
            if (fn == null)
                System.out.println("You cancelled the choice");
            else
                System.out.println("You chose " + fn);
        }
    });
}

From source file:GetApplets.java

public void init() {
    Button b = new Button("Click to call getApplets()");
    b.addActionListener(this);

    setLayout(new BorderLayout());
    add("North", b);

    textArea = new TextArea(5, 40);
    textArea.setEditable(false);/*from w w w . j  a v a  2s. c  o m*/
    add("Center", textArea);

    newline = System.getProperty("line.separator");
}

From source file:ShowDocApplet.java

/** Initialize the Applet */
public void init() {
    setBackground(Color.gray);/*from  w  w  w.jav a 2 s  .  c o m*/
    try {
        targetURL = new URL(targetString);
    } catch (MalformedURLException mfu) {
        throw new IllegalArgumentException("ShowDocApplet got bad URL " + targetString);
    }
    Button b = new Button("View Secret");
    add(b);
    b.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            getAppletContext().showDocument(targetURL);
        }
    });
}

From source file:MainClass.java

public void init() {
    System.out.println("Code base = " + getCodeBase());
    System.out.println("Document base = " + getDocumentBase());

    System.out.println("\ninit () called");
    System.out.println("isActive () returns " + isActive());

    Button b = new Button("Visit www.java2s.com");
    b.addActionListener(this);
    add(b);/*from w w w . j av  a2  s . c o  m*/

    b = new Button("Audio");
    b.addActionListener(this);
    add(b);

    String imageName = getParameter("image");

    if (imageName != null)
        im = getImage(getCodeBase(), imageName);
}

From source file:FileViewer.java

/**
 * The real constructor. Create a FileViewer object to display the specified
 * file from the specified directory//  ww w  .  j  ava2s . com
 */
public FileViewer(String directory, String filename) {
    super(); // Create the frame

    // Destroy the window when the user requests it
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            dispose();
        }
    });

    // Create a TextArea to display the contents of the file in
    textarea = new TextArea("", 24, 80);
    textarea.setFont(new Font("MonoSpaced", Font.PLAIN, 12));
    textarea.setEditable(false);
    this.add("Center", textarea);

    // Create a bottom panel to hold a couple of buttons in
    Panel p = new Panel();
    p.setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 5));
    this.add(p, "South");

    // Create the buttons and arrange to handle button clicks
    Font font = new Font("SansSerif", Font.BOLD, 14);
    Button openfile = new Button("Open File");
    Button close = new Button("Close");
    openfile.addActionListener(this);
    openfile.setActionCommand("open");
    openfile.setFont(font);
    close.addActionListener(this);
    close.setActionCommand("close");
    close.setFont(font);
    p.add(openfile);
    p.add(close);

    this.pack();

    // Figure out the directory, from filename or current dir, if necessary
    if (directory == null) {
        File f;
        if ((filename != null) && (f = new File(filename)).isAbsolute()) {
            directory = f.getParent();
            filename = f.getName();
        } else
            directory = System.getProperty("user.dir");
    }

    this.directory = directory; // Remember the directory, for FileDialog
    setFile(directory, filename); // Now load and display the file
}

From source file:PrintFromButton.java

public void init() {
    setLayout(new BorderLayout());
    GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();

    BufferedImage bImage = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB);

    ImageComponent2D buffer = new ImageComponent2D(ImageComponent.FORMAT_RGBA, bImage);
    buffer.setCapability(ImageComponent2D.ALLOW_IMAGE_READ);

    Raster drawRaster = new Raster(new Point3f(0.0f, 0.0f, 0.0f), Raster.RASTER_COLOR, 0, 0, 200, 200, buffer,
            null);//from   w ww . java2s  .  c o m

    drawRaster.setCapability(Raster.ALLOW_IMAGE_WRITE);

    // create the main scene graph
    BranchGroup scene = createSceneGraph(drawRaster);

    // create the on-screen canvas
    Canvas3D d = new Canvas3D(config, false);
    add("Center", d);

    // create a simple universe
    u = new SimpleUniverse(d);

    // This will move the ViewPlatform back a bit so the
    // objects in the scene can be viewed.
    u.getViewingPlatform().setNominalViewingTransform();

    // create an off Screen Buffer

    c = new OffScreenCanvas3D(config, true, drawRaster);

    // set the offscreen to match the onscreen
    Screen3D sOn = d.getScreen3D();
    Screen3D sOff = c.getScreen3D();
    sOff.setSize(sOn.getSize());
    sOff.setPhysicalScreenWidth(sOn.getPhysicalScreenWidth());
    sOff.setPhysicalScreenHeight(sOn.getPhysicalScreenHeight());

    // attach the same view to the offscreen canvas
    u.getViewer().getView().addCanvas3D(c);

    // create the gui
    Button b = new Button("Print");
    b.addActionListener(this);
    Panel p = new Panel();
    p.add(b);
    add("North", p);

    u.addBranchGraph(scene);
}

From source file:MultipartViewer.java

protected void setupDisplay(Multipart mp) {
    // we display the first body part in a main frame on the left, and then
    // on the right we display the rest of the parts as attachments

    GridBagConstraints gc = new GridBagConstraints();
    gc.gridheight = GridBagConstraints.REMAINDER;
    gc.fill = GridBagConstraints.BOTH;
    gc.weightx = 1.0;//from  ww  w  . j a v a2s. c o  m
    gc.weighty = 1.0;

    // get the first part
    try {
        BodyPart bp = mp.getBodyPart(0);
        Component comp = getComponent(bp);
        add(comp, gc);

    } catch (MessagingException me) {
        add(new Label(me.toString()), gc);
    }

    // see if there are more than one parts
    try {
        int count = mp.getCount();

        // setup how to display them
        gc.gridwidth = GridBagConstraints.REMAINDER;
        gc.gridheight = 1;
        gc.fill = GridBagConstraints.NONE;
        gc.anchor = GridBagConstraints.NORTH;
        gc.weightx = 0.0;
        gc.weighty = 0.0;
        gc.insets = new Insets(4, 4, 4, 4);

        // for each one we create a button with the content type
        for (int i = 1; i < count; i++) { // we skip the first one 
            BodyPart curr = mp.getBodyPart(i);
            String label = null;
            if (label == null)
                label = curr.getFileName();
            if (label == null)
                label = curr.getDescription();
            if (label == null)
                label = curr.getContentType();

            Button but = new Button(label);
            but.addActionListener(new AttachmentViewer(curr));
            add(but, gc);
        }

    } catch (MessagingException me2) {
        me2.printStackTrace();
    }

}