Example usage for javax.swing JDialog setLocationRelativeTo

List of usage examples for javax.swing JDialog setLocationRelativeTo

Introduction

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

Prototype

public void setLocationRelativeTo(Component c) 

Source Link

Document

Sets the location of the window relative to the specified component according to the following scenarios.

Usage

From source file:Main.java

public static boolean showModalDialogOnEDT(JComponent contents, String title, String okButtonMessage,
        String cancelButtonMessage, ModalityType modalityType, final boolean systemExitOnDisposed) {

    class Result {
        boolean OK = false;
    }/*from   ww w  . j av  a  2s . c  om*/
    final Result result = new Result();

    final JDialog dialog = new JDialog((Frame) null, title, true) {
        @Override
        public void dispose() {
            super.dispose();
            if (systemExitOnDisposed) {
                System.exit(0);
            }
        }
    };

    // ensure it doesn't block other dialogs
    if (modalityType != null) {
        dialog.setModalityType(modalityType);
    }

    // See http://stackoverflow.com/questions/1343542/how-do-i-close-a-jdialog-and-have-the-window-event-listeners-be-notified
    dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

    JPanel buttonPane = new JPanel();
    buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
    if (okButtonMessage != null) {
        buttonPane.add(new JButton(new AbstractAction(okButtonMessage) {

            @Override
            public void actionPerformed(ActionEvent e) {
                result.OK = true;
                dialog.dispose();
            }
        }));
    }

    if (cancelButtonMessage != null) {
        buttonPane.add(new JButton(new AbstractAction(cancelButtonMessage) {

            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        }));
    }

    JPanel panel = new JPanel();
    panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    panel.setLayout(new BorderLayout());
    panel.add(contents, BorderLayout.CENTER);
    panel.add(buttonPane, BorderLayout.SOUTH);

    // startup frame
    dialog.getContentPane().add(panel);
    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    dialog.pack();

    // This hopefully centres the dialog even though the parameter is null 
    // see http://stackoverflow.com/questions/213266/how-do-i-center-a-jdialog-on-screen
    dialog.setLocationRelativeTo(null);
    dialog.setVisible(true);

    return result.OK;
}

From source file:IHM.GialogGraph.java

public void Show() {
    VisualizationViewer<String, String> vv;
    vv = new VisualizationViewer<>(new CircleLayout<String, String>(JungGraph), dim);

    Transformer<String, String> transformer = new Transformer<String, String>() {
        @Override//from  ww  w  .  j a  v a 2 s .  c om
        public String transform(String arg0) {
            return arg0;
        }
    };
    vv.getRenderContext().setVertexLabelTransformer(transformer);
    transformer = new Transformer<String, String>() {
        @Override
        public String transform(String arg0) {
            return arg0;
        }
    };
    vv.getRenderContext().setEdgeLabelTransformer(transformer);
    vv.getRenderer().setVertexRenderer(new MyRenderer());
    DefaultModalGraphMouse<String, Number> graphMouse = new DefaultModalGraphMouse<String, Number>();
    vv.setGraphMouse(graphMouse);
    graphMouse.setMode(ModalGraphMouse.Mode.PICKING);

    JDialog frame = new JDialog(MymainWidow);
    frame.getContentPane().add(vv);
    frame.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    frame.addWindowListener(new WindowListener() {

        @Override
        public void windowOpened(WindowEvent e) {

        }

        @Override
        public void windowClosing(WindowEvent e) {
            MymainWidow.enable();
        }

        @Override
        public void windowClosed(WindowEvent e) {
            MymainWidow.enable();
        }

        @Override
        public void windowIconified(WindowEvent e) {

        }

        @Override
        public void windowDeiconified(WindowEvent e) {

        }

        @Override
        public void windowActivated(WindowEvent e) {

        }

        @Override
        public void windowDeactivated(WindowEvent e) {

        }
    });
    frame.pack();
    frame.setLocationRelativeTo(MymainWidow);
    frame.setResizable(true);
    frame.setVisible(true);
}

From source file:net.sourceforge.processdash.ev.ui.ScheduleBalancingDialog.java

