Example usage for java.awt Frame setLocation

List of usage examples for java.awt Frame setLocation

Introduction

In this page you can find the example usage for java.awt Frame setLocation.

Prototype

@Override
public void setLocation(int x, int y) 

Source Link

Document

The method changes the geometry-related data.

Usage

From source file:gdsc.smlm.ij.plugins.pcpalm.PCPALMAnalysis.java

/**
 * Perform the PC Analysis/*from  www  . j  a v a2s .  c  o  m*/
 * 
 * @param molecules
 */
private void analyse(ArrayList<Molecule> molecules) {
    // Check if the plots are currently shown
    String spatialPlotTitle = TITLE + " molecules/um^2";
    String frequencyDomainTitle = TITLE + " g(r)";

    boolean noPlots;
    String topPlotTitle;

    long start = System.nanoTime();
    if (spatialDomain) {
        // -----------------
        // Analysis in the spatial domain
        // -----------------

        log("---");
        log("Spatial domain analysis");
        log("Computing density histogram");

        // Compute all-vs-all distance matrix.
        // Create histogram of distances at different radii.
        final int nBins = (int) (correlationDistance / correlationInterval) + 1;
        final double maxDistance2 = correlationDistance * correlationDistance;
        int[] H = new int[nBins];

        // TODO - Update this using a grid with a resolution of maxDistance to increase speed
        // by only comparing to neighbours within range.

        // An all-vs-all analysis does not account for a border. 
        // A simple solution is to only process molecules within the border but compare them 
        // to all molecules within the region. Thus every molecule has a complete circle of the max 
        // radius around them to use:
        // ----------------------
        // |                    |
        // |   --------------   |
        // |   |  Within    |   |
        // |   |  Border    |   |
        // |   |            |   |
        // |   --------------   |
        // |      Region        |
        // ----------------------
        // If the fraction of points within the correlation distance of the edge is low then this 
        // will not make much difference. 

        final double boundaryMinx = (useBorder) ? minx + correlationDistance : minx;
        final double boundaryMaxx = (useBorder) ? maxx - correlationDistance : maxx;
        final double boundaryMiny = (useBorder) ? miny + correlationDistance : miny;
        final double boundaryMaxy = (useBorder) ? maxy - correlationDistance : maxy;

        int N = 0;
        if (boundaryMaxx <= boundaryMinx || boundaryMaxy <= boundaryMiny) {
            log("ERROR: 'Use border' option of %s nm is not possible: Width = %s nm, Height = %s nm",
                    Utils.rounded(correlationDistance, 4), Utils.rounded(maxx - minx, 3),
                    Utils.rounded(maxy - miny, 3));
            return;
        } else {
            for (int i = molecules.size(); i-- > 0;) {
                final Molecule m = molecules.get(i);
                // Optionally ignore molecules that are near the edge of the boundary
                if (useBorder && (m.x < boundaryMinx || m.x > boundaryMaxx || m.y < boundaryMiny
                        || m.y > boundaryMaxy))
                    continue;
                N++;

                for (int j = molecules.size(); j-- > 0;) {
                    if (i == j)
                        continue;

                    double d = m.distance2(molecules.get(j));
                    if (d < maxDistance2) {
                        H[(int) (Math.sqrt(d) / correlationInterval)]++;
                    }
                }
            }
        }

        double[] r = new double[nBins + 1];
        for (int i = 0; i <= nBins; i++)
            r[i] = i * correlationInterval;
        double[] pcf = new double[nBins];
        if (N > 0) {
            // Note: Convert nm^2 to um^2
            final double N_pi = N * Math.PI / 1000000.0;
            for (int i = 0; i < nBins; i++) {
                // Pair-correlation is the count at the given distance divided by N and the area at distance ri:
                // H(r_i) / (N x (pi x (r_i+1)^2 - pi x r_i^2))
                pcf[i] = H[i] / (N_pi * (r[i + 1] * r[i + 1] - r[i] * r[i]));
            }
        }

        // The final bin may be empty if the correlation interval was a factor of the correlation distance
        if (pcf[pcf.length - 1] == 0) {
            r = Arrays.copyOf(r, nBins - 1);
            pcf = Arrays.copyOf(pcf, nBins - 1);
        } else {
            r = Arrays.copyOf(r, nBins);
        }

        double[][] gr = new double[][] { r, pcf, null };

        CorrelationResult result = new CorrelationResult(results.size() + 1,
                PCPALMMolecules.results.getSource(), boundaryMinx, boundaryMiny, boundaryMaxx, boundaryMaxy, N,
                correlationInterval, 0, false, gr, true);
        results.add(result);

        noPlots = WindowManager.getFrame(spatialPlotTitle) == null;
        topPlotTitle = frequencyDomainTitle;

        plotCorrelation(gr, 0, spatialPlotTitle, "molecules/um^2", true, false);
    } else {
        // -----------------
        // Image correlation in the Frequency Domain
        // -----------------
        log("Frequency domain analysis");

        // Create a binary image for the molecules

        ImageProcessor im = PCPALMMolecules.drawImage(molecules, minx, miny, maxx, maxy, nmPerPixel, true,
                binaryImage);
        log("Image scale = %.2f nm/pixel : %d x %d pixels", nmPerPixel, im.getWidth(), im.getHeight());

        // Apply a window function to the image to reduce FFT edge artifacts.
        if (applyWindow) {
            im = applyWindow(im, imageWindow);
        }

        if (showHighResolutionImage) {
            PCPALMMolecules.displayImage(PCPALMMolecules.results.getName() + " "
                    + ((binaryImage) ? "Binary" : "Count") + " Image (high res)", im, nmPerPixel);
        }

        // Create weight image (including windowing)
        ImageProcessor w = createWeightImage(im, applyWindow);

        // Store the area of the image in um^2
        weightedAreaInPx = areaInPx = im.getWidth() * im.getHeight();
        if (applyWindow) {
            weightedAreaInPx *= w.getStatistics().mean;
        }
        area = areaInPx * nmPerPixel * nmPerPixel / 1e6;
        weightedArea = weightedAreaInPx * nmPerPixel * nmPerPixel / 1e6;
        noOfMolecules = molecules.size();

        // Pad the images to the largest scale being investigated by the correlation function.
        // Original Sengupta paper uses 800nm for the padding size.
        // Limit to within 80% of the minimum dimension of the image.
        double maxRadius = correlationDistance / nmPerPixel;
        int imageSize = FastMath.min(im.getWidth(), im.getHeight());
        if (imageSize < 1.25 * maxRadius)
            maxRadius = imageSize / 1.25;
        int pad = (int) Math.round(maxRadius);
        log("Analysing up to %.0f nm = %d pixels", maxRadius * nmPerPixel, pad);
        im = padImage(im, pad);
        w = padImage(w, pad);

        //      // Used for debugging
        //      {
        //         ImageProcessor w2 = w.duplicate();
        //         w2.setMinAndMax(0, 1);
        //         PCPALMMolecules.displayImage(PCPALMMolecules.results.getName() + " Binary Image Mask", w2, nmPerPixel);
        //      }

        final double peakDensity = getDensity(im);

        // Create 2D auto-correlation
        double[][] gr;
        try {
            // Use the FFT library as it is multi-threaded. This may not be in the user's path.
            gr = computeAutoCorrelationCurveFFT(im, w, pad, nmPerPixel, peakDensity);
        } catch (Exception e) {
            // Default to the ImageJ built-in FHT
            gr = computeAutoCorrelationCurveFHT(im, w, pad, nmPerPixel, peakDensity);
        }
        if (gr == null)
            return;

        // Add the g(r) curve to the results
        addResult(peakDensity, gr);

        noPlots = WindowManager.getFrame(frequencyDomainTitle) == null;
        topPlotTitle = spatialPlotTitle;

        // Do not plot r=0 value on the curve
        plotCorrelation(gr, 1, frequencyDomainTitle, "g(r)", false, showErrorBars);
    }

    if (noPlots) {
        // Position the plot underneath the other one
        Frame f1 = WindowManager.getFrame(topPlotTitle);
        if (f1 != null) {
            String bottomPlotTitle = (topPlotTitle.equals(spatialPlotTitle) ? frequencyDomainTitle
                    : spatialPlotTitle);
            Frame f2 = WindowManager.getFrame(bottomPlotTitle);
            if (f2 != null)
                f2.setLocation(f2.getLocation().x, f2.getLocation().y + f1.getHeight());
        }
    }

    log("%s domain analysis computed in %s ms", (spatialDomain) ? "Spatial" : "Frequency",
            Utils.rounded((System.nanoTime() - start) * 1e-6, 4));
    log("---");
}

From source file:de.prozesskraft.pmodel.PmodelPartUi1.java

/**
 * Create contents of the view part.// www  . java2  s. c om
 */
