List of usage examples for javax.swing JOptionPane showOptionDialog
@SuppressWarnings("deprecation") public static int showOptionDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon, Object[] options, Object initialValue) throws HeadlessException
initialValue
parameter and the number of choices is determined by the optionType
parameter. From source file:interfaces.InterfazPrincipal.java
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura(); ArrayList<String[]> listado = controladorFlujoFactura.getTodosFlujo_Factura(""); DefaultTableModel modelo = (DefaultTableModel) TablaDeReporteDiario.getModel(); if (modelo.getRowCount() > 0) { for (int k = modelo.getRowCount() - 1; k > -1; k--) { modelo.removeRow(k);/* www . j ava 2 s . com*/ } } int contador = 1; double abono = 0; double deuda = 0; for (int i = 0; i < listado.size(); i++) { String[] fila = listado.get(i); String[] partirEspacios = fila[3].split("\\s"); //El primer string es la fecha sin hora //Ahora esparamos por - String[] tomarAgeMesDia = partirEspacios[0].split("-"); //Realizar filtro int ageConsulta = Integer.parseInt(tomarAgeMesDia[0]); int mesConsulta = Integer.parseInt(tomarAgeMesDia[1]); int diaConsulta = Integer.parseInt(tomarAgeMesDia[2]); Calendar fechaDeLaBD = new GregorianCalendar(ageConsulta, mesConsulta, diaConsulta); int anioInicial = fechaReporteDiario.getSelectedDate().get(Calendar.YEAR); int mesInicial = fechaReporteDiario.getSelectedDate().get(Calendar.MONTH) + 1; int diaInicial = fechaReporteDiario.getSelectedDate().get(Calendar.DAY_OF_MONTH); Calendar fechaInicialRango = new GregorianCalendar(anioInicial, mesInicial, diaInicial); //fechaReporteDiarioHasta int anioFinal = fechaReporteDiarioHasta.getSelectedDate().get(Calendar.YEAR); int mesFinal = fechaReporteDiarioHasta.getSelectedDate().get(Calendar.MONTH) + 1; int diaFinal = fechaReporteDiarioHasta.getSelectedDate().get(Calendar.DAY_OF_MONTH); Calendar fechaFinalRango = new GregorianCalendar(anioFinal, mesFinal, diaFinal); //System.out.println("antes"); //System.out.println("Va a comparar" + fechaDeLaBD.toString()); //System.out.println(" con " + fechaInicialRango.toString()); if (fechaDeLaBD.compareTo(fechaInicialRango) >= 0 && fechaDeLaBD.compareTo(fechaFinalRango) <= 0) { //System.out.println("Entra"); Object[] row = new Object[5]; row[0] = (contador); contador++; row[1] = fila[1]; row[2] = fila[3]; row[3] = fila[2]; row[4] = fila[4]; modelo.addRow(row); //flujo_id","factura_id","tipo_flujo","fecha","valor" /*System.out.println("fila 0" + fila[0]); System.out.println("fila 1" + fila[1]); System.out.println("fila 2" + fila[2]); System.out.println("fila 3" + fila[3]);*/ if (fila[2].equals("abono")) { abono += Double.parseDouble(fila[4]); } else { deuda += Double.parseDouble(fila[4]); } ; } } ReporteDiarioAbono.setText(abono + ""); ReporteDiarioDeuda.setText(deuda + ""); TablaDeReporteDiario.setModel(modelo); Object opciones[] = { "Cerrar", "Imprimir", "Guardar en disco" }; int opcion = JOptionPane.showOptionDialog(this, "Se ha generado el diario solicitado\nQue desea hacer?", "Elija una opcin", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, opciones, null); GenerarReporteDiario generarReporteDiario = new GenerarReporteDiario(); switch (opcion) { case 1: generarReporteDiario.imprimiDiario(fechaReporteDiario.getSelectedDate(), fechaReporteDiarioHasta.getSelectedDate(), modelo, this); break; case 2: PDDocument documento = generarReporteDiario.crearDiario(fechaReporteDiario.getSelectedDate(), fechaReporteDiarioHasta.getSelectedDate(), modelo, this); JFileChooser fc = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Archivo PDF", "pdf", "text"); fc.setFileFilter(filter); fc.showSaveDialog(this); if (fc.getSelectedFile() != null) { File selectedFile = fc.getSelectedFile(); try { documento.save(selectedFile + ".pdf"); JOptionPane.showMessageDialog(this, "El archivo ha sido guardado en disco"); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "EL Archivo no se puede leer!"); } } break; default: break; } }
From source file:edu.ku.brc.specify.dbsupport.SpecifySchemaUpdateService.java
/** * Launches dialog for Importing and Exporting Forms and Resources. *//*from w w w.j a v a 2s . c o m*/ public static boolean askToUpdateSchema() { if (SubPaneMgr.getInstance().aboutToShutdown()) { Object[] options = { getResourceString("CONTINUE"), //$NON-NLS-1$ getResourceString("CANCEL") //$NON-NLS-1$ }; return JOptionPane.YES_OPTION == JOptionPane.showOptionDialog(UIRegistry.getTopWindow(), getLocalizedMessage(mkKey("DB_SCH_UP")), //$NON-NLS-1$ getResourceString(mkKey("DB_SCH_UP_TITLE")), //$NON-NLS-1$ JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); } return false; }
From source file:interfazGrafica.loginInterface.java
private void ventaCrearVentaButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ventaCrearVentaButtonActionPerformed // TODO add your handling code here: Venta venta = new Venta(); Comprador comprador = new Comprador(); Operaciones operacion = new Operaciones(); String id_usuario = (String) codVendedorVender.getText(); String id_vehiculo = (String) codVehiculoVender.getText(); String id_comprador = (String) codCompradorVender.getText(); String fecha_venta = operacion.obtenerFecha(); Object[] options = { "Pagar", "Cancelar" }; int n = JOptionPane.showOptionDialog(null, "Est a punto de confirmar la venta por un valor de: " + new Vehiculo().valorVehiculoIVA(id_vehiculo) + "\nDesea confirmar el pago?", "Confirmar pago", WIDTH, HEIGHT, null, options, options[1]); boolean bool; bool = (id_usuario.isEmpty() || id_vehiculo.isEmpty() || id_comprador.isEmpty()); if (!bool) {/*from www .ja va 2s . co m*/ if (n == 0) { cedulaIngresarCliente.setText(id_comprador); if (!comprador.existeComprador(id_comprador)) { ingresarUsuarioFrame.setVisible(true); JOptionPane.showMessageDialog(null, "El comprador no se encuentra registrado\nPor favor ingrese los datos."); } else { venta.crearVenta(id_usuario, id_vehiculo, id_comprador, fecha_venta); JOptionPane.showMessageDialog(null, "Factura generada!", "Factura", JOptionPane.INFORMATION_MESSAGE); int codVenta = Integer.parseInt(codVentaVender.getText()); double valorTotal = new Vehiculo().valorVehiculoIVA(id_vehiculo); venta.generarFactura(codVenta, valorTotal); limpiarCrearVenta(); } } else { JOptionPane.showMessageDialog(null, "Error en el pago"); } } else { JOptionPane.showMessageDialog(null, "No deje espacios vacios"); } codVentaVender.setText(venta.buscarUltimoCodigo()); }
From source file:interfaces.InterfazPrincipal.java
private void tablaUsuariosDelSistemaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaUsuariosDelSistemaMouseClicked // TODO add your handling code here: String opcionHabilitar = "Habilitar"; String nombreUsuario = String .valueOf(tablaUsuariosDelSistema.getValueAt(tablaUsuariosDelSistema.getSelectedRow(), 0)); String estado = String .valueOf(tablaUsuariosDelSistema.getValueAt(tablaUsuariosDelSistema.getSelectedRow(), 2)); if (estado.equals("Habilitado")) { opcionHabilitar = "Deshabilitar"; }/* ww w . j av a2 s . co m*/ Object[] opciones = { "Cancelar", "Editar", opcionHabilitar }; final ControladorUsuarios controladorUsuarios = new ControladorUsuarios(); final Usuarios usuarioSelecionado = controladorUsuarios.obtenerUsuario(nombreUsuario); if (nombreUsuario.equals("admin") || nombreUsuario.equals(JTextFieldnombreDeUsuario.getText())) { JOptionPane.showMessageDialog(this, "No se puede editarse a si mismo o el usuario administrador del sistema", "Mensaje del sistema", JOptionPane.WARNING_MESSAGE); } else { int opcionElegida = JOptionPane.showOptionDialog(this, "Por favor elija una opcin", "Editar cliente", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, opciones, null); switch (opcionElegida) { case 1: final JDialog dialogoEditar = new JDialog(this); dialogoEditar.setTitle("Editar usuario"); dialogoEditar.setSize(400, 310); dialogoEditar.setResizable(false); JPanel panelDialogo = new JPanel(); panelDialogo.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; JLabel editarTextoPrincipalDialogo = new JLabel("Editar clientes"); c.gridx = 0; c.gridy = 0; c.gridwidth = 2; c.insets = new Insets(15, 10, 40, 0); c.ipadx = 0; Font textoGrande = new Font("Arial", 1, 18); editarTextoPrincipalDialogo.setFont(textoGrande); panelDialogo.add(editarTextoPrincipalDialogo, c); c.insets = new Insets(0, 5, 10, 0); c.gridx = 0; c.gridy = 1; c.gridwidth = 1; c.ipadx = 0; JLabel editarNombreClienteDialogo = new JLabel("Login:"); panelDialogo.add(editarNombreClienteDialogo, c); final JTextField valorEditarNombreClienteDialogo = new JTextField(); c.gridx = 1; c.gridy = 1; c.gridwidth = 1; c.ipadx = 0; c.insets = new Insets(0, 5, 10, 0); valorEditarNombreClienteDialogo.setText(usuarioSelecionado.getLogin()); panelDialogo.add(valorEditarNombreClienteDialogo, c); c.gridx = 0; c.gridy = 2; c.gridwidth = 1; c.ipadx = 0; c.insets = new Insets(0, 5, 10, 0); JLabel editarPasswordClienteDialogo = new JLabel("Contrasea:"); panelDialogo.add(editarPasswordClienteDialogo, c); final JTextField valoreditarPasswordClienteDialogo = new JTextField(); c.gridx = 1; c.gridy = 2; c.gridwidth = 1; c.ipadx = 0; c.insets = new Insets(0, 5, 10, 0); panelDialogo.add(valoreditarPasswordClienteDialogo, c); c.gridx = 0; c.gridy = 3; c.gridwidth = 2; c.ipadx = 0; c.insets = new Insets(0, 5, 10, 0); JLabel mensajeEditarPassword = new JLabel( "Si no desea editar la contrasea deje este espacio en blanco:"); panelDialogo.add(mensajeEditarPassword, c); c.gridx = 0; c.gridy = 4; c.gridwidth = 1; c.ipadx = 0; c.insets = new Insets(0, 15, 10, 15); JButton botonGuardarClienteDialogo = new JButton("Guardar"); panelDialogo.add(botonGuardarClienteDialogo, c); c.gridx = 1; c.gridy = 4; c.gridwidth = 1; c.insets = new Insets(0, 15, 10, 15); c.ipadx = 0; JButton botonCerrarClienteDialogo = new JButton("Cancelar"); panelDialogo.add(botonCerrarClienteDialogo, c); botonCerrarClienteDialogo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialogoEditar.dispose(); } }); botonGuardarClienteDialogo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String nombreUsuario = valorEditarNombreClienteDialogo.getText(); usuarioSelecionado.setLogin(nombreUsuario); if (!valoreditarPasswordClienteDialogo.getText().equals("")) { usuarioSelecionado.setPassword(valoreditarPasswordClienteDialogo.getText()); } controladorUsuarios.modificarUsuario(usuarioSelecionado.getUser_id(), usuarioSelecionado.getLogin(), usuarioSelecionado.getPassword()); JOptionPane.showMessageDialog(dialogoEditar, "Se ha modificado el usuario con xito", "Mensaje del sistema", JOptionPane.INFORMATION_MESSAGE); generarTablaUsuarios(); dialogoEditar.dispose(); } }); dialogoEditar.add(panelDialogo); dialogoEditar.setVisible(true); break; case 2: if (estado.equals("Habilitado")) { usuarioSelecionado.setStatus('i'); } else { usuarioSelecionado.setStatus('e'); } controladorUsuarios.modificarEstadoUsuario(usuarioSelecionado); JOptionPane.showMessageDialog(this, "Se ha cambiado el estado del usuario", "Mensaje del sistema", JOptionPane.INFORMATION_MESSAGE); generarTablaUsuarios(); break; default: break; } } // TODO add your handling code here: }
From source file:interfazGrafica.loginInterface.java
private void crearCotizacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_crearCotizacionActionPerformed // TODO add your handling code here: Cotizaciones cotizacion = new Cotizaciones(); Comprador comprador = new Comprador(); Operaciones operacion = new Operaciones(); String id_usuario = (String) codVendedorCrearCot.getText(); String id_vehiculo = (String) codVehiculoCrearCot.getText(); String id_comprador = (String) codCompradorCrearCot.getText(); String fecha_coti = operacion.obtenerFecha(); Object[] options = { "Cotizar", "Cancelar" }; int n = JOptionPane.showOptionDialog(null, "Est a punto de confirmar la cotizacion por un valor de: " + new Vehiculo().valorVehiculoIVA(id_vehiculo) + "\nDesea confirmar la cotizacion ?", "Confirmar cotizacion", WIDTH, HEIGHT, null, options, options[1]); boolean bool; bool = (id_usuario.isEmpty() || id_vehiculo.isEmpty() || id_comprador.isEmpty()); if (!bool) {//from w w w . j a v a 2 s . co m if (n == 0) { cedulaIngresarCliente.setText(id_comprador); if (!comprador.existeComprador(id_comprador)) { ingresarUsuarioFrame.setVisible(true); JOptionPane.showMessageDialog(null, "El comprador no se encuentra registrado\nPor favor ingrese los datos."); } else { cotizacion.crearCoti(id_usuario, id_vehiculo, id_comprador, fecha_coti); //codVendedorCrearCot.setText(""); codVehiculoCrearCot.setText(""); codCompradorCrearCot.setText(""); JOptionPane.showMessageDialog(null, "Factura generada!", "Factura", JOptionPane.INFORMATION_MESSAGE); int codCot = Integer.parseInt(cotizacion.buscarUltimoCodigo()); double valorTotal = new Vehiculo().valorVehiculoIVA(id_vehiculo); Date fecha = cotizacion.obtenerFechaVencimiento(new Date()); cotizacion.generarFactura(--codCot, valorTotal, fecha); } } else { JOptionPane.showMessageDialog(null, "Error en la cotizacion"); } } else { JOptionPane.showMessageDialog(null, "Por favor complete todos los campos"); } //limpiarCrearVenta(); //venta.generarFactura(codVenta, valorTotal); //codVentaVender.setText(venta.buscarUltimoCodigo()); }
From source file:interfaces.InterfazPrincipal.java
private void tablaMostrarComprasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMostrarComprasMouseClicked // TODO add your handling code here: int fila = tablaMostrarCompras.getSelectedRow(); int identificacion = (int) tablaMostrarCompras.getValueAt(fila, 0); Object opciones[] = { "Editar", "Eliminar" }; ControladorCompraProveedor controladorCompraProveedor = new ControladorCompraProveedor(); ControladorFlujoCompras controladorFlujoCompras = new ControladorFlujoCompras(); int opcion = JOptionPane.showOptionDialog(this, "Que operacin desea realizar con la compra nmero " + identificacion + "?", "Mensaje del sistema", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, opciones, null);//from ww w . j a va 2 s. co m switch (opcion) { case 0: String valor = JOptionPane.showInputDialog("Desea cambiar el monto de la compra\nEl monto actual es: " + tablaMostrarCompras.getValueAt(fila, 3)); Double.parseDouble(valor); controladorCompraProveedor.editarCompraProveedor(String.valueOf(identificacion), valor); //Editar flujos //Registrar nueva deuda controladorFlujoCompras.registrarFlujoDeuda(String.valueOf(identificacion), valor); controladorFlujoCompras.registrarFlujoAbono(String.valueOf(identificacion), String.valueOf(tablaMostrarCompras.getValueAt(fila, 3))); tablaMostrarCompras.setValueAt(valor, fila, 3); try { } catch (Exception e) { JOptionPane.showMessageDialog(this, "El monto debe ser numrico", "Error", JOptionPane.ERROR_MESSAGE); } break; case 1: int confirmacion = JOptionPane.showConfirmDialog(this, "Quieres eliminar la compra nmero " + identificacion + "?"); if (confirmacion == JOptionPane.YES_OPTION) { controladorCompraProveedor .eliminarCompraProveedor(" where ID_Compra_Proveedor = " + identificacion); DefaultTableModel modeloTabla = (DefaultTableModel) tablaMostrarCompras.getModel(); modeloTabla.removeRow(fila); tablaMostrarCompras.setModel(modeloTabla); //Eliminar flujo controladorFlujoCompras.borrarFlujosDeUnaCompraPorIDDeCompra(String.valueOf(identificacion)); } break; default: break; } }
From source file:lu.fisch.unimozer.Diagram.java
public void exportPNG() { selectClass(null);/*from w ww. jav a 2 s .c om*/ JFileChooser dlgSave = new JFileChooser("Export diagram as PNG ..."); // propose name String uniName = directoryName.substring(directoryName.lastIndexOf('/') + 1).trim(); dlgSave.setSelectedFile(new File(uniName)); dlgSave.addChoosableFileFilter(new PNGFilter()); int result = dlgSave.showSaveDialog(frame); if (result == JFileChooser.APPROVE_OPTION) { String filename = dlgSave.getSelectedFile().getAbsoluteFile().toString(); if (!filename.substring(filename.length() - 4, filename.length()).toLowerCase().equals(".png")) { filename += ".png"; } File file = new File(filename); BufferedImage bi = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_4BYTE_ABGR); paint(bi.getGraphics()); try { ImageIO.write(bi, "png", file); } catch (Exception e) { JOptionPane.showOptionDialog(frame, "Error while saving the image!", "Error", JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null); } } }
From source file:src.gui.ItSIMPLE.java
/** * @return Returns the planAnalysisFramePanel. *///from w w w. j av a 2 s.c o m private ItFramePanel getPlanAnalysisFramePanel() { if (planAnalysisFramePanel == null) { planAnalysisFramePanel = new ItFramePanel(":: Plan Analysis", ItFramePanel.NO_MINIMIZE_MAXIMIZE); // tool bar JToolBar chartsToolBar = new JToolBar(); chartsToolBar.add(new JButton(drawChartAction)); // charts panel chartsPanel = new JPanel(); chartsPanel.setLayout(new BoxLayout(chartsPanel, BoxLayout.Y_AXIS)); ItFramePanel variableSelectionPanel = new ItFramePanel(".: Select variables to be tracked", ItFramePanel.NO_MINIMIZE_MAXIMIZE); //variableSelectionPanel.setBackground(new Color(151,151,157)); JSplitPane split = new JSplitPane(); split.setContinuousLayout(true); split.setOrientation(JSplitPane.HORIZONTAL_SPLIT); split.setDividerLocation(2 * screenSize.height / 3); split.setDividerSize(8); //split.setPreferredSize(new Dimension(screenSize.width/4-20, screenSize.height/2 - 50)); //split.setPreferredSize(new Dimension(screenSize.width/4-20, 120)); split.setLeftComponent(new JScrollPane(variablesPlanTree)); split.setRightComponent(new JScrollPane(selectedVariablesPlanTree)); variableSelectionPanel.setContent(split, false); //variableSelectionPanel.setParentSplitPane() //JPanel variableSelectionPanel = new JPanel(new BorderLayout()); //variableSelectionPanel.add(new JScrollPane(variablesPlanTree), BorderLayout.CENTER); //variableSelectionPanel.add(new JScrollPane(selectedVariablesPlanTree), BorderLayout.EAST); ItFramePanel variableGraphPanel = new ItFramePanel(".: Chart", ItFramePanel.NO_MINIMIZE_MAXIMIZE); variableGraphPanel.setContent(chartsPanel, true); JSplitPane mainvariablesplit = new JSplitPane(); mainvariablesplit.setContinuousLayout(true); mainvariablesplit.setOrientation(JSplitPane.VERTICAL_SPLIT); mainvariablesplit.setDividerLocation(150); mainvariablesplit.setDividerSize(8); //mainvariablesplit.setPreferredSize(new Dimension(screenSize.width/4-20, screenSize.height/2 - 50)); mainvariablesplit.setTopComponent(variableSelectionPanel); mainvariablesplit.setBottomComponent(variableGraphPanel); // main charts panel - used to locate the tool bar above the charts panel JPanel mainChartsPanel = new JPanel(new BorderLayout()); mainChartsPanel.add(chartsToolBar, BorderLayout.NORTH); //mainChartsPanel.add(new JScrollPane(chartsPanel), BorderLayout.CENTER); mainChartsPanel.add(mainvariablesplit, BorderLayout.CENTER); //Results planInfoEditorPane = new JEditorPane(); planInfoEditorPane.setContentType("text/html"); planInfoEditorPane.setEditable(false); planInfoEditorPane.setCursor(new Cursor(Cursor.TEXT_CURSOR)); planInfoEditorPane.setBackground(Color.WHITE); JPanel resultsPanel = new JPanel(new BorderLayout()); JToolBar resultsToolBar = new JToolBar(); resultsToolBar.setRollover(true); JButton planReportButton = new JButton("View Full Report", new ImageIcon("resources/images/viewreport.png")); planReportButton.setToolTipText("<html>View full plan report.<br> For multiple plans you will need " + "access to the Internet.<br> The components used in the report require such access (no data is " + "sent through the Internet).</html>"); planReportButton.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Opens html with defaut browser String path = "resources/report/Report.html"; File report = new File(path); path = report.getAbsolutePath(); try { BrowserLauncher launcher = new BrowserLauncher(); launcher.openURLinBrowser("file://" + path); } catch (BrowserLaunchingInitializingException ex) { Logger.getLogger(ItSIMPLE.class.getName()).log(Level.SEVERE, null, ex); appendOutputPanelText("ERROR. Problem while trying to open the default browser. \n"); } catch (UnsupportedOperatingSystemException ex) { Logger.getLogger(ItSIMPLE.class.getName()).log(Level.SEVERE, null, ex); appendOutputPanelText("ERROR. Problem while trying to open the default browser. \n"); } } }); resultsToolBar.add(planReportButton); resultsToolBar.addSeparator(); JButton planReportDataButton = new JButton("Save Report Data", new ImageIcon("resources/images/savePDDL.png")); planReportDataButton.setToolTipText("<html>Save report data to file</html>"); planReportDataButton.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Save report data if (solveResult != null) { Element lastOpenFolderElement = itSettings.getChild("generalSettings") .getChild("lastOpenFolder"); JFileChooser fc = new JFileChooser(lastOpenFolderElement.getText()); fc.setDialogTitle("Save Report Data"); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); fc.setFileFilter(new XMLFileFilter()); int returnVal = fc.showSaveDialog(ItSIMPLE.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File selectedFile = fc.getSelectedFile(); String path = selectedFile.getPath(); if (!path.toLowerCase().endsWith(".xml")) { path += ".xml"; } //save file (xml) try { FileWriter file = new FileWriter(path); file.write(XMLUtilities.toString(solveResult)); file.close(); } catch (IOException e1) { e1.printStackTrace(); } //Save as a last open folder String folder = selectedFile.getParent(); //Element lastOpenFolderElement = itSettings.getChild("generalSettings").getChild("lastOpenFolder"); lastOpenFolderElement.setText(folder); XMLUtilities.writeToFile("resources/settings/itSettings.xml", itSettings.getDocument()); //Ask if the user wants to save plans individually too. boolean needToSavePlans = false; int option = JOptionPane.showOptionDialog(instance, "<html><center>Do you also want to save the plans" + "<br>in individual files?</center></html>", "Save plans", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); switch (option) { case JOptionPane.YES_OPTION: { needToSavePlans = true; } break; case JOptionPane.NO_OPTION: { needToSavePlans = false; } break; } if (needToSavePlans) { //Close Open tabs List<?> problems = null; try { XPath ppath = new JDOMXPath("project/domains/domain/problems/problem"); problems = ppath.selectNodes(solveResult); } catch (JaxenException e2) { e2.printStackTrace(); } for (int i = 0; i < problems.size(); i++) { Element problem = (Element) problems.get(i); //create a folder for each problem and put all plans inside as xml files String folderName = problem.getChildText("name"); String folderPath = selectedFile.getAbsolutePath() .replace(selectedFile.getName(), folderName); //System.out.println(folderPath); File planfolder = new File(folderPath); boolean canSavePlan = false; try { if (planfolder.mkdir()) { System.out.println("Directory '" + folderPath + "' created."); canSavePlan = true; } else { System.out.println("Directory '" + folderPath + "' was not created."); } } catch (Exception ep) { ep.printStackTrace(); } if (canSavePlan) { Element plans = problem.getChild("plans"); for (Iterator<Element> it = plans.getChildren("xmlPlan").iterator(); it .hasNext();) { Element eaplan = it.next(); Element theplanner = eaplan.getChild("planner"); //save file (xml) String planFileName = "solution" + theplanner.getChildText("name") + "-" + theplanner.getChildText("version") + "-" + Integer.toString(plans.getChildren().indexOf(eaplan)) + ".xml"; String planPath = folderPath + File.separator + planFileName; /* try { FileWriter planfile = new FileWriter(planPath); planfile.write(XMLUtilities.toString(eaplan)); planfile.close(); System.out.println("File '" + planPath + "' created."); } catch (IOException e1) { e1.printStackTrace(); } * */ if (eaplan.getChild("plan").getChildren().size() > 0) { //TODO: save the plan in PDDL too. It should be done through the XPDDL/PDDL classes String pddlplan = ToXPDDL.XMLtoXPDDLPlan(eaplan); String planFileNamePDDL = "solution" + theplanner.getChildText("name") + "-" + theplanner.getChildText("version") + "-" + Integer.toString(plans.getChildren().indexOf(eaplan)) + ".pddl"; String planPathPDDL = folderPath + File.separator + planFileNamePDDL; //String cfolderPath = selectedFile.getAbsolutePath().replace(selectedFile.getName(), ""); //String planFileNamePDDL = theplanner.getChildText("name")+"-"+theplanner.getChildText("version") + "-" + folderName+"-solution.pddl"; //String planPathPDDL = cfolderPath + File.separator + planFileNamePDDL; //if (!theplanner.getChildText("name").contains("MIPS")){ try { FileWriter planfile = new FileWriter(planPathPDDL); planfile.write(pddlplan); planfile.close(); System.out.println("File '" + planPathPDDL + "' created."); } catch (IOException e1) { e1.printStackTrace(); } } //} } } } } } } else { appendOutputPanelText(">> No report data available to save! \n"); } } }); resultsToolBar.add(planReportDataButton); JButton openPlanReportDataButton = new JButton("Open Report Data", new ImageIcon("resources/images/openreport.png")); openPlanReportDataButton.setToolTipText("<html>Open report data to file</html>"); openPlanReportDataButton.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(ActionEvent e) { planSimStatusBar.setText("Status: Opening File..."); appendOutputPanelText(">> Opening File... \n"); //Open report data Element lastOpenFolderElement = itSettings.getChild("generalSettings") .getChild("lastOpenFolder"); JFileChooser fc = new JFileChooser(lastOpenFolderElement.getText()); fc.setDialogTitle("Open Report Data"); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); fc.setFileFilter(new XMLFileFilter()); int returnVal = fc.showOpenDialog(ItSIMPLE.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); // Get itSIMPLE itSettings from itSettings.xml org.jdom.Document resultsDoc = null; try { resultsDoc = XMLUtilities.readFromFile(file.getPath()); solveResult = resultsDoc.getRootElement(); //XMLUtilities.printXML(solveResult); if (solveResult.getName().equals("projects")) { String report = PlanAnalyzer.generatePlannersComparisonReport(solveResult); String comparisonReport = PlanAnalyzer .generateFullPlannersComparisonReport(solveResult); //Save Comparison Report file saveFile("resources/report/Report.html", comparisonReport); setPlanInfoPanelText(report); setPlanEvaluationInfoPanelText(""); appendOutputPanelText(">> Report data read! \n"); //My experiments PlanAnalyzer.myAnalysis(itPlanners.getChild("planners"), solveResult); } } catch (Exception e1) { e1.printStackTrace(); } //Save as a last open folder String folder = fc.getSelectedFile().getParent(); lastOpenFolderElement.setText(folder); XMLUtilities.writeToFile("resources/settings/itSettings.xml", itSettings.getDocument()); } else { planSimStatusBar.setText("Status:"); appendOutputPanelText(">> Canceled \n"); } } }); resultsToolBar.add(openPlanReportDataButton); JButton compareProjectReportDataButton = new JButton("Compare Project Data", new ImageIcon("resources/images/compare.png")); compareProjectReportDataButton.setToolTipText( "<html>Compare different project report data <br> This is commonly use to compare diferent domain models with different adjustments.<br>" + "One project data must be chosen as a reference; others will be compared to this referencial one.</html>"); compareProjectReportDataButton.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(ActionEvent e) { final ProjectComparisonDialog dialog = new ProjectComparisonDialog(); dialog.setVisible(true); final List<String> files = dialog.getFiles(); if (files.size() > 1) { new Thread() { public void run() { appendOutputPanelText(">> Project comparison report requested. Processing... \n"); planSimStatusBar.setText("Status: Reading files ..."); appendOutputPanelText(">> Reading files ... \n"); //base project file String baseFileName = files.get(0); appendOutputPanelText(">> Reading file '" + baseFileName + "' \n"); org.jdom.Document baseProjectDoc = null; try { baseProjectDoc = XMLUtilities.readFromFile(baseFileName); } catch (Exception ec) { ec.printStackTrace(); } Element baseProject = null; if (baseProjectDoc != null) { baseProject = baseProjectDoc.getRootElement().getChild("project"); } //The comparible projects List<Element> comparableProjects = new ArrayList<Element>(); for (int i = 1; i < files.size(); i++) { String eafile = files.get(i); appendOutputPanelText(">> Reading file '" + eafile + "' \n"); org.jdom.Document eaProjectDoc = null; try { eaProjectDoc = XMLUtilities.readFromFile(eafile); } catch (Exception ec) { ec.printStackTrace(); } if (eaProjectDoc != null) { comparableProjects.add(eaProjectDoc.getRootElement().getChild("project")); } } appendOutputPanelText(">> Files read. Building report... \n"); String comparisonReport = PlanAnalyzer.generateProjectComparisonReport(baseProject, comparableProjects); saveFile("resources/report/Report.html", comparisonReport); appendOutputPanelText( ">> Project comparison report generated. Press 'View Full Report'\n"); appendOutputPanelText(" \n"); } }.start(); } } }); resultsToolBar.add(compareProjectReportDataButton); resultsPanel.add(resultsToolBar, BorderLayout.NORTH); resultsPanel.add(new JScrollPane(planInfoEditorPane), BorderLayout.CENTER); JTabbedPane planAnalysisTabbedPane = new JTabbedPane(); planAnalysisTabbedPane.addTab("Results", resultsPanel); planAnalysisTabbedPane.addTab("Variable Tracking", mainChartsPanel); planAnalysisTabbedPane.addTab("Movie Maker", getMovieMakerPanel()); planAnalysisTabbedPane.addTab("Plan Evaluation", getPlanEvaluationPanel()); planAnalysisTabbedPane.addTab("Plan Database", getPlanDatabasePanel()); planAnalysisTabbedPane.addTab("Rationale Database", getRationaleDatabasePanel()); JPanel planAnalysisPanel = new JPanel(new BorderLayout()); //planAnalysisPanel.add(chartsToolBar, BorderLayout.NORTH); planAnalysisPanel.add(planAnalysisTabbedPane, BorderLayout.CENTER); planAnalysisFramePanel.setContent(planAnalysisPanel, false); } return planAnalysisFramePanel; }
From source file:net.team2xh.crt.gui.util.GUIToolkit.java
/** * Displays a dialog with "OK" button.//from ww w . j a va 2s .c om * * @param parent Parent window * @param message Message (can contain "\n" characters) * @param title Dialog title * @param type Icon type (use JOptionPane static values) */ public static void showOkDialog(java.awt.Window parent, String message, String title, int type) { SwingUtilities.invokeLater(() -> { Object[] options = { "OK" }; JLabel msg = new JLabel(convertToMultiline(message)); Dimension sz = msg.getPreferredSize(); msg.setPreferredSize(new Dimension(sz.width + 20, sz.height)); JOptionPane.showOptionDialog(parent, msg, title, JOptionPane.DEFAULT_OPTION, type, null, options, options[0]); }); }
From source file:nl.detoren.ijsco.ui.Mainscreen.java
public void ShowWarning(String warning) { /* JPanel p = new JPanel(new BorderLayout()); DefaultTableModel tableModel = new DefaultTableModel(); tableModel.addColumn("Selection", new Object[] { "A", "B", "C" }); /* www . j a v a2s . c om*/ JTable table = new JTable(tableModel); ListSelectionModel selectionModel = table.getSelectionModel(); p.add(table, BorderLayout.CENTER); */ Object[] options = { "OK" }; int option = JOptionPane.showOptionDialog(null, warning, "Warning", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); //int option = JOptionPane.showConfirmDialog(null, warning, "Warning", , JOptionPane.ERROR_MESSAGE); if (option == 0) { return; } }