private void buildAndShowGUI() {
    chartData = null;/*from www.j  av  a 2  s. c  o  m*/
    int numScheduleRows = scheduleRows.size();

    sumUpTotalTime();
    originalTotalTime = totalRow.time;
    if (originalTotalTime == 0)
        // if the rows added up to zero, choose a nominal target total time
        // corresponding to 10 hours per included schedule
        originalTotalTime = numScheduleRows * 60 * 10;

    JPanel panel = new JPanel(new GridBagLayout());
    if (numScheduleRows == 1) {
        totalRow.rowLabel = scheduleRows.get(0).rowLabel;
    } else {
        for (int i = 0; i < numScheduleRows; i++)
            scheduleRows.get(i).addToPanel(panel, i);
        scheduleRows.get(numScheduleRows - 1).showPercentageTickMarks();
        addChartToPanel(panel, numScheduleRows + 1);
    }
    totalRow.addToPanel(panel, numScheduleRows);

    if (rowsAreEditable == false) {
        String title = TaskScheduleDialog.resources.getString("Balance.Read_Only_Title");
        JOptionPane.showMessageDialog(parent.frame, panel, title, JOptionPane.PLAIN_MESSAGE);

    } else {
        String title = TaskScheduleDialog.resources.getString("Balance.Editable_Title");
        JDialog dialog = new JDialog(parent.frame, title, true);
        addButtons(dialog, panel, numScheduleRows + 2);
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        dialog.getContentPane().add(panel);
        dialog.pack();
        dialog.setLocationRelativeTo(parent.frame);
        dialog.setResizable(true);
        dialog.setVisible(true);
    }
}

From source file:net.sf.jabref.gui.openoffice.StyleSelectDialog.java

private void displayStyle(OOBibStyle style) {
    // Make a dialog box to display the contents:
    final JDialog dd = new JDialog(diag, style.getName(), true);

    JTextArea ta = new JTextArea(style.getLocalCopy());
    ta.setEditable(false);//from  w  w w  . j a  va  2s  .  c  om
    JScrollPane sp = new JScrollPane(ta);
    sp.setPreferredSize(new Dimension(700, 500));
    dd.getContentPane().add(sp, BorderLayout.CENTER);
    JButton okButton = new JButton(Localization.lang("OK"));
    ButtonBarBuilder bb = new ButtonBarBuilder();
    bb.addGlue();
    bb.addButton(okButton);
    bb.addGlue();
    bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    dd.getContentPane().add(bb.getPanel(), BorderLayout.SOUTH);
    okButton.addActionListener(actionEvent -> dd.dispose());
    dd.pack();
    dd.setLocationRelativeTo(diag);
    dd.setVisible(true);
}

From source file:org.moeaframework.analysis.plot.Plot.java

/**
 * Displays the chart in a blocking JDialog.
 * /*from   w  ww. j  ava2s .co  m*/
 * @param width the width of the chart
 * @param height the height of the chart
 * @return the window that was created
 */
public JDialog showDialog(int width, int height) {
    JDialog frame = new JDialog();

    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(getChartPanel(), BorderLayout.CENTER);

    frame.setPreferredSize(new Dimension(width, height));
    frame.pack();

    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setTitle("MOEA Framework Plot");
    frame.setModalityType(ModalityType.APPLICATION_MODAL);
    frame.setVisible(true);

    return frame;
}

From source file:net.sf.taverna.t2.workbench.ui.servicepanel.actions.AddServiceProviderAction.java

@Override
public void actionPerformed(ActionEvent e) {
    if (confProvider instanceof CustomizedConfigurePanelProvider) {
        final CustomizedConfigurePanelProvider provider = (CustomizedConfigurePanelProvider) confProvider;
        provider.createCustomizedConfigurePanel(new CustomizedConfigureCallBack() {
            @Override//from   www . jav  a 2  s.  c  o m
            public Configuration getTemplateConfig() {
                return (Configuration) provider.getConfiguration().clone();
            }

            @Override
            public ServiceDescriptionRegistry getServiceDescriptionRegistry() {
                return AddServiceProviderAction.this.getServiceDescriptionRegistry();
            }

            @Override
            public void newProviderConfiguration(Configuration providerConfig) {
                addNewProvider(providerConfig);
            }
        });
        return;
    }

    Configuration configuration;
    try {
        configuration = (Configuration) confProvider.getConfiguration().clone();
    } catch (Exception ex) {
        throw new RuntimeException("Can't clone configuration bean", ex);
    }
    JPanel buildEditor = buildEditor(configuration);
    String title = "Add " + confProvider.getName();
    JDialog dialog = new HelpEnabledDialog(getMainWindow(), title, true, null);
    JPanel iconPanel = new JPanel();
    iconPanel.add(new JLabel(confProvider.getIcon()), NORTH);
    dialog.add(iconPanel, WEST);
    dialog.add(buildEditor, CENTER);
    JPanel buttonPanel = new JPanel(new BorderLayout());
    final AddProviderAction addProviderAction = new AddProviderAction(configuration, dialog);
    JButton addProviderButton = new JButton(addProviderAction);
    buttonPanel.add(addProviderButton, WEST);

    dialog.add(buttonPanel, SOUTH);
    // When user presses "Return" key fire the action on the "Add" button
    addProviderButton.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent evt) {
            if (evt.getKeyCode() == VK_ENTER)
                addProviderAction.actionPerformed(null);
        }
    });
    dialog.getRootPane().setDefaultButton(addProviderButton);

    // dialog.setSize(buttonPanel.getPreferredSize());
    dialog.pack();
    dialog.setLocationRelativeTo(owner);
    //      dialog.setLocation(owner.getLocationOnScreen().x + owner.getWidth(),
    //            owner.getLocationOnScreen().y + owner.getHeight());
    dialog.setVisible(true);
}