@PostConstruct
public void createControls(Composite composite) {

    composite.setSize(613, 649);
    GridData gd_composite = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
    gd_composite.minimumWidth = 10;
    gd_composite.minimumHeight = 10;
    composite.setLayoutData(gd_composite);
    composite.setLayout(new GridLayout(1, false));

    Composite composite_1 = new Composite(composite, SWT.NONE);
    GridLayout gl_composite_1 = new GridLayout(4, false);
    gl_composite_1.marginWidth = 0;
    gl_composite_1.marginHeight = 0;
    composite_1.setLayout(gl_composite_1);
    GridData gd_composite_1 = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
    gd_composite_1.heightHint = 445;
    gd_composite_1.widthHint = 122;
    composite_1.setLayoutData(gd_composite_1);

    Composite composite_11 = new Composite(composite_1, SWT.NONE);
    composite_11.setLayout(new GridLayout(1, false));
    GridData gd_composite_11 = new GridData(SWT.LEFT, SWT.FILL, false, true, 1, 1);
    gd_composite_11.heightHint = 437;
    gd_composite_11.widthHint = 169;
    composite_11.setLayoutData(gd_composite_11);

    Group grpVisual = new Group(composite_11, SWT.NONE);
    grpVisual.setText("visual");
    grpVisual.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
    grpVisual.setLayout(new GridLayout(2, false));

    //      ExpandBar barVisual = new ExpandBar(composite_11, SWT.V_SCROLL);
    //      Composite grpVisual = new Composite(barVisual, SWT.NONE);
    //      ExpandItem item0 = new ExpandItem(barVisual, SWT.NONE, 0);
    //      item0.setText("visual settings");
    //      item0.setHeight(grpVisual.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
    //      item0.setControl(grpVisual);
    //      item0.setExpanded(true);
    //      barVisual.setSpacing(8);

    Label lblNewLabel_2 = new Label(grpVisual, SWT.NONE);
    lblNewLabel_2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
    lblNewLabel_2.setText("size");

    scale_size = new Scale(grpVisual, SWT.NONE);
    scale_size.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
    scale_size.setMaximum(200);
    scale_size.setMinimum(10);
    scale_size.setSelection(100);
    scale_size.addMouseWheelListener(listener_mousewheel_size);

    Label lblNewLabel_21 = new Label(grpVisual, SWT.NONE);
    lblNewLabel_21.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
    lblNewLabel_21.setText("zoom");

    scale_zoom = new Scale(grpVisual, SWT.NONE);
    scale_zoom.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
    scale_zoom.setMaximum(200);
    scale_zoom.setMinimum(10);
    scale_zoom.setSelection(100);
    scale_zoom.addMouseWheelListener(listener_mousewheel_zoom);

    //      Label lblNewLabel_3 = new Label(grpVisual, SWT.NONE);
    //      lblNewLabel_3.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
    //      lblNewLabel_3.setText("label");

    //      spinner_labelsize = new Spinner(grpVisual, SWT.BORDER);
    //      spinner_labelsize.setMaximum(20);
    //      spinner_labelsize.setSelection(10);
    //      spinner_labelsize.setMinimum(0);

    Label lblNewLabel_4 = new Label(grpVisual, SWT.NONE);
    lblNewLabel_4.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
    lblNewLabel_4.setText("text");

    spinner_textsize = new Spinner(grpVisual, SWT.BORDER);
    spinner_textsize.setMaximum(20);
    spinner_textsize.setSelection(10);
    spinner_textsize.setMinimum(0);

    button_fix = new Button(grpVisual, SWT.NONE | SWT.TOGGLE);
    button_fix.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
    button_fix.setText("fix");

    Button btnNewButton2 = new Button(grpVisual, SWT.NONE);
    btnNewButton2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));
    btnNewButton2.setText("autoscale");
    btnNewButton2.addSelectionListener(listener_autoscale_button);

    Group grpFunction = new Group(composite_11, SWT.NONE);
    grpFunction.setLayout(new GridLayout(2, false));
    grpFunction.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
    grpFunction.setText("function");

    button_refresh = new Button(grpFunction, SWT.NONE | SWT.PUSH);
    button_refresh.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
    button_refresh.setText("refresh");
    button_refresh.addListener(SWT.Selection, (Listener) listener_refresh_button);
    button_refresh.setEnabled(true);

    //      button_refresh.getDisplay().asyncExec( new Runnable()
    //      {
    //         public void run()
    //         {
    //            // das Prozess Binary File ueberwachen
    //            // Wenn modifiziert wurde? dann soll Enable=true gesetzt werden
    //      //      Path processRootDir = Paths.get(einstellungen.getProcess().getRootdir());
    //            Path processRootDir = Paths.get("/localhome/avoge/Desktop");
    //      
    //            System.err.println("watching directory " + processRootDir);
    //            
    //            try {
    //               // Watch Service erstellen
    //               WatchService service = FileSystems.getDefault().newWatchService();
    //      
    //               // Watch key erstellen
    //               WatchKey key = processRootDir.register(service, ENTRY_MODIFY);
    //               
    //               while(true)
    //               {
    //                  try {
    //                     Thread.sleep(500);
    //                  } catch (InterruptedException e) {
    //                     // TODO Auto-generated catch block
    //                     e.printStackTrace();
    //                  }
    //                  WatchKey key1;
    //                  try
    //                  {
    //                     key1 = service.take();
    //                  }
    //                  catch (InterruptedException x)
    //                  {
    //                     break;
    //                  }
    //                  
    //                  for(WatchEvent<?> event: key1.pollEvents())
    //                  {
    //                     WatchEvent.Kind<?> kind = event.kind();
    //                     
    //                     if(kind == OVERFLOW)
    //                     {
    //                        continue;
    //                     }
    //                     
    //                     WatchEvent<Path> ev = (WatchEvent<Path>) event;
    //                     Path filename = ev.context();
    //                     Path child = processRootDir.resolve(filename);
    //                     log("debug", "directory modified");
    //      //               if(child.equals(Paths.get(einstellungen.getProcess().getRootdir() + "/process.pmb")))
    ////                     if(child.equals(Paths.get("/localhome/avoge/Desktop/testfileNotification")))
    //                     {
    //                        button_refresh.setEnabled(true);
    //                        log("debug", "binary modified");
    //                     }
    //                  }
    //               }
    //      
    //            } catch (IOException e) {
    //               // TODO Auto-generated catch block
    //               e.printStackTrace();
    //            }
    //         }
    //      });

    button_startmanager = new Button(grpFunction, SWT.NONE);
    button_startmanager.setSelection(true);
    GridData gd_btnNewButton = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1);
    gd_btnNewButton.widthHint = 69;
    button_startmanager.setLayoutData(gd_btnNewButton);
    button_startmanager.setText("start new manager");
    button_startmanager.addSelectionListener(listener_startmanager_button);

    button_stopmanager = new Button(grpFunction, SWT.NONE);
    button_stopmanager.setSelection(true);
    GridData gd_button_stopmanager = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1);
    gd_button_stopmanager.widthHint = 69;
    button_stopmanager.setLayoutData(gd_button_stopmanager);
    button_stopmanager.setText("stop manager");
    button_stopmanager.addSelectionListener(listener_stopmanager_button);

    label_marked = new Label(composite_11, SWT.NONE);
    label_marked.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
    label_marked.setText("New Label");

    SashForm sashForm = new SashForm(composite_1, SWT.SMOOTH);
    sashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    new Label(composite_1, SWT.NONE);

    Composite composite_12 = new Composite(sashForm, SWT.EMBEDDED | SWT.NO_BACKGROUND);
    composite_12.setLayout(new GridLayout(1, false));
    GridData gd_composite_12 = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
    gd_composite_12.heightHint = 390;
    gd_composite_12.minimumWidth = 10;
    gd_composite_12.minimumHeight = 10;
    composite_12.setLayoutData(gd_composite_12);

    Frame frame = SWT_AWT.new_Frame(composite_12);

    frame.add(applet, BorderLayout.CENTER);
    applet.init();
    frame.pack();
    frame.setLocation(0, 0);
    frame.setVisible(true);

    Composite composite_13 = new Composite(sashForm, SWT.NONE);
    composite_13.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
    GridLayout gl_composite_13 = new GridLayout(1, false);
    gl_composite_13.marginWidth = 0;
    gl_composite_13.marginHeight = 0;
    composite_13.setLayout(gl_composite_13);
    //      tabFolder_13.addSelectionListener(listener_tabFolder_selection);
    new Label(composite_1, SWT.NONE);

    //      SashForm sashForm_13 = new SashForm(composite_13, SWT.SMOOTH | SWT.VERTICAL);
    //      composite_13.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    composite_131 = new Composite(composite_13, SWT.BORDER);
    composite_131.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
    GridLayout gl_composite_131 = new GridLayout(1, false);
    gl_composite_131.marginWidth = 0;
    gl_composite_131.marginHeight = 0;
    composite_131.setLayout(gl_composite_131);

    composite_132 = new Composite(composite_13, SWT.BORDER);
    composite_132.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
    GridLayout gl_composite_132 = new GridLayout(1, false);
    gl_composite_132.marginWidth = 0;
    gl_composite_132.marginHeight = 0;
    composite_132.setLayout(gl_composite_132);

    Composite composite_2 = new Composite(composite, SWT.NONE);
    composite_2.setLayout(new GridLayout(1, false));
    GridData gd_composite_2 = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
    gd_composite_2.heightHint = 164;
    composite_2.setLayoutData(gd_composite_2);

    //      text_logging = new Text(composite_2, SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL | SWT.MULTI);
    //      text_logging.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    text_logging = new StyledText(composite_2, SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL | SWT.MULTI);
    text_logging.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    // virtuelle ablage fuer gerade nicht anzuzeigende composites
    shell_dummy_insight = new Shell(display);
    //      shell_dummy_insight.setLayout(new FillLayout());

    bindingContextVisual = initDataBindingsVisual();
    bindingContextMarked = initDataBindingsMarked();
    bindingContextRefresh = initDataBindingsRefresh();

    // erzeugen der 'step-insight' listeners beim wechsel der markierung
    generateNewInsight(einstellungen);

    // erzeugen den insight fuer den Prozess
    createControlsProcessInsight(composite_131);
    new Label(composite_131, SWT.NONE);

    // erzeugen der ersten insight ansicht fuer den aktuell markierten step (root)
    createControlsStepInsight(composite_132);

    // die processing darstellung refreshen
    applet_refresh();

}

From source file:com.mirth.connect.plugins.rtfviewer.RTFViewer.java

@Override
public void viewAttachments(List<String> attachmentIds) {
    // do viewing code

    Frame frame = new Frame("RTF Viewer");

    frame.setLayout(new BorderLayout());

    try {/*from   ww  w  .jav a  2s  .c  om*/

        Attachment attachment = parent.mirthClient.getAttachment(attachmentIds.get(0));
        byte[] rawRTF = Base64.decodeBase64(attachment.getData());
        JEditorPane jEditorPane = new JEditorPane("text/rtf", new String(rawRTF));

        if (jEditorPane.getDocument().getLength() == 0) {
            // decoded when it should not have been.  i.e.) the attachment data was not encoded.
            jEditorPane.setText(new String(attachment.getData()));
        }

        jEditorPane.setEditable(false);
        JScrollPane scrollPane = new javax.swing.JScrollPane();
        scrollPane.setViewportView(jEditorPane);
        frame.add(scrollPane);
        frame.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                e.getWindow().dispose();
            }
        });

        frame.setSize(600, 800);

        Dimension dlgSize = frame.getSize();
        Dimension frmSize = parent.getSize();
        Point loc = parent.getLocation();

        if ((frmSize.width == 0 && frmSize.height == 0) || (loc.x == 0 && loc.y == 0)) {
            frame.setLocationRelativeTo(null);
        } else {
            frame.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x,
                    (frmSize.height - dlgSize.height) / 2 + loc.y);
        }

        frame.setVisible(true);
    } catch (Exception e) {
        parent.alertException(parent, e.getStackTrace(), e.getMessage());
    }
}

From source file:com.mirth.connect.plugins.textviewer.TextViewer.java

@Override
public void viewAttachments(String channelId, Long messageId, String attachmentId) {
    // do viewing code
    Frame frame = new Frame("Text Viewer");
    frame.setLayout(new BorderLayout());

    try {/*from  www . ja va 2  s.c o m*/
        Attachment attachment = parent.mirthClient.getAttachment(channelId, messageId, attachmentId);
        byte[] content = Base64.decodeBase64(attachment.getContent());

        boolean isRTF = attachment.getType().toLowerCase().contains("rtf");
        //TODO set character encoding
        JEditorPane jEditorPane = new JEditorPane(isRTF ? "text/rtf" : "text/plain", new String(content));

        if (jEditorPane.getDocument().getLength() == 0) {
            // decoded when it should not have been.  i.e.) the attachment data was not encoded.
            jEditorPane.setText(new String(attachment.getContent()));
        }

        jEditorPane.setEditable(false);
        JScrollPane scrollPane = new javax.swing.JScrollPane();
        scrollPane.setViewportView(jEditorPane);
        frame.add(scrollPane);
        frame.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                e.getWindow().dispose();
            }
        });

        frame.setSize(600, 800);

        Dimension dlgSize = frame.getSize();
        Dimension frmSize = parent.getSize();
        Point loc = parent.getLocation();

        if ((frmSize.width == 0 && frmSize.height == 0) || (loc.x == 0 && loc.y == 0)) {
            frame.setLocationRelativeTo(null);
        } else {
            frame.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x,
                    (frmSize.height - dlgSize.height) / 2 + loc.y);
        }

        frame.setVisible(true);
    } catch (Exception e) {
        parent.alertThrowable(parent, e);
    }
}

From source file:net.sf.freecol.FreeCol.java

public static void startYourAddition() throws FontFormatException, IOException {
    Frame mainFrame;
    Frame mainFrame2;//from   w  ww .  ja va  2 s.c  o  m
    TextField t1;
    TextField t2;
    TextField t3;
    TextField t4;
    Frame mainFrame3 = new Frame("Haha, am i middle?");
    mainFrame = new Frame("Haha, am I right?!");
    mainFrame.setSize(400, 400);
    mainFrame.setLayout(null);

    t1 = new TextField("Enter here");
    t1.setBounds(160, 200, 150, 50);

    t2 = new TextField("What grade do we deserve?");
    t3 = new TextField("Enter here");
    t3.setBounds(160, 200, 150, 50);

    t4 = new TextField("What letter grade do we deserve?");
    Button b = new Button("click ----->");
    b.setBounds(30, 250, 130, 30);
    b.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            t2.setText("I think you meant 100");
        }
    });
    Button c = new Button("Submit");
    c.setBounds(150, 250, 80, 30);
    c.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            String in = t1.getText();
            if (in.equals("100")) {
                t1.setText("Correct");
                t1.setEditable(false);
                t1.setBackground(new Color(95, 216, 109));

                if (t3.getText().equals("Correct")) {
                    mainFrame3.setVisible(true);
                }
            } else {
                t1.setText("Wrong");
                t1.setBackground(new Color(214, 81, 96));
            }
        }
    });

    t2.setBounds(160, 0, 175, 100);
    t2.setEditable(false);

    mainFrame.add(b);
    mainFrame.add(c);
    mainFrame.add(t1);
    mainFrame.add(t2);

    mainFrame.setLocation(1280, 0);

    mainFrame.setVisible(true);

    ///////////////The left area below and above is right

    mainFrame2 = new Frame("Haha, am i left?");
    mainFrame2.setSize(400, 400);
    mainFrame2.setLayout(null);

    Button b2 = new Button("click ----->");
    b2.setBounds(30, 250, 130, 30);
    b2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            t4.setText("I think you meant A");
        }
    });
    Button c2 = new Button("Submit");
    c2.setBounds(150, 250, 80, 30);
    c2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            String in = t3.getText();
            if (in.equals("A")) {
                t3.setText("Correct");
                t3.setEditable(false);
                t3.setBackground(new Color(95, 216, 109));

                if (t1.getText().equals("Correct")) {
                    mainFrame3.setVisible(true);
                }

            } else {
                t3.setText("Wrong");
                t3.setBackground(new Color(214, 81, 96));
            }
        }
    });

    t4.setBounds(120, 0, 220, 100);
    t4.setEditable(false);

    mainFrame2.add(b2);
    mainFrame2.add(c2);
    mainFrame2.add(t3);
    mainFrame2.add(t4);

    mainFrame2.setVisible(true);

    //Overall correct

    mainFrame3.setSize(400, 400);
    mainFrame3.setLayout(null);
    mainFrame3.setLocation(640, 420);
    mainFrame3.setBackground(new Color(95, 216, 109));
    TextField t6 = new TextField("Soooooo give us an A!!!");
    t6.setBounds(160, 200, 200, 50);
    t6.setBackground(new Color(102, 136, 232));

    mainFrame3.add(t6);
}

From source file:javazoom.jlgui.player.amp.Player.java

/**
 * Manages events.//from w  w w  .j  a v a2  s  .  c o m
 */