From source file:com.peterbochs.sourceleveldebugger.SourceLevelDebugger3.java

public void loadELF(String elfPaths[]) {
    final JDialog dialog = new JDialog(peterBochsDebugger, true);
    JLabel jLabel = new JLabel();
    jLabel.setHorizontalAlignment(JTextField.CENTER);
    dialog.setContentPane(jLabel);/*from ww  w  .  ja  v a 2  s . c o  m*/
    dialog.setSize(500, 100);
    dialog.setLocationRelativeTo(peterBochsDebugger);
    new Thread(new Runnable() {
        @Override
        public void run() {
            dialog.setVisible(true);
        }
    }).start();

    //$hide>>$
    if (Global.debug) {
        System.out.println("load elf");
    }

    for (String elfPath : elfPaths) {
        File file;
        long memoryOffset = 0;

        if (elfPath.contains("=")) {
            memoryOffset = CommonLib.string2long(elfPath.split("=")[1]);
            file = new File(elfPath.split("=")[0]);
        } else {
            file = new File(elfPath);
        }
        loadELF(file, dialog, memoryOffset);
    }

    if (Global.debug) {
        System.out.println("load elf end");
    }
    //$hide<<$

    dialog.setVisible(false);
}

From source file:net.mariottini.swing.JFontChooser.java

/**
 * Show a "Choose Font" dialog with the specified title and modality.
 * //from w w w . j a va2 s  .  c o m
 * @param parent
 *          the parent component, or null to use a default root frame as parent.
 * @param title
 *          the title for the dialog.
 * @param modal
 *          true to show a modal dialog, false to show a non-modal dialog (in this case the
 *          function will return immediately after making visible the dialog).
 * @return <code>APPROVE_OPTION</code> if the user chose a font, <code>CANCEL_OPTION</code> if the
 *         user canceled the operation. <code>CANCEL_OPTION</code> is always returned for a
 *         non-modal dialog, use an ActionListener to be notified when the user approves/cancels
 *         the dialog.
 * @see #APPROVE_OPTION
 * @see #CANCEL_OPTION
 * @see #addActionListener
 */
public int showDialog(Component parent, String title, boolean modal) {
    final int[] result = new int[] { CANCEL_OPTION };
    while (parent != null && !(parent instanceof Window)) {
        parent = parent.getParent();
    }
    final JDialog d;
    if (parent instanceof Frame) {
        d = new JDialog((Frame) parent, title, modal);
    } else if (parent instanceof Dialog) {
        d = new JDialog((Dialog) parent, title, modal);
    } else {
        d = new JDialog();
        d.setTitle(title);
        d.setModal(modal);
    }
    final ActionListener[] listener = new ActionListener[1];
    listener[0] = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (e.getActionCommand().equals(APPROVE_SELECTION)) {
                result[0] = APPROVE_OPTION;
            }
            removeActionListener(listener[0]);
            d.setContentPane(new JPanel());
            d.setVisible(false);
            d.dispose();
        }
    };
    addActionListener(listener[0]);
    d.setComponentOrientation(getComponentOrientation());
    d.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
    d.getContentPane().add(this, BorderLayout.CENTER);
    d.pack();
    d.setLocationRelativeTo(parent);
    d.setVisible(true);
    return result[0];
}

From source file:com.biosis.biosislite.vistas.AsignarPermiso.java