public void actionPerformed(ActionEvent e) {

    /*------------------------------------*/
    /*--        Interact on Seek        --*/
    /*------------------------------------*/
    if (e.getActionCommand().equals("Seek")) {
        if (acPosBar.isMousePressed() == false) {
            FirstPosBarDrag = true;
            posValueJump = true;
            processSeek();
            repaint();
        } else {
            int DeltaX = 0;
            if (FirstPosBarDrag == false) {
                DeltaX = acPosBar.getMouseX() - XPosBarDrag;
                XPosBarDrag = acPosBar.getMouseX() - DeltaX;
                if (posBarLocation[0] + DeltaX < posBarBounds[0])
                    posBarLocation[0] = posBarBounds[0];
                else if (posBarLocation[0] + DeltaX > posBarBounds[1])
                    posBarLocation[0] = posBarBounds[1];
                else
                    posBarLocation[0] = posBarLocation[0] + DeltaX;
                acPosBar.setLocation(posBarLocation[0], posBarLocation[1]);
                double a = (maxPos - minPos) / (posBarBounds[1] - posBarBounds[0]);
                posValue = (a * (posBarLocation[0] - posBarBounds[0]) + minPos);
            } else {
                FirstPosBarDrag = false;
                XPosBarDrag = acPosBar.getMouseX();
            }
        }
    }

    /*------------------------------------*/
    /*--       Interact on Volume       --*/
    /*------------------------------------*/
    else if (e.getActionCommand().equals("Volume")) {
        if (acVolume.isMousePressed() == false) {
            FirstVolumeDrag = true;
            offScreenGraphics.drawImage(clearImage, titleLocation[0], titleLocation[1], this);
            offScreenGraphics.drawImage(titleImage, titleLocation[0], titleLocation[1], this);
            repaint();
        } else {
            int DeltaX = 0;
            if (FirstVolumeDrag == false) {
                DeltaX = acVolume.getMouseX() - XVolumeDrag;
                XVolumeDrag = acVolume.getMouseX() - DeltaX;
                if (volumeLocation[0] + DeltaX < volumeBounds[0])
                    volumeLocation[0] = volumeBounds[0];
                else if (volumeLocation[0] + DeltaX > volumeBounds[1])
                    volumeLocation[0] = volumeBounds[1];
                else
                    volumeLocation[0] = volumeLocation[0] + DeltaX;
                acVolume.setLocation(volumeLocation[0], volumeLocation[1]);
                double a = (maxGain - minGain) / (volumeBounds[1] - volumeBounds[0]);
                gainValue = (int) (a * (volumeLocation[0] - volumeBounds[0]) + minGain);
                try {
                    if (gainValue == 0)
                        theSoundPlayer.setGain(0);
                    else
                        theSoundPlayer.setGain(((double) gainValue / (double) maxGain));
                } catch (BasicPlayerException e1) {
                    log.debug("Cannot set gain", e1);
                }
                String volumeText = "VOLUME: " + (int) Math.round(
                        (100 / (volumeBounds[1] - volumeBounds[0])) * (volumeLocation[0] - volumeBounds[0]))
                        + "%";
                Image volImage = (new Taftb(fontIndex, imText, fontWidth, fontHeight, 0, volumeText))
                        .getBanner();
                offScreenGraphics.drawImage(
                        volumeImage[(int) Math
                                .round(((double) gainValue / (double) maxGain) * (volumeImage.length - 1))],
                        volumeBarLocation[0], volumeBarLocation[1], this);
                offScreenGraphics.drawImage(clearImage, titleLocation[0], titleLocation[1], this);
                offScreenGraphics.drawImage(volImage, titleLocation[0], titleLocation[1], this);
            } else {
                FirstVolumeDrag = false;
                XVolumeDrag = acVolume.getMouseX();
            }
        }
    }

    /*------------------------------------*/
    /*--       Interact on Balance       --*/
    /*------------------------------------*/
    else if (e.getActionCommand().equals("Balance")) {
        if (acBalance.isMousePressed() == false) {
            FirstBalanceDrag = true;
            offScreenGraphics.drawImage(clearImage, titleLocation[0], titleLocation[1], this);
            offScreenGraphics.drawImage(titleImage, titleLocation[0], titleLocation[1], this);
            repaint();
        } else {
            int DeltaX = 0;
            if (FirstBalanceDrag == false) {
                DeltaX = acBalance.getMouseX() - XBalanceDrag;
                XBalanceDrag = acBalance.getMouseX() - DeltaX;
                if (balanceLocation[0] + DeltaX < balanceBounds[0])
                    balanceLocation[0] = balanceBounds[0];
                else if (balanceLocation[0] + DeltaX > balanceBounds[1])
                    balanceLocation[0] = balanceBounds[1];
                else
                    balanceLocation[0] = balanceLocation[0] + DeltaX;
                acBalance.setLocation(balanceLocation[0], balanceLocation[1]);
                double a = (maxBalance - minBalance) / (balanceBounds[1] - balanceBounds[0]);
                balanceValue = (a * (balanceLocation[0] - balanceBounds[0]) + minBalance);
                try {
                    theSoundPlayer.setPan((float) balanceValue);
                } catch (BasicPlayerException e1) {
                    log.debug("Cannot set pan", e1);
                }
                String balanceText = "BALANCE: " + (int) Math.abs(balanceValue * 100) + "%";
                if (balanceValue > 0)
                    balanceText = balanceText + " RIGHT";
                else if (balanceValue < 0)
                    balanceText = balanceText + " LEFT";
                else
                    balanceText = "BALANCE: CENTER";
                Image balImage = (new Taftb(fontIndex, imText, fontWidth, fontHeight, 0, balanceText))
                        .getBanner();
                offScreenGraphics.drawImage(
                        balanceImage[(int) Math.round(
                                ((double) Math.abs(balanceValue) / (double) 1) * (balanceImage.length - 1))],
                        balanceBarLocation[0], balanceBarLocation[1], this);
                offScreenGraphics.drawImage(clearImage, titleLocation[0], titleLocation[1], this);
                offScreenGraphics.drawImage(balImage, titleLocation[0], titleLocation[1], this);
            } else {
                FirstBalanceDrag = false;
                XBalanceDrag = acBalance.getMouseX();
            }
        }
    }

    /*------------------------------------*/
    /*-- Select Filename or URL to load --*/
    /*------------------------------------*/
    else if (e.getActionCommand().equals("Eject")) {
        if ((playerState == PLAY) || (playerState == PAUSE)) {
            try {
                theSoundPlayer.stop();
            } catch (BasicPlayerException e1) {
                log.info("Cannot stop", e1);
            }
            playerState = STOP;
        }
        if ((playerState == INIT) || (playerState == STOP) || (playerState == OPEN)) {
            System.gc();
            PlaylistItem pli = null;
            // Local File.
            // E.B : FileSelector added as M.S did.
            if (acEject.getMouseButton() == MouseEvent.BUTTON1_MASK) {
                Frame f = new Frame();
                f.setLocation(this.getBounds().x, this.getBounds().y + 10);
                FileSelector.setWindow(f);
                String fsFile = FileSelector.selectFile(FileSelector.OPEN, config.getExtensions(),
                        config.getLastDir());
                fsFile = FileSelector.getFile();
                if (fsFile != null) {
                    config.setLastDir(FileSelector.getDirectory());
                    if (fsFile != null) {
                        // Loads a new playlist.
                        if ((fsFile.toLowerCase().endsWith(".m3u"))
                                || (fsFile.toLowerCase().endsWith(".pls"))) {
                            if (loadPlaylist(config.getLastDir() + fsFile)) {
                                config.setPlaylistFilename(config.getLastDir() + fsFile);
                                playlist.begin();
                                fileList.initPlayList();
                                this.setCurrentSong(playlist.getCursor());
                                fileList.repaint();
                            }
                        } else if (fsFile.toLowerCase().endsWith(".wsz")) {
                            this.dispose();
                            loadSkin(config.getLastDir() + fsFile);
                            config.setDefaultSkin(config.getLastDir() + fsFile);
                        } else
                            pli = new PlaylistItem(fsFile, config.getLastDir() + fsFile, -1, true);
                    }
                }
            }
            // Remote File.
            else if (acEject.getMouseButton() == MouseEvent.BUTTON3_MASK) {
                UrlDialog UD = new UrlDialog("Open location", this.getBounds().x, this.getBounds().y + 10, 280,
                        130, config.getLastURL());
                UD.show();
                if (UD.getFile() != null) {
                    showTitle("PLEASE WAIT ... LOADING ...");
                    displayAll();
                    if (fileList != null)
                        fileList.displayAll();
                    if (equalizer != null)
                        equalizer.displayAll();
                    // Remote playlist ?
                    if ((UD.getURL().toLowerCase().endsWith(".m3u"))
                            || (UD.getURL().toLowerCase().endsWith(".pls"))) {
                        if (loadPlaylist(UD.getURL())) {
                            config.setPlaylistFilename(UD.getURL());
                            playlist.begin();
                            fileList.initPlayList();
                            this.setCurrentSong(playlist.getCursor());
                            fileList.repaint();
                        }
                    }
                    // Remote file or stream.
                    else {
                        pli = new PlaylistItem(UD.getFile(), UD.getURL(), -1, false);
                    }
                    config.setLastURL(UD.getURL());
                }
            }

            if (pli != null) {
                playlist.removeAllItems();
                playlist.appendItem(pli);
                playlist.nextCursor();
                fileList.initPlayList();
                this.setCurrentSong(pli);
            }
        }
        offScreenGraphics.drawImage(iconsImage[2], iconsLocation[0], iconsLocation[1], this);
        offScreenGraphics.drawImage(iconsImage[4], iconsLocation[2], iconsLocation[3], this);
        repaint();
    }

    /*---------------------------*/
    /*-- Play the current File --*/
    /*---------------------------*/
    else if (e.getActionCommand().equals("Play")) {
        if (playlist.isModified()) // playlist has been modified since we were last there, must update our cursor pos etc.
        {
            PlaylistItem pli = playlist.getCursor();
            if (pli == null) {
                playlist.begin();
                pli = playlist.getCursor();
                if (firstSong) {
                    String info = pli.getName();
                    info += " STARTED PLAYLIST";
                    tFrame.addText(info);
                    firstSong = false;
                }
            } else if (playlist.getSelectedIndex() == 0) {
                if (firstSong) {
                    String info = pli.getName();
                    info += " STARTED PLAYLIST";
                    tFrame.addText(info);
                    firstSong = false;
                }
            }
            this.setCurrentSong(pli);
            if (!isRepeat) {
                //String info = pli.getName();
                //info += " STARTED PLAYLIST";
                //tFrame.addText(info);
            } else
                isRepeat = false;
            playlist.setModified(false);
            fileList.repaint();
        }

        // Resume is paused.
        if (playerState == PAUSE) {
            try {
                theSoundPlayer.resume();
            } catch (BasicPlayerException e1) {
                log.error("Cannot resume", e1);
            }
            playerState = PLAY;
            offScreenGraphics.drawImage(iconsImage[0], iconsLocation[0], iconsLocation[1], this);
            offScreenGraphics.drawImage(iconsImage[3], iconsLocation[2], iconsLocation[3], this);
            repaint();
        }

        // Stop if playing.
        else if (playerState == PLAY) {
            try {
                theSoundPlayer.stop();
            } catch (BasicPlayerException e1) {
                log.error("Cannot stop", e1);
            }
            playerState = PLAY;
            secondsAmount = 0;
            offScreenGraphics.drawImage(timeImage[0], minuteDLocation[0], minuteDLocation[1], this);
            offScreenGraphics.drawImage(timeImage[0], minuteLocation[0], minuteLocation[1], this);
            offScreenGraphics.drawImage(timeImage[0], secondDLocation[0], secondDLocation[1], this);
            offScreenGraphics.drawImage(timeImage[0], secondLocation[0], secondLocation[1], this);
            repaint();
            if (currentFileOrURL != null) {
                try {
                    if (currentIsFile == true)
                        theSoundPlayer.open(openFile(currentFileOrURL));
                    else
                        theSoundPlayer.open(new URL(currentFileOrURL));
                    theSoundPlayer.play();
                } catch (Exception ex) {
                    log.error("Cannot read file : " + currentFileOrURL, ex);
                    showMessage("INVALID FILE");
                }
            }
        } else if ((playerState == STOP) || (playerState == OPEN)) {
            try {
                theSoundPlayer.stop();
            } catch (BasicPlayerException e1) {
                log.error("Stop failed", e1);
            }
            if (currentFileOrURL != null) {
                try {
                    if (currentIsFile == true)
                        theSoundPlayer.open(openFile(currentFileOrURL));
                    else
                        theSoundPlayer.open(new URL(currentFileOrURL));
                    theSoundPlayer.play();
                    titleText = currentSongName.toUpperCase();

                    // Get bitrate, samplingrate, channels, time in the following order :
                    // PlaylistItem, BasicPlayer (JavaSound SPI), Manual computation.
                    int bitRate = -1;
                    if (currentPlaylistItem != null)
                        bitRate = currentPlaylistItem.getBitrate();
                    if ((bitRate <= 0) && (audioInfo.containsKey("bitrate")))
                        bitRate = ((Integer) audioInfo.get("bitrate")).intValue();
                    if ((bitRate <= 0) && (audioInfo.containsKey("audio.framerate.fps"))
                            && (audioInfo.containsKey("audio.framesize.bytes"))) {
                        float FR = ((Float) audioInfo.get("audio.framerate.fps")).floatValue();
                        int FS = ((Integer) audioInfo.get("audio.framesize.bytes")).intValue();
                        bitRate = Math.round(FS * FR * 8);
                    }
                    int channels = -1;
                    if (currentPlaylistItem != null)
                        channels = currentPlaylistItem.getChannels();
                    if ((channels <= 0) && (audioInfo.containsKey("audio.channels")))
                        channels = ((Integer) audioInfo.get("audio.channels")).intValue();
                    float sampleRate = -1.0f;
                    if (currentPlaylistItem != null)
                        sampleRate = currentPlaylistItem.getSamplerate();
                    if ((sampleRate <= 0) && (audioInfo.containsKey("audio.samplerate.hz")))
                        sampleRate = ((Float) audioInfo.get("audio.samplerate.hz")).floatValue();
                    long lenghtInSecond = -1L;
                    if (currentPlaylistItem != null)
                        lenghtInSecond = currentPlaylistItem.getLength();
                    if ((lenghtInSecond <= 0) && (audioInfo.containsKey("duration")))
                        lenghtInSecond = ((Long) audioInfo.get("duration")).longValue() / 1000000;
                    if ((lenghtInSecond <= 0) && (audioInfo.containsKey("audio.length.bytes"))) {
                        // Try to compute time length.
                        lenghtInSecond = (long) Math.round(getTimeLengthEstimation(audioInfo) / 1000);
                        if (lenghtInSecond > 0) {
                            int minutes = (int) Math.floor(lenghtInSecond / 60);
                            int hours = (int) Math.floor(minutes / 60);
                            minutes = minutes - hours * 60;
                            int seconds = (int) (lenghtInSecond - minutes * 60 - hours * 3600);
                            if (seconds >= 10)
                                titleText = "(" + minutes + ":" + seconds + ") " + titleText;
                            else
                                titleText = "(" + minutes + ":0" + seconds + ") " + titleText;
                        }
                    }
                    bitRate = Math.round((bitRate / 1000));
                    sampleRateImage = (new Taftb(fontIndex, imText, fontWidth, fontHeight, 0,
                            "" + Math.round((sampleRate / 1000)))).getBanner();
                    if (bitRate > 999) {
                        bitRate = (int) (bitRate / 100);
                        bitsRateImage = (new Taftb(fontIndex, imText, fontWidth, fontHeight, 0,
                                "" + bitRate + "H")).getBanner();
                    } else
                        bitsRateImage = (new Taftb(fontIndex, imText, fontWidth, fontHeight, 0, "" + bitRate))
                                .getBanner();
                    offScreenGraphics.drawImage(sampleRateImage, sampleRateLocation[0], sampleRateLocation[1],
                            this);
                    offScreenGraphics.drawImage(bitsRateImage, bitsRateLocation[0], bitsRateLocation[1], this);
                    if (channels == 2) {
                        offScreenGraphics.drawImage(activeModeImage[0], stereoLocation[0], stereoLocation[1],
                                this);
                    } else if (channels == 1) {
                        offScreenGraphics.drawImage(activeModeImage[1], monoLocation[0], monoLocation[1], this);
                    }
                    showTitle(titleText);
                    offScreenGraphics.drawImage(timeImage[0], minuteDLocation[0], minuteDLocation[1], this);
                    offScreenGraphics.drawImage(timeImage[0], minuteLocation[0], minuteLocation[1], this);
                    offScreenGraphics.drawImage(timeImage[0], secondDLocation[0], secondDLocation[1], this);
                    offScreenGraphics.drawImage(timeImage[0], secondLocation[0], secondLocation[1], this);

                    offScreenGraphics.drawImage(iconsImage[0], iconsLocation[0], iconsLocation[1], this);
                    offScreenGraphics.drawImage(iconsImage[3], iconsLocation[2], iconsLocation[3], this);
                } catch (BasicPlayerException bpe) {
                    log.info("Stream error :" + currentFileOrURL, bpe);
                    showMessage("INVALID FILE");
                } catch (MalformedURLException mue) {
                    log.info("Stream error :" + currentFileOrURL, mue);
                    showMessage("INVALID FILE");
                }

                // Set pan/gain.
                try {
                    theSoundPlayer.setGain(((double) gainValue / (double) maxGain));
                    theSoundPlayer.setPan((float) balanceValue);
                } catch (BasicPlayerException e2) {
                    log.info("Cannot set control", e2);
                }

                playerState = PLAY;
                repaint();
                log.info(titleText);
            }
        }
    }

    /*-----------------------------------*/
    /*-- Pause/Resume the current File --*/
    /*-----------------------------------*/
    else if (e.getActionCommand().equals("Pause")) {
        if (playerState == PLAY) {
            try {
                theSoundPlayer.pause();
            } catch (BasicPlayerException e1) {
                log.error("Cannot pause", e1);
            }
            playerState = PAUSE;
            offScreenGraphics.drawImage(iconsImage[1], iconsLocation[0], iconsLocation[1], this);
            offScreenGraphics.drawImage(iconsImage[4], iconsLocation[2], iconsLocation[3], this);
            repaint();
        } else if (playerState == PAUSE) {
            try {
                theSoundPlayer.resume();
            } catch (BasicPlayerException e1) {
                log.info("Cannot resume", e1);
            }
            playerState = PLAY;
            offScreenGraphics.drawImage(iconsImage[0], iconsLocation[0], iconsLocation[1], this);
            offScreenGraphics.drawImage(iconsImage[3], iconsLocation[2], iconsLocation[3], this);
            repaint();
        }
    }

    /*------------------*/
    /*-- Stop to play --*/
    /*------------------*/
    else if (e.getActionCommand().equals("Stop")) {
        if ((playerState == PAUSE) || (playerState == PLAY)) {
            try {
                theSoundPlayer.stop();
            } catch (BasicPlayerException e1) {
                log.info("Cannot stop", e1);
            }
            playerState = STOP;
            secondsAmount = 0;
            acPosBar.setLocation(posBarBounds[0], posBarLocation[1]);
            offScreenGraphics.drawImage(iconsImage[2], iconsLocation[0], iconsLocation[1], this);
            offScreenGraphics.drawImage(iconsImage[4], iconsLocation[2], iconsLocation[3], this);
            repaint();
        }
    }

    /*----------*/
    /*-- Next --*/
    /*----------*/
    else if (e.getActionCommand().equals("Next")) {
        // Try to get next song from the playlist
        playlist.nextCursor();
        fileList.nextCursor();
        PlaylistItem pli = playlist.getCursor();
        String info = pli.getName();
        info += ", NEXT";
        if (tFrame != null)
            tFrame.addText(info);
        firstSong = false;
        this.setCurrentSong(pli);
    }

    /*--------------*/
    /*-- Previous --*/
    /*--------------*/
    else if (e.getActionCommand().equals("Previous")) {
        // Try to get previous song from the playlist
        playlist.previousCursor();
        fileList.nextCursor();
        PlaylistItem pli = playlist.getCursor();
        String info = pli.getName();
        info += ", PREVIOUS";
        if (tFrame != null)
            tFrame.addText(info);
        firstSong = false;
        this.setCurrentSong(pli);
    }

    /*--------------------------------------------*/
    /*--     Exit window through Exit Button    --*/
    /*--------------------------------------------*/
    else if (e.getActionCommand().equals("Exit")) {
        closePlayer();
    }

    /*----------------------------------------------------*/
    /*--     Minimize window through Minimize Button    --*/
    /*----------------------------------------------------*/
    else if (e.getActionCommand().equals("Minimize")) {
        // Iconify top frame.
        topFrame.setLocation(OrigineX, OrigineY);
        topFrame.setState(Frame.ICONIFIED);
        //topFrame.show();
    }

    /*--------------------------------------------*/
    /*-- Move full window through its Title Bar --*/
    /*--------------------------------------------*/
    else if (e.getActionCommand().equals("TitleBar")) {
        //log.info("X="+acTitle.getMouseX()+" Y="+acTitle.getMouseY());
        if (acTitleBar.isMousePressed() == false)
            FirstDrag = true;
        else {
            int DeltaX = 0;
            int DeltaY = 0;
            if (FirstDrag == false) {
                DeltaX = acTitleBar.getMouseX() - XDrag;
                DeltaY = acTitleBar.getMouseY() - YDrag;
                XDrag = acTitleBar.getMouseX() - DeltaX;
                YDrag = acTitleBar.getMouseY() - DeltaY;
                OrigineX = OrigineX + DeltaX;
                OrigineY = OrigineY + DeltaY;

                if (config.isScreenLimit()) {
                    // Keep player window in screen
                    if (OrigineX < 0)
                        OrigineX = 0;
                    if (OrigineY < 0)
                        OrigineY = 0;
                    if (screenWidth != -1) {
                        if (OrigineX > screenWidth - WinWidth)
                            OrigineX = screenWidth - WinWidth;
                    }
                    if (screenHeight != -1) {
                        if (OrigineY > screenHeight - WinHeight)
                            OrigineY = screenHeight - WinHeight;
                    }
                }
                // Moves top frame.
                topFrame.setLocation(OrigineX, OrigineY);
                topFrame.setSize(0, 0);
                // Moves the main window + playlist
                setLocation(OrigineX, OrigineY);
                fileList.setLocation(OrigineX, OrigineY + WinHeight);
                int factor = 1;
                if (config.isPlaylistEnabled())
                    factor = 2;
                equalizer.setLocation(OrigineX, OrigineY + WinHeight * factor);
            } else {
                FirstDrag = false;
                XDrag = acTitleBar.getMouseX();
                YDrag = acTitleBar.getMouseY();
            }
        }
    }
    /*-----------------------------------------*/
    /*--     Playlist window hide/display    --*/
    /*-----------------------------------------*/
    else if (e.getActionCommand().equals("Playlist")) {
        if (acPlaylist.getCheckboxState()) {
            config.setPlaylistEnabled(true);
            if (config.isEqualizerEnabled()) {
                equalizer.setLocation(OrigineX, OrigineY + WinHeight * 2);
            }
            fileList.setVisible(true);
        } else {
            config.setPlaylistEnabled(false);
            fileList.setVisible(false);
            if (config.isEqualizerEnabled()) {
                equalizer.setLocation(OrigineX, OrigineY + WinHeight);
            }
        }
    }

    /*--------------------------------------*/
    /*--     Playlist window equalizer    --*/
    /*--------------------------------------*/
    else if (e.getActionCommand().equals("Equalizer")) {
        if (acEqualizer.getCheckboxState()) {
            config.setEqualizerEnabled(true);
            int factor = 1;
            if (config.isPlaylistEnabled())
                factor = 2;
            equalizer.setLocation(OrigineX, OrigineY + WinHeight * factor);
            equalizer.setVisible(true);
        } else {
            config.setEqualizerEnabled(false);
            equalizer.setVisible(false);
        }
    }

    /*--------------------*/
    /*--     Shuffle    --*/
    /*--------------------*/
    else if (e.getActionCommand().equals("Shuffle")) {
        if (acShuffle.getCheckboxState()) {
            config.setShuffleEnabled(true);
            if (playlist != null) {
                playlist.shuffle();
                fileList.initPlayList();
                // Play from the top
                PlaylistItem pli = playlist.getCursor();
                this.setCurrentSong(pli);
            }
        } else {
            config.setShuffleEnabled(false);
        }
    }
    /*-------------------*/
    /*--     Repeat    --*/
    /*-------------------*/
    else if (e.getActionCommand().equals("Repeat")) {
        if (acRepeat.getCheckboxState()) {
            config.setRepeatEnabled(true);
        } else {
            config.setRepeatEnabled(false);
        }
    }
    /*----------------------*/
    /*--     Equalizer    --*/
    /*----------------------*/
    else if (e.getActionCommand().equals("Equalizer")) {
        if (acEqualizer.getCheckboxState()) {
            config.setEqualizerEnabled(true);
        } else {
            config.setEqualizerEnabled(false);
        }
    } else if (e.getActionCommand().equals("Load Skin")) {
        Frame f = new Frame("Select a skin");
        f.setLocation(this.getBounds().x, this.getBounds().y + 10);
        FileSelector.setWindow(f);
        String fsFile = FileSelector.selectFile(FileSelector.OPEN, "wsz", config.getLastDir());
        fsFile = FileSelector.getFile();
        String fsDir = FileSelector.getDirectory();
        if ((fsFile != null) && (fsDir != null)) {
            config.setLastDir(fsDir);
            loadSkin(config.getLastDir() + fsFile);
            config.setDefaultSkin(config.getLastDir() + fsFile);
        }
    } else {
        // Unknown action.
    }
}

From source file:javazoom.jlgui.player.amp.PlayerApplet.java

/**
 * Manages events./* w  w w  . jav a  2 s .c  o m*/
 */
public void actionPerformed(ActionEvent e) {

    /*------------------------------------*/
    /*--        Interact on Seek        --*/
    /*------------------------------------*/
    if (e.getActionCommand().equals("Seek")) {
        if (acPosBar.isMousePressed() == false) {
            FirstPosBarDrag = true;
            posValueJump = true;
            processSeek();
            repaint();
        } else {
            int DeltaX = 0;
            if (FirstPosBarDrag == false) {
                DeltaX = acPosBar.getMouseX() - XPosBarDrag;
                XPosBarDrag = acPosBar.getMouseX() - DeltaX;
                if (posBarLocation[0] + DeltaX < posBarBounds[0])
                    posBarLocation[0] = posBarBounds[0];
                else if (posBarLocation[0] + DeltaX > posBarBounds[1])
                    posBarLocation[0] = posBarBounds[1];
                else
                    posBarLocation[0] = posBarLocation[0] + DeltaX;
                acPosBar.setLocation(posBarLocation[0], posBarLocation[1]);
                double a = (maxPos - minPos) / (posBarBounds[1] - posBarBounds[0]);
                posValue = (a * (posBarLocation[0] - posBarBounds[0]) + minPos);
            } else {
                FirstPosBarDrag = false;
                XPosBarDrag = acPosBar.getMouseX();
            }
        }
    }

    /*------------------------------------*/
    /*--       Interact on Volume       --*/
    /*------------------------------------*/
    else if (e.getActionCommand().equals("Volume")) {
        if (acVolume.isMousePressed() == false) {
            FirstVolumeDrag = true;
            offScreenGraphics.drawImage(clearImage, titleLocation[0], titleLocation[1], this);
            offScreenGraphics.drawImage(titleImage, titleLocation[0], titleLocation[1], this);
            repaint();
        } else {
            int DeltaX = 0;
            if (FirstVolumeDrag == false) {
                DeltaX = acVolume.getMouseX() - XVolumeDrag;
                XVolumeDrag = acVolume.getMouseX() - DeltaX;
                if (volumeLocation[0] + DeltaX < volumeBounds[0])
                    volumeLocation[0] = volumeBounds[0];
                else if (volumeLocation[0] + DeltaX > volumeBounds[1])
                    volumeLocation[0] = volumeBounds[1];
                else
                    volumeLocation[0] = volumeLocation[0] + DeltaX;
                acVolume.setLocation(volumeLocation[0], volumeLocation[1]);
                double a = (maxGain - minGain) / (volumeBounds[1] - volumeBounds[0]);
                gainValue = (int) (a * (volumeLocation[0] - volumeBounds[0]) + minGain);
                try {
                    if (gainValue == 0)
                        theSoundPlayer.setGain(0);
                    else
                        theSoundPlayer.setGain(((double) gainValue / (double) maxGain));
                } catch (BasicPlayerException e1) {
                    log.debug("Cannot set gain", e1);
                }
                String volumeText = "VOLUME: " + (int) Math.round(
                        (100 / (volumeBounds[1] - volumeBounds[0])) * (volumeLocation[0] - volumeBounds[0]))
                        + "%";
                Image volImage = (new Taftb(fontIndex, imText, fontWidth, fontHeight, 0, volumeText))
                        .getBanner();
                offScreenGraphics.drawImage(
                        volumeImage[(int) Math
                                .round(((double) gainValue / (double) maxGain) * (volumeImage.length - 1))],
                        volumeBarLocation[0], volumeBarLocation[1], this);
                offScreenGraphics.drawImage(clearImage, titleLocation[0], titleLocation[1], this);
                offScreenGraphics.drawImage(volImage, titleLocation[0], titleLocation[1], this);
            } else {
                FirstVolumeDrag = false;
                XVolumeDrag = acVolume.getMouseX();
            }
        }
    }

    /*------------------------------------*/
    /*--       Interact on Balance       --*/
    /*------------------------------------*/
    else if (e.getActionCommand().equals("Balance")) {
        if (acBalance.isMousePressed() == false) {
            FirstBalanceDrag = true;
            offScreenGraphics.drawImage(clearImage, titleLocation[0], titleLocation[1], this);
            offScreenGraphics.drawImage(titleImage, titleLocation[0], titleLocation[1], this);
            repaint();
        } else {
            int DeltaX = 0;
            if (FirstBalanceDrag == false) {
                DeltaX = acBalance.getMouseX() - XBalanceDrag;
                XBalanceDrag = acBalance.getMouseX() - DeltaX;
                if (balanceLocation[0] + DeltaX < balanceBounds[0])
                    balanceLocation[0] = balanceBounds[0];
                else if (balanceLocation[0] + DeltaX > balanceBounds[1])
                    balanceLocation[0] = balanceBounds[1];
                else
                    balanceLocation[0] = balanceLocation[0] + DeltaX;
                acBalance.setLocation(balanceLocation[0], balanceLocation[1]);
                double a = (maxBalance - minBalance) / (balanceBounds[1] - balanceBounds[0]);
                balanceValue = (a * (balanceLocation[0] - balanceBounds[0]) + minBalance);
                try {
                    theSoundPlayer.setPan((float) balanceValue);
                } catch (BasicPlayerException e1) {
                    log.debug("Cannot set pan", e1);
                }
                String balanceText = "BALANCE: " + (int) Math.abs(balanceValue * 100) + "%";
                if (balanceValue > 0)
                    balanceText = balanceText + " RIGHT";
                else if (balanceValue < 0)
                    balanceText = balanceText + " LEFT";
                else
                    balanceText = "BALANCE: CENTER";
                Image balImage = (new Taftb(fontIndex, imText, fontWidth, fontHeight, 0, balanceText))
                        .getBanner();
                offScreenGraphics.drawImage(
                        balanceImage[(int) Math.round(
                                ((double) Math.abs(balanceValue) / (double) 1) * (balanceImage.length - 1))],
                        balanceBarLocation[0], balanceBarLocation[1], this);
                offScreenGraphics.drawImage(clearImage, titleLocation[0], titleLocation[1], this);
                offScreenGraphics.drawImage(balImage, titleLocation[0], titleLocation[1], this);
            } else {
                FirstBalanceDrag = false;
                XBalanceDrag = acBalance.getMouseX();
            }
        }
    }

    /*------------------------------------*/
    /*-- Select Filename or URL to load --*/
    /*------------------------------------*/
    else if (e.getActionCommand().equals("Eject")) {
        if ((playerState == PLAY) || (playerState == PAUSE)) {
            try {
                theSoundPlayer.stop();
            } catch (BasicPlayerException e1) {
                log.info("Cannot stop", e1);
            }
            playerState = STOP;
        }
        if ((playerState == INIT) || (playerState == STOP) || (playerState == OPEN)) {
            System.gc();
            PlaylistItem pli = null;
            if (location != NONE) {
                // Local File.
                // E.B : FileSelector added as M.S did.
                if (acEject.getMouseButton() == MouseEvent.BUTTON1_MASK) {
                    String fsFile = null;
                    if (location == ALL) {
                        Frame f = new Frame();
                        f.setLocation(this.getBounds().x, this.getBounds().y + 10);
                        FileSelector.setWindow(f);
                        fsFile = FileSelector.selectFile(FileSelector.OPEN, config.getExtensions(),
                                config.getLastDir());
                        fsFile = FileSelector.getFile();
                    } else if (location == URL) {
                        UrlDialog UD = new UrlDialog("Open location", this.getBounds().x,
                                this.getBounds().y + 10, 280, 120, config.getLastURL());
                        UD.show();
                        if (UD.getFile() != null) {
                            config.setLastURL(UD.getURL());
                            fsFile = UD.getURL();
                        }
                    }
                    if (fsFile != null) {
                        if (location == ALL)
                            config.setLastDir(FileSelector.getDirectory());
                        else
                            config.setLastDir("");
                        if (fsFile != null) {
                            // Loads a new playlist.
                            if ((fsFile.toLowerCase().endsWith(".m3u"))
                                    || (fsFile.toLowerCase().endsWith(".pls"))) {
                                if (loadPlaylist(config.getLastDir() + fsFile)) {
                                    config.setPlaylistFilename(config.getLastDir() + fsFile);
                                    playlist.begin();
                                    fileList.initPlayList();
                                    this.setCurrentSong(playlist.getCursor());
                                    fileList.repaint();
                                }
                            } else if (fsFile.toLowerCase().endsWith(".wsz")) {
                                //this.dispose();
                                loadSkin(config.getLastDir() + fsFile);
                                config.setDefaultSkin(config.getLastDir() + fsFile);
                            } else {
                                if (location == ALL)
                                    pli = new PlaylistItem(fsFile, config.getLastDir() + fsFile, -1, true);
                                else
                                    pli = new PlaylistItem(fsFile, fsFile, -1, false);
                            }
                        }
                    }
                }
                // Remote File.
                else if (acEject.getMouseButton() == MouseEvent.BUTTON3_MASK) {
                    UrlDialog UD = new UrlDialog("Open location", this.getBounds().x, this.getBounds().y + 10,
                            280, 130, config.getLastURL());
                    UD.show();
                    if (UD.getFile() != null) {
                        showTitle("PLEASE WAIT ... LOADING ...");
                        displayAll();
                        if (fileList != null)
                            fileList.displayAll();
                        if (equalizer != null)
                            equalizer.displayAll();
                        // Remote playlist ?
                        if ((UD.getURL().toLowerCase().endsWith(".m3u"))
                                || (UD.getURL().toLowerCase().endsWith(".pls"))) {
                            if (loadPlaylist(UD.getURL())) {
                                config.setPlaylistFilename(UD.getURL());
                                playlist.begin();
                                fileList.initPlayList();
                                this.setCurrentSong(playlist.getCursor());
                                fileList.repaint();
                            }
                        }
                        // Remote file or stream.
                        else {
                            pli = new PlaylistItem(UD.getFile(), UD.getURL(), -1, false);
                        }
                        config.setLastURL(UD.getURL());
                    }
                }
            }

            if (pli != null) {
                playlist.removeAllItems();
                playlist.appendItem(pli);
                playlist.nextCursor();
                fileList.initPlayList();
                this.setCurrentSong(pli);
            }
        }
        offScreenGraphics.drawImage(iconsImage[2], iconsLocation[0], iconsLocation[1], this);
        offScreenGraphics.drawImage(iconsImage[4], iconsLocation[2], iconsLocation[3], this);
        repaint();
    }

    /*---------------------------*/
    /*-- Play the current File --*/
    /*---------------------------*/
    else if (e.getActionCommand().equals("Play")) {
        if (playlist.isModified()) // playlist has been modified since we were last there, must update our cursor pos etc.
        {
            PlaylistItem pli = playlist.getCursor();
            if (pli == null) {
                playlist.begin();
                pli = playlist.getCursor();
            }
            this.setCurrentSong(pli);
            playlist.setModified(false);
            fileList.repaint();
        }

        // Resume is paused.
        if (playerState == PAUSE) {
            try {
                theSoundPlayer.resume();
            } catch (BasicPlayerException e1) {
                log.error("Cannot resume", e1);
            }
            playerState = PLAY;
            offScreenGraphics.drawImage(iconsImage[0], iconsLocation[0], iconsLocation[1], this);
            offScreenGraphics.drawImage(iconsImage[3], iconsLocation[2], iconsLocation[3], this);
            repaint();
        }

        // Stop if playing.
        else if (playerState == PLAY) {
            try {
                theSoundPlayer.stop();
            } catch (BasicPlayerException e1) {
                log.error("Cannot stop", e1);
            }
            playerState = PLAY;
            secondsAmount = 0;
            offScreenGraphics.drawImage(timeImage[0], minuteDLocation[0], minuteDLocation[1], this);
            offScreenGraphics.drawImage(timeImage[0], minuteLocation[0], minuteLocation[1], this);
            offScreenGraphics.drawImage(timeImage[0], secondDLocation[0], secondDLocation[1], this);
            offScreenGraphics.drawImage(timeImage[0], secondLocation[0], secondLocation[1], this);
            repaint();
            if (currentFileOrURL != null) {
                try {
                    if (currentIsFile == true)
                        theSoundPlayer.open(openFile(currentFileOrURL));
                    else
                        theSoundPlayer.open(new URL(currentFileOrURL));
                    theSoundPlayer.play();
                } catch (Exception ex) {
                    log.error("Cannot read file : " + currentFileOrURL, ex);
                    showMessage("INVALID FILE");
                }
            }
        } else if ((playerState == STOP) || (playerState == OPEN)) {
            try {
                theSoundPlayer.stop();
            } catch (BasicPlayerException e1) {
                log.error("Stop failed", e1);
            }
            if (currentFileOrURL != null) {
                try {
                    if (currentIsFile == true)
                        theSoundPlayer.open(openFile(currentFileOrURL));
                    else
                        theSoundPlayer.open(new URL(currentFileOrURL));
                    theSoundPlayer.play();
                    titleText = currentSongName.toUpperCase();

                    // Get bitrate, samplingrate, channels, time in the following order :
                    // PlaylistItem, BasicPlayer (JavaSound SPI), Manual computation.
                    int bitRate = -1;
                    if (currentPlaylistItem != null)
                        bitRate = currentPlaylistItem.getBitrate();
                    if ((bitRate <= 0) && (audioInfo.containsKey("bitrate")))
                        bitRate = ((Integer) audioInfo.get("bitrate")).intValue();
                    if ((bitRate <= 0) && (audioInfo.containsKey("audio.framerate.fps"))
                            && (audioInfo.containsKey("audio.framesize.bytes"))) {
                        float FR = ((Float) audioInfo.get("audio.framerate.fps")).floatValue();
                        int FS = ((Integer) audioInfo.get("audio.framesize.bytes")).intValue();
                        bitRate = Math.round(FS * FR * 8);
                    }
                    int channels = -1;
                    if (currentPlaylistItem != null)
                        channels = currentPlaylistItem.getChannels();
                    if ((channels <= 0) && (audioInfo.containsKey("audio.channels")))
                        channels = ((Integer) audioInfo.get("audio.channels")).intValue();
                    float sampleRate = -1.0f;
                    if (currentPlaylistItem != null)
                        sampleRate = currentPlaylistItem.getSamplerate();
                    if ((sampleRate <= 0) && (audioInfo.containsKey("audio.samplerate.hz")))
                        sampleRate = ((Float) audioInfo.get("audio.samplerate.hz")).floatValue();
                    long lenghtInSecond = -1L;
                    if (currentPlaylistItem != null)
                        lenghtInSecond = currentPlaylistItem.getLength();
                    if ((lenghtInSecond <= 0) && (audioInfo.containsKey("duration")))
                        lenghtInSecond = ((Long) audioInfo.get("duration")).longValue() / 1000000;
                    if ((lenghtInSecond <= 0) && (audioInfo.containsKey("audio.length.bytes"))) {
                        // Try to compute time length.
                        lenghtInSecond = (long) Math.round(getTimeLengthEstimation(audioInfo) / 1000);
                        if (lenghtInSecond > 0) {
                            int minutes = (int) Math.floor(lenghtInSecond / 60);
                            int hours = (int) Math.floor(minutes / 60);
                            minutes = minutes - hours * 60;
                            int seconds = (int) (lenghtInSecond - minutes * 60 - hours * 3600);
                            if (seconds >= 10)
                                titleText = "(" + minutes + ":" + seconds + ") " + titleText;
                            else
                                titleText = "(" + minutes + ":0" + seconds + ") " + titleText;
                        }
                    }
                    bitRate = Math.round((bitRate / 1000));
                    sampleRateImage = (new Taftb(fontIndex, imText, fontWidth, fontHeight, 0,
                            "" + Math.round((sampleRate / 1000)))).getBanner();
                    if (bitRate > 999) {
                        bitRate = (int) (bitRate / 100);
                        bitsRateImage = (new Taftb(fontIndex, imText, fontWidth, fontHeight, 0,
                                "" + bitRate + "H")).getBanner();
                    } else
                        bitsRateImage = (new Taftb(fontIndex, imText, fontWidth, fontHeight, 0, "" + bitRate))
                                .getBanner();
                    offScreenGraphics.drawImage(sampleRateImage, sampleRateLocation[0], sampleRateLocation[1],
                            this);
                    offScreenGraphics.drawImage(bitsRateImage, bitsRateLocation[0], bitsRateLocation[1], this);
                    if (channels == 2) {
                        offScreenGraphics.drawImage(activeModeImage[0], stereoLocation[0], stereoLocation[1],
                                this);
                    } else if (channels == 1) {
                        offScreenGraphics.drawImage(activeModeImage[1], monoLocation[0], monoLocation[1], this);
                    }
                    showTitle(titleText);
                    offScreenGraphics.drawImage(timeImage[0], minuteDLocation[0], minuteDLocation[1], this);
                    offScreenGraphics.drawImage(timeImage[0], minuteLocation[0], minuteLocation[1], this);
                    offScreenGraphics.drawImage(timeImage[0], secondDLocation[0], secondDLocation[1], this);
                    offScreenGraphics.drawImage(timeImage[0], secondLocation[0], secondLocation[1], this);

                    offScreenGraphics.drawImage(iconsImage[0], iconsLocation[0], iconsLocation[1], this);
                    offScreenGraphics.drawImage(iconsImage[3], iconsLocation[2], iconsLocation[3], this);
                } catch (BasicPlayerException bpe) {
                    log.info("Stream error :" + currentFileOrURL, bpe);
                    showMessage("INVALID FILE");
                } catch (MalformedURLException mue) {
                    log.info("Stream error :" + currentFileOrURL, mue);
                    showMessage("INVALID FILE");
                }

                // Set pan/gain.
                try {
                    theSoundPlayer.setGain(((double) gainValue / (double) maxGain));
                    theSoundPlayer.setPan((float) balanceValue);
                } catch (BasicPlayerException e2) {
                    log.info("Cannot set control", e2);
                }

                playerState = PLAY;
                repaint();
                log.info(titleText);
            }
        }
    }

    /*-----------------------------------*/
    /*-- Pause/Resume the current File --*/
    /*-----------------------------------*/
    else if (e.getActionCommand().equals("Pause")) {
        if (playerState == PLAY) {
            try {
                theSoundPlayer.pause();
            } catch (BasicPlayerException e1) {
                log.error("Cannot pause", e1);
            }
            playerState = PAUSE;
            offScreenGraphics.drawImage(iconsImage[1], iconsLocation[0], iconsLocation[1], this);
            offScreenGraphics.drawImage(iconsImage[4], iconsLocation[2], iconsLocation[3], this);
            repaint();
        } else if (playerState == PAUSE) {
            try {
                theSoundPlayer.resume();
            } catch (BasicPlayerException e1) {
                log.info("Cannot resume", e1);
            }
            playerState = PLAY;
            offScreenGraphics.drawImage(iconsImage[0], iconsLocation[0], iconsLocation[1], this);
            offScreenGraphics.drawImage(iconsImage[3], iconsLocation[2], iconsLocation[3], this);
            repaint();
        }
    }

    /*------------------*/
    /*-- Stop to play --*/
    /*------------------*/
    else if (e.getActionCommand().equals("Stop")) {
        if ((playerState == PAUSE) || (playerState == PLAY)) {
            try {
                theSoundPlayer.stop();
            } catch (BasicPlayerException e1) {
                log.info("Cannot stop", e1);
            }
            playerState = STOP;
            secondsAmount = 0;
            acPosBar.setLocation(posBarBounds[0], posBarLocation[1]);
            offScreenGraphics.drawImage(iconsImage[2], iconsLocation[0], iconsLocation[1], this);
            offScreenGraphics.drawImage(iconsImage[4], iconsLocation[2], iconsLocation[3], this);
            repaint();
        }
    }

    /*----------*/
    /*-- Next --*/
    /*----------*/
    else if (e.getActionCommand().equals("Next")) {
        // Try to get next song from the playlist
        playlist.nextCursor();
        fileList.nextCursor();
        PlaylistItem pli = playlist.getCursor();
        this.setCurrentSong(pli);
    }

    /*--------------*/
    /*-- Previous --*/
    /*--------------*/
    else if (e.getActionCommand().equals("Previous")) {
        // Try to get previous song from the playlist
        playlist.previousCursor();
        fileList.nextCursor();
        PlaylistItem pli = playlist.getCursor();
        this.setCurrentSong(pli);
    }

    /*--------------------------------------------*/
    /*--     Exit window through Exit Button    --*/
    /*--------------------------------------------*/
    else if (e.getActionCommand().equals("Exit")) {
        closePlayer();
    }

    /*----------------------------------------------------*/
    /*--     Minimize window through Minimize Button    --*/
    /*----------------------------------------------------*/
    else if (e.getActionCommand().equals("Minimize")) {
        // Iconify top frame.
        topFrame.setLocation(OrigineX, OrigineY);
        //topFrame.setState(Frame.ICONIFIED);
        //topFrame.show();
    }

    /*--------------------------------------------*/
    /*-- Move full window through its Title Bar --*/
    /*--------------------------------------------*/
    else if (e.getActionCommand().equals("TitleBar")) {
        //log.info("X="+acTitle.getMouseX()+" Y="+acTitle.getMouseY());
        if (acTitleBar.isMousePressed() == false)
            FirstDrag = true;
        else {
            int DeltaX = 0;
            int DeltaY = 0;
            if (FirstDrag == false) {
                DeltaX = acTitleBar.getMouseX() - XDrag;
                DeltaY = acTitleBar.getMouseY() - YDrag;
                XDrag = acTitleBar.getMouseX() - DeltaX;
                YDrag = acTitleBar.getMouseY() - DeltaY;
                OrigineX = OrigineX + DeltaX;
                OrigineY = OrigineY + DeltaY;

                if (config.isScreenLimit()) {
                    // Keep player window in screen
                    if (OrigineX < 0)
                        OrigineX = 0;
                    if (OrigineY < 0)
                        OrigineY = 0;
                    if (screenWidth != -1) {
                        if (OrigineX > screenWidth - WinWidth)
                            OrigineX = screenWidth - WinWidth;
                    }
                    if (screenHeight != -1) {
                        if (OrigineY > screenHeight - WinHeight)
                            OrigineY = screenHeight - WinHeight;
                    }
                }
                // Moves top frame.
                topFrame.setLocation(OrigineX, OrigineY);
                topFrame.setSize(0, 0);
                // Moves the main window + playlist
                setLocation(OrigineX, OrigineY);
                fileList.setLocation(OrigineX, OrigineY + WinHeight);
                int factor = 1;
                if (config.isPlaylistEnabled())
                    factor = 2;
                equalizer.setLocation(OrigineX, OrigineY + WinHeight * factor);
            } else {
                FirstDrag = false;
                XDrag = acTitleBar.getMouseX();
                YDrag = acTitleBar.getMouseY();
            }
        }
    }
    /*-----------------------------------------*/
    /*--     Playlist window hide/display    --*/
    /*-----------------------------------------*/
    else if (e.getActionCommand().equals("Playlist")) {
        if (acPlaylist.getCheckboxState()) {
            config.setPlaylistEnabled(true);
            if (config.isEqualizerEnabled()) {
                equalizer.setLocation(OrigineX, OrigineY + WinHeight * 2);
            }
            fileList.setVisible(true);
        } else {
            config.setPlaylistEnabled(false);
            fileList.setVisible(false);
            if (config.isEqualizerEnabled()) {
                equalizer.setLocation(OrigineX, OrigineY + WinHeight);
            }
        }
    }

    /*--------------------------------------*/
    /*--     Playlist window equalizer    --*/
    /*--------------------------------------*/
    else if (e.getActionCommand().equals("Equalizer")) {
        if (acEqualizer.getCheckboxState()) {
            config.setEqualizerEnabled(true);
            int factor = 1;
            if (config.isPlaylistEnabled())
                factor = 2;
            equalizer.setLocation(OrigineX, OrigineY + WinHeight * factor);
            equalizer.setVisible(true);
        } else {
            config.setEqualizerEnabled(false);
            equalizer.setVisible(false);
        }
    }

    /*--------------------*/
    /*--     Shuffle    --*/
    /*--------------------*/
    else if (e.getActionCommand().equals("Shuffle")) {
        if (acShuffle.getCheckboxState()) {
            config.setShuffleEnabled(true);
            if (playlist != null) {
                playlist.shuffle();
                fileList.initPlayList();
                // Play from the top
                PlaylistItem pli = playlist.getCursor();
                this.setCurrentSong(pli);
            }
        } else {
            config.setShuffleEnabled(false);
        }
    }
    /*-------------------*/
    /*--     Repeat    --*/
    /*-------------------*/
    else if (e.getActionCommand().equals("Repeat")) {
        if (acRepeat.getCheckboxState()) {
            config.setRepeatEnabled(true);
        } else {
            config.setRepeatEnabled(false);
        }
    }
    /*----------------------*/
    /*--     Equalizer    --*/
    /*----------------------*/
    else if (e.getActionCommand().equals("Equalizer")) {
        if (acEqualizer.getCheckboxState()) {
            config.setEqualizerEnabled(true);
        } else {
            config.setEqualizerEnabled(false);
        }
    }

    else {
        // Unknown action.
    }
}

From source file:pl.edu.icm.visnow.lib.utils.ImageUtilities.java

public static void centerFrame(Frame f) {
    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension d = f.getSize();//from www. j a  v a 2 s .com
    int x = (screen.width - d.width) / 2;
    int y = (screen.height - d.height) / 2;
    f.setLocation(x, y);
}