private void imprimirBoletaViaje(AsignacionPermiso asignacion) {
    File reporte = new File("reportes/permiso_comision-servicios.jasper");

    List<AsignacionPermiso> listadoReporteAsignacion = new ArrayList();
    listadoReporteAsignacion.add(asignacion);

    Map<String, Object> parametros = new HashMap<>();
    parametros.put("reporte_ususario", UsuarioActivo.getUsuario().getLogin());

    Departamento area = asignacion.getEmpleado().getAreaEmpleadoList().get(0).getDepartamento();
    if (area != null) {
        parametros.put("area", area.getNombre());
    }/*w ww . j  a va2 s.c o  m*/

    //        AsignarVacacion vac = new AsignarVacacion();
    long dias = this.fechasAlong(asignacion.getPermiso().getFechaInicio(),
            asignacion.getPermiso().getFechaFin());
    parametros.put("dias", dias);

    //Parametros del viaje
    Viaje viaje = vsc.buscarPorPermiso(asignacion.getPermiso());

    if (viaje != null) {
        parametros.put("alimentacion", viaje.getAlimentacion());
        parametros.put("alojamiento", viaje.getAlojamiento());
        parametros.put("movilidad", viaje.getMovilidad());
        parametros.put("combustible", viaje.getCombustible());
        parametros.put("dias_alimentacion", viaje.getDiasAlimentacion());
        parametros.put("dias_alojamiento", viaje.getDiasAlojamiento());
        parametros.put("dias_movilidad", viaje.getDiasMovLocal());
        //            if (asignacion.getEmpleado().getAreaEmpleadoList().get(0).getDepartamento().getDepartamento().getNombre() != null) {
        //                parametros.put("gerencia", asignacion.getEmpleado().getAreaEmpleadoList().get(0).getDepartamento().getDepartamento().getNombre());
        //            } else {
        parametros.put("gerencia",
                asignacion.getEmpleado().getAreaEmpleadoList().get(0).getGerencia().getNombre());
        //            }
        parametros.put("centro_costo", viaje.getCentroCosto());
        parametros.put("ubigeo", viaje.getDestino());
        parametros.put("cargo", asignacion.getEmpleado().getPuestoList().get(0).getPuesto().getNombre());

        double total = (viaje.getAlimentacion() * viaje.getDiasAlimentacion())
                + (viaje.getAlojamiento() * viaje.getDiasAlojamiento())
                + (viaje.getMovilidad() * viaje.getDiasMovLocal()) + viaje.getCombustible();

        parametros.put("total", total);
    }

    //Fin de parametros del viaje
    Component contentPane = reporteador.obtenerReporte(listadoReporteAsignacion, reporte, parametros);
    Frame principal = JOptionPane.getRootFrame();
    JDialog visor = new JDialog(principal, "Reporte", true);
    visor.setSize(contentPane.getSize());
    //        visor.setSize(ventana.getSize().width, ventana.getSize().height);
    visor.getContentPane().add(contentPane);
    visor.setLocationRelativeTo(this);

    //            visor.setUndecorated(true);
    visor.setBounds(GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds());
    visor.setVisible(true);
    visor.setAlwaysOnTop(true);
    //        reporteador.getReporte(reporte, parametros, listado) //        reporteador.setConn(controlador.getDao().getConexion());
    //        reporteador.generarReporte(reporte, parametros, JOptionPane.getFrameForComponent(this));
}

From source file:components.DialogDemo.java

/** Creates the panel shown by the second tab. */
private JPanel createFeatureDialogBox() {
    final int numButtons = 5;
    JRadioButton[] radioButtons = new JRadioButton[numButtons];
    final ButtonGroup group = new ButtonGroup();

    JButton showItButton = null;//from w ww.  j  a  va 2s. c  o m

    final String pickOneCommand = "pickone";
    final String textEnteredCommand = "textfield";
    final String nonAutoCommand = "nonautooption";
    final String customOptionCommand = "customoption";
    final String nonModalCommand = "nonmodal";

    radioButtons[0] = new JRadioButton("Pick one of several choices");
    radioButtons[0].setActionCommand(pickOneCommand);

    radioButtons[1] = new JRadioButton("Enter some text");
    radioButtons[1].setActionCommand(textEnteredCommand);

    radioButtons[2] = new JRadioButton("Non-auto-closing dialog");
    radioButtons[2].setActionCommand(nonAutoCommand);

    radioButtons[3] = new JRadioButton("Input-validating dialog " + "(with custom message area)");
    radioButtons[3].setActionCommand(customOptionCommand);

    radioButtons[4] = new JRadioButton("Non-modal dialog");
    radioButtons[4].setActionCommand(nonModalCommand);

    for (int i = 0; i < numButtons; i++) {
        group.add(radioButtons[i]);
    }
    radioButtons[0].setSelected(true);

    showItButton = new JButton("Show it!");
    showItButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String command = group.getSelection().getActionCommand();

            //pick one of many
            if (command == pickOneCommand) {
                Object[] possibilities = { "ham", "spam", "yam" };
                String s = (String) JOptionPane.showInputDialog(frame,
                        "Complete the sentence:\n" + "\"Green eggs and...\"", "Customized Dialog",
                        JOptionPane.PLAIN_MESSAGE, icon, possibilities, "ham");

                //If a string was returned, say so.
                if ((s != null) && (s.length() > 0)) {
                    setLabel("Green eggs and... " + s + "!");
                    return;
                }

                //If you're here, the return value was null/empty.
                setLabel("Come on, finish the sentence!");

                //text input
            } else if (command == textEnteredCommand) {
                String s = (String) JOptionPane.showInputDialog(frame,
                        "Complete the sentence:\n" + "\"Green eggs and...\"", "Customized Dialog",
                        JOptionPane.PLAIN_MESSAGE, icon, null, "ham");

                //If a string was returned, say so.
                if ((s != null) && (s.length() > 0)) {
                    setLabel("Green eggs and... " + s + "!");
                    return;
                }

                //If you're here, the return value was null/empty.
                setLabel("Come on, finish the sentence!");

                //non-auto-closing dialog
            } else if (command == nonAutoCommand) {
                final JOptionPane optionPane = new JOptionPane(
                        "The only way to close this dialog is by\n" + "pressing one of the following buttons.\n"
                                + "Do you understand?",
                        JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);

                //You can't use pane.createDialog() because that
                //method sets up the JDialog with a property change
                //listener that automatically closes the window
                //when a button is clicked.
                final JDialog dialog = new JDialog(frame, "Click a button", true);
                dialog.setContentPane(optionPane);
                dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                dialog.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent we) {
                        setLabel("Thwarted user attempt to close window.");
                    }
                });
                optionPane.addPropertyChangeListener(new PropertyChangeListener() {
                    public void propertyChange(PropertyChangeEvent e) {
                        String prop = e.getPropertyName();

                        if (dialog.isVisible() && (e.getSource() == optionPane)
                                && (JOptionPane.VALUE_PROPERTY.equals(prop))) {
                            //If you were going to check something
                            //before closing the window, you'd do
                            //it here.
                            dialog.setVisible(false);
                        }
                    }
                });
                dialog.pack();
                dialog.setLocationRelativeTo(frame);
                dialog.setVisible(true);

                int value = ((Integer) optionPane.getValue()).intValue();
                if (value == JOptionPane.YES_OPTION) {
                    setLabel("Good.");
                } else if (value == JOptionPane.NO_OPTION) {
                    setLabel("Try using the window decorations " + "to close the non-auto-closing dialog. "
                            + "You can't!");
                } else {
                    setLabel("Window unavoidably closed (ESC?).");
                }

                //non-auto-closing dialog with custom message area
                //NOTE: if you don't intend to check the input,
                //then just use showInputDialog instead.
            } else if (command == customOptionCommand) {
                customDialog.setLocationRelativeTo(frame);
                customDialog.setVisible(true);

                String s = customDialog.getValidatedText();
                if (s != null) {
                    //The text is valid.
                    setLabel("Congratulations!  " + "You entered \"" + s + "\".");
                }

                //non-modal dialog
            } else if (command == nonModalCommand) {
                //Create the dialog.
                final JDialog dialog = new JDialog(frame, "A Non-Modal Dialog");

                //Add contents to it. It must have a close button,
                //since some L&Fs (notably Java/Metal) don't provide one
                //in the window decorations for dialogs.
                JLabel label = new JLabel("<html><p align=center>" + "This is a non-modal dialog.<br>"
                        + "You can have one or more of these up<br>" + "and still use the main window.");
                label.setHorizontalAlignment(JLabel.CENTER);
                Font font = label.getFont();
                label.setFont(label.getFont().deriveFont(font.PLAIN, 14.0f));

                JButton closeButton = new JButton("Close");
                closeButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        dialog.setVisible(false);
                        dialog.dispose();
                    }
                });
                JPanel closePanel = new JPanel();
                closePanel.setLayout(new BoxLayout(closePanel, BoxLayout.LINE_AXIS));
                closePanel.add(Box.createHorizontalGlue());
                closePanel.add(closeButton);
                closePanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 5));

                JPanel contentPane = new JPanel(new BorderLayout());
                contentPane.add(label, BorderLayout.CENTER);
                contentPane.add(closePanel, BorderLayout.PAGE_END);
                contentPane.setOpaque(true);
                dialog.setContentPane(contentPane);

                //Show it.
                dialog.setSize(new Dimension(300, 150));
                dialog.setLocationRelativeTo(frame);
                dialog.setVisible(true);
            }
        }
    });

    return createPane(moreDialogDesc + ":", radioButtons, showItButton);
}