Java Code Examples for javax.swing.JOptionPane.OK_OPTION

The following are Jave code examples for showing how to use OK_OPTION of the javax.swing.JOptionPane class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: PTEAssistant   File: MainFrame.java   View Source Code Vote up 6 votes
private void btnDeleteUserSetting_Click(ActionEvent e) {
    if (tableUser.getSelectedRowCount() <= 0) {  
        JOptionPane.showMessageDialog(null, "请选择帐号");  
        return;  
    }
    int ret = JOptionPane.showConfirmDialog(this,
            "你确定要删除所选择的帐号?", null,
            JOptionPane.YES_NO_OPTION);
    if (ret == JOptionPane.OK_OPTION)
        userTableModel.removeSeletedUserSetting();
}
 
Example 2
Project: iTrace-Archive   File: JSONGazeExportSolver.java   View Source Code Vote up 6 votes
@Override
public void displayExportFile() {
	JTextField displayVal = new JTextField(filename);
	displayVal.setEditable(false);
	
	JPanel displayPanel = new JPanel();
	displayPanel.setLayout(new BoxLayout(displayPanel, BoxLayout.Y_AXIS)); //vertically align
	displayPanel.add(new JLabel("Export Filename"));
	displayPanel.add(displayVal);
	displayPanel.setPreferredSize(new Dimension(400,40)); //resize appropriately
	
	final int displayDialog = JOptionPane.showConfirmDialog(null, displayPanel, 
			friendlyName() + " Display", JOptionPane.OK_CANCEL_OPTION,
			JOptionPane.PLAIN_MESSAGE);
	if (displayDialog == JOptionPane.OK_OPTION) {
		//do nothing
	}
}
 
Example 3
Project: parabuild-ci   File: LegendPropertyEditPanel.java   View Source Code Vote up 6 votes
/**
 * Allows the user the opportunity to change the outline stroke.
 */
private void attemptModifyOutlineStroke() {

    StrokeChooserPanel panel = new StrokeChooserPanel(
        this.outlineStroke, this.availableStrokeSamples
    );
    int result = JOptionPane.showConfirmDialog(
        this, panel, localizationResources.getString("Pen_Stroke_Selection"),
        JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE
    );

    if (result == JOptionPane.OK_OPTION) {
        this.outlineStroke.setStroke(panel.getSelectedStroke());
    }

}
 
Example 4
Project: jiracli   File: CredentialsPanel.java   View Source Code Vote up 6 votes
public static Credentials getCredentials(Window parent, String username, String url) {
    CredentialsPanel credentialsPanel = new CredentialsPanel(username, url);
    int result = JOptionPane.showConfirmDialog(parent, credentialsPanel, Constants.getTitle(),
            JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
    if (result == JOptionPane.OK_OPTION) {
        if (credentialsPanel.isAnonymous()) {
            return Credentials.getAnonymous();
        } else {
            String user = credentialsPanel.getUsername();
            char[] password = credentialsPanel.getPassword();
            return Credentials.create(user, password);
        }
    } else {
        return null;
    }
}
 
Example 5
Project: xdman   File: XDMMainWindow.java   View Source Code Vote up 6 votes
int getDupAction(String url) {
	JTextField txt = new JTextField(url, 30);
	String lbl = StringResource.getString("DUP_TXT");
	JComboBox choice = new JComboBox(new String[] { StringResource.getString("DUP_OP1"),
			StringResource.getString("DUP_OP2"), StringResource.getString("DUP_OP3") });
	JCheckBox chk = new JCheckBox(StringResource.getString("DUP_CHK"));
	int ret = JOptionPane.showOptionDialog(null, new Object[] { txt, lbl, choice, chk },
			StringResource.getString("DUP_TITLE"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null,
			null, null);
	if (ret == JOptionPane.OK_OPTION) {
		int index = choice.getSelectedIndex();
		if (chk.isSelected()) {
			config.duplicateLinkAction = index;
		}
		return index;
	}
	return -1;
}
 
Example 6
Project: parabuild-ci   File: PlotPropertyEditPanel.java   View Source Code Vote up 5 votes
/**
 * Allow the user to change the outline stroke.
 */
private void attemptOutlineStrokeSelection() {
    StrokeChooserPanel panel = new StrokeChooserPanel(null, this.availableStrokeSamples);
    int result = JOptionPane.showConfirmDialog(this, panel,
        localizationResources.getString("Stroke_Selection"),
        JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

    if (result == JOptionPane.OK_OPTION) {
        this.outlineStrokeSample.setStroke(panel.getSelectedStroke());
    }
}
 
Example 7
Project: scorekeeperfrontend   File: BracketPane.java   View Source Code Vote up 5 votes
@Override
public boolean importData(TransferHandler.TransferSupport support)
{
	try
	{
		if (support.isDrop())
		{
			BracketEntry transfer = (BracketEntry)support.getTransferable().getTransferData(BracketEntry.Transfer.myFlavor);
			EntrantLabel target = (EntrantLabel)support.getComponent();
			BracketEntry old = target.getEntry();					
			boolean swap = ((transfer.source != null) && (transfer.source.getDepth() == target.entryId.getDepth()));

			// swap operation in the same level of the challenge
			if (swap)
			{
				if (!target.isEmpty() && (JOptionPane.showConfirmDialog(BracketPane.this,
										String.format("This will swap %s and %s.  Is that what you would like to do?", old.entrant.getName(), transfer.entrant.getName()),
											"Entrant Swap", JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION))
					return false;
				model.setEntrant(transfer.source, old.entrant, old.dialin);
				rounds.get(transfer.source.round).updateEntrants();
			}

			// copy from tree or previous round
			if (!swap)
			{
				if (!target.isEmpty() && (JOptionPane.showConfirmDialog(null, 
										String.format("This will overwrite %s with %s.  Is that what you would like to do?", old.entrant.getName(), transfer.entrant.getName()), 
											"Overwrite Warning", JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION))
					return false;
			}
				
			target.setEntry(transfer);
			Messenger.sendEvent(MT.ENTRANT_CHANGED, old);
			return true;
		}
	}
	catch (Exception ioe) { log.warning("\bError during drop:" + ioe); }
	return false;
}
 
Example 8
Project: parabuild-ci   File: DefaultNumberAxisEditor.java   View Source Code Vote up 5 votes
/**
 * Handle a grid stroke selection.
 */
private void attemptGridStrokeSelection() {
    StrokeChooserPanel panel = new StrokeChooserPanel(
        null, this.availableStrokeSamples
    );
    int result = JOptionPane.showConfirmDialog(
        this, panel, localizationResources.getString("Stroke_Selection"),
        JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE
    );

    if (result == JOptionPane.OK_OPTION) {
        this.gridStrokeSample.setStroke(panel.getSelectedStroke());
    }
}
 
Example 9
Project: geomapapp   File: AgeDepthModel.java   View Source Code Vote up 5 votes
public void exportASCII() {
	JFileChooser jfc = new JFileChooser(System.getProperty("user.dir"));
	File f=new File(graphDialog.getTitle()+"_age_depth.txt");
	jfc.setSelectedFile(f);
	do {
		int c = jfc.showSaveDialog(null);
		if (c==JFileChooser.CANCEL_OPTION||c==JFileChooser.ERROR_OPTION) return;
		f = jfc.getSelectedFile();
		if (f.exists()) {
			c=JOptionPane.showConfirmDialog(null, "File Already Exists\nConfirm Overwrite");
			if (c==JOptionPane.OK_OPTION) break;
			if (c==JOptionPane.CANCEL_OPTION) return;
		}
	} while (f.exists());

	try {
		BufferedWriter out = new BufferedWriter(new FileWriter(f));
		out.write("ID\tdepth\tage\tsource\n");
		float[] firstTie = (float[])ties.get(0);
		String sourceString = (String)holeSources.get(0);
		out.write(graphDialog.getTitle() + "\t" + firstTie[0] + "\t" + firstTie[1] + "\t" + sourceString + "\n");
		for( int i=0 ; i<ties.size() ; i++) {
			float[] tie = (float[])ties.get(i);
			out.write("\t" + tie[0] + "\t" + tie[1] + "\t\n");
		}
		out.close();
	} catch (IOException ex){

	}
}
 
Example 10
Project: QN-ACTR-Release   File: ModelLoader.java   View Source Code Vote up 5 votes
/**
 * Saves specified model into specified file or shows save as window if file is null
 * @param modelData data file where information should be stored. Note that <b>its type
 * must be compatible with defaultFilter chosen in the constructor</b>, otherwise a
 * ClassCastException will be thrown
 * @param parent parent window that will own the save as dialog
 * @param file location where pecified model must be saved or null if save as must be shown
 * @return SUCCESS on success, CANCELLED if loading is cancelled,
 * FAILURE if an error occurs
 * @throws ClassCastException if modelData is not of instance of the correct class
 * @see #getFailureMotivation getFailureMotivation()
 */
public int saveModel(Object modelData, Component parent, File file) {
	if (file == null) {
		// Shows save as window
		int status;
		status = this.showSaveDialog(parent);
		if (status == JFileChooser.CANCEL_OPTION) {
			return CANCELLED;
		} else if (status == JFileChooser.ERROR_OPTION) {
			failureMotivation = "Error selecting output file";
			return FAILURE;
		}
		file = dialog.getSelectedFile();
	} else
	// Check extension to avoid saving over a converted file
	if (!file.getName().endsWith(defaultFilter.getFirstExtension())) {
		int resultValue = JOptionPane.showConfirmDialog(parent, "<html>File <font color=#0000ff>" + file.getName() + "</font> does not have \""
				+ defaultFilter.getFirstExtension() + "\" extension.<br>Do you want to replace it anyway?</html>", "JMT - Warning",
				JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
		if (resultValue != JOptionPane.OK_OPTION) {
			return CANCELLED;
		}
	}

	// Now checks to save correct type of model
	try {
		if (defaultFilter == JMODEL || defaultFilter == JSIM) {
			XMLArchiver.saveModel(file, (CommonModel) modelData);
		} else if (defaultFilter == JMVA) {
			xmlutils.saveXML(((ExactModel) modelData).createDocument(), file);
		} else if (defaultFilter == JABA) {
			xmlutils.saveXML(((JabaModel) modelData).createDocument(), file);
		}
	} catch (Exception e) {
		failureMotivation = e.getClass().getName() + ": " + e.getMessage();
		return FAILURE;
	}
	return SUCCESS;
}
 
Example 11
Project: parabuild-ci   File: ChartPanel.java   View Source Code Vote up 5 votes
/**
 * Displays a dialog that allows the user to edit the properties for the
 * current chart.
 */
private void attemptEditChartProperties() {

    ChartPropertyEditPanel panel = new ChartPropertyEditPanel(this.chart);
    int result = 
        JOptionPane.showConfirmDialog(this, panel, 
                                      localizationResources.getString("Chart_Properties"),
                                      JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
    if (result == JOptionPane.OK_OPTION) {
        panel.updateChartProperties(this.chart);
    }

}
 
Example 12
Project: rapidminer   File: AbstractChartPanel.java   View Source Code Vote up 5 votes
/**
 * Displays a dialog that allows the user to edit the properties for the current chart.
 * 
 * @since 1.0.3
 */

@Override
public void doEditChartProperties() {

	ChartEditor editor = ChartEditorManager.getChartEditor(this.chart);
	int result = JOptionPane.showConfirmDialog(this, editor, localizationResources.getString("Chart_Properties"),
			JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
	if (result == JOptionPane.OK_OPTION) {
		editor.updateChart(this.chart);
	}

}
 
Example 13
Project: geomapapp   File: UnknownDataSet.java   View Source Code Vote up 5 votes
public void exportASCII(String saveOption){
	//run standard checks before exporting
	if (!exportChecks(saveOption)) return;
	
	JFileChooser jfc = new JFileChooser(System.getProperty("user.home"));
	File f=new File(desc.name.replace(":", "")+".txt");
	jfc.setSelectedFile(f);
	do {
		int c = jfc.showSaveDialog(null);
		if (c==JFileChooser.CANCEL_OPTION||c==JFileChooser.ERROR_OPTION) return;
		f = jfc.getSelectedFile();
		if (f.exists()) {
			c=JOptionPane.showConfirmDialog(null, "File Already Exists\nConfirm Overwrite");
			if (c==JOptionPane.OK_OPTION) break;
			if (c==JOptionPane.CANCEL_OPTION) return;
		}
	} while (f.exists());

	try {
		BufferedWriter out = new BufferedWriter(new FileWriter(f));
		//don't include Plot column
		for (int i=1;i<dataT.getColumnCount();i++)
			out.write(dataT.getColumnName(i)+"\t");
		out.write("\n");
		
		int[] ind;
		if (saveOption.equals("selection")) {
			ind = dataT.getSelectedRows();
		} else if (saveOption.equals("plottable")) {
			ind = getPlottableRows();
		} else {
			ind = new int[dataT.getRowCount()];
			for (int i=0; i<dataT.getRowCount(); i++) ind[i] = i;
		}
			
		for (int i=0;i<ind.length;i++) {
			for (int j=1; j<dataT.getColumnCount();j++) {
				Object o = dataT.getValueAt(ind[i], j);
				if (o instanceof String && ((String)o).equals("NaN")) o = "";
				out.write(o+"\t");
			}
			out.write("\n");
		}
		out.close();
	} catch (IOException ex){

	}
}
 
Example 14
Project: Proyecto-DASI   File: ControladorGestionEscenariosRosace.java   View Source Code Vote up 5 votes
public  void peticionGuardarEscenario(EscenarioSimulacionRobtsVictms escenarioComp) {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    // si no hay un escenario actual definido indicamos al usuario que no hay escenario definido
    // si en el escenario a guardar no hay robots ni victimas se lo decimos
        escenarioEdicionComp = escenarioComp;
        if (escenarioEdicionComp.getNumRobots()<=0)visorEditorEscen.visualizarConsejo(tituloAvisoEscenSinRobotsDefinidos, mensajeEscenarioSinRobots, recomendacionDefinirRobots);
        else{
            int respuesta =visorEditorEscen.confirmarPeticionGuardarEscenario("Se va a guardar el escenario : ");
            if (respuesta==JOptionPane.OK_OPTION){
                
                 ArrayList<String> robotNombres = escenarioComp.getListIdentsRobots();
             for (String ideRobot:robotNombres){
//                 String ideRobot = (String)robtIter.next();
              RobotStatus1 infoRobot = (RobotStatus1) escenarioComp.getRobotInfo(ideRobot);
              List<RobotCapability> capacidades=infoRobot.getRobotCapabilities();
                 System.out.println("Desde peticion Guardar Lista de capacidades a guardar del robot  : " + ideRobot+"Capacidades : "+ capacidades.toString() );
             }
             System.out.println("Desde peticion Guardar Numero de Robots  : " + escenarioEdicionComp.getNumRobots()+" Numero de victimas : "+ escenarioEdicionComp.getNumVictimas());
//             if (itfPersistenciaSimul==null)   
//                persistenciaLocal.guardarInfoEscenarioSimulacion(directorioPersistencia, escenarioEdicionComp);
//             else 
                 try {
                     itfPersistenciaSimul.guardarInfoEscenarioSimulacion(escenarioEdicionComp);
                 } catch (Exception ex) {
                     Exceptions.printStackTrace(ex);
                 }
                if ( peticionObtenerEscenarioValido&&!escenarioValidoObtenido){
                    // se envia el escenario al agente controlador que puede estar esperandolo
                    notifEvts.sendInfoEscenarioSeleccionado(escenarioEdicionComp);
                }
            }
            if (!visorMovientoIniciado){
            visorControlSim.visualizarIdentsEquipoRobot(escenarioComp.getListIdentsRobots());
            visorControlSim.setIdentEscenarioActual(escenarioComp.getIdentEscenario());
            }
        } 
    }
 
Example 15
Project: iTrace-Archive   File: SessionInfoHandler.java   View Source Code Vote up 5 votes
protected void developerUI() {
	//Textfields needed for data entry
	JTextField devUserText = new JTextField();
	JTextField devNameText = new JTextField();
   	
	//Add text fields to main JPanel
	JPanel devPanel = new JPanel();
	devPanel.setLayout(new BoxLayout(devPanel, BoxLayout.Y_AXIS)); //vertically align
	devPanel.add(new JLabel("Developer Username (Alphanumeric Characters Only):"));
	devPanel.add(devUserText);
	devPanel.add(new JLabel("Developer Name (Optional, Alpha/Space Characters Only):"));
	devPanel.add(devNameText);
	
	final int selection = JOptionPane.showConfirmDialog(null, devPanel, 
			"Enter the Developer Info.",
			JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
	if (selection == JOptionPane.OK_OPTION) {
		Pattern p = Pattern.compile("[^a-zA-Z0-9]");
		Pattern p2 = Pattern.compile("[^A-Za-z ]");
		if (!p.matcher(devUserText.getText()).find() &&
				!devUserText.getText().isEmpty() &&
				!p2.matcher(devNameText.getText()).find()) {
			devUsername = devUserText.getText();
			devName = devNameText.getText();
		} else {
			//error
			JOptionPane.showMessageDialog(null, "You "
					+ "have Non-alphanumeric Characters "
					+ "in your Developer Username or you have "
					+ "Non-alphabetic/Space Characters "
					+ "in your Developer Name or you have not "
					+ "provided a Developer Username. Please re-enter "
					+ "your Developer Information.", "Error", 
					JOptionPane.ERROR_MESSAGE);
			//re-enter devUsername
			developerUI();
		}
		hasDevInfo = true;
	}
}
 
Example 16
Project: jmt   File: ModelLoader.java   View Source Code Vote up 5 votes
/**
 * Overrides default method to provide a warning if saving over an existing file
 */
@Override
public void approveSelection() {
	// Gets the chosen file name
	String name = getSelectedFile().getName();
	String parent = getSelectedFile().getParent();
	if (getDialogType() == OPEN_DIALOG) {
		super.approveSelection();
	}
	if (getDialogType() == SAVE_DIALOG) {
		boolean hasValidExtension = false;
		String[] extensions = defaultSaveFilter.getExtensions();
		for (String e : extensions) {
			if (name.toLowerCase().endsWith(e)) {
				hasValidExtension = true;
				break;
			}
		}
		if (!hasValidExtension) {
			name += extensions[0];
			setSelectedFile(new File(parent, name));
		}
		if (getSelectedFile().exists()) {
			int resultValue = JOptionPane.showConfirmDialog(this, "<html>File <font color=#0000ff>" + name
					+ "</font> already exists in this folder.<br>Do you want to replace it?</html>", "JMT - Warning",
					JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
			if (resultValue == JOptionPane.OK_OPTION) {
				getSelectedFile().delete();
				super.approveSelection();
			}
		} else {
			super.approveSelection();
		}
	}
}
 
Example 17
Project: OpenJSharp   File: DialogCallbackHandler.java   View Source Code Vote up 4 votes
void setCallback(ConfirmationCallback callback)
    throws UnsupportedCallbackException
{
    this.callback = callback;

    int confirmationOptionType = callback.getOptionType();
    switch (confirmationOptionType) {
    case ConfirmationCallback.YES_NO_OPTION:
        optionType = JOptionPane.YES_NO_OPTION;
        translations = new int[] {
            JOptionPane.YES_OPTION, ConfirmationCallback.YES,
            JOptionPane.NO_OPTION, ConfirmationCallback.NO,
            JOptionPane.CLOSED_OPTION, ConfirmationCallback.NO
        };
        break;
    case ConfirmationCallback.YES_NO_CANCEL_OPTION:
        optionType = JOptionPane.YES_NO_CANCEL_OPTION;
        translations = new int[] {
            JOptionPane.YES_OPTION, ConfirmationCallback.YES,
            JOptionPane.NO_OPTION, ConfirmationCallback.NO,
            JOptionPane.CANCEL_OPTION, ConfirmationCallback.CANCEL,
            JOptionPane.CLOSED_OPTION, ConfirmationCallback.CANCEL
        };
        break;
    case ConfirmationCallback.OK_CANCEL_OPTION:
        optionType = JOptionPane.OK_CANCEL_OPTION;
        translations = new int[] {
            JOptionPane.OK_OPTION, ConfirmationCallback.OK,
            JOptionPane.CANCEL_OPTION, ConfirmationCallback.CANCEL,
            JOptionPane.CLOSED_OPTION, ConfirmationCallback.CANCEL
        };
        break;
    case ConfirmationCallback.UNSPECIFIED_OPTION:
        options = callback.getOptions();
        /*
         * There's no way to know if the default option means
         * to cancel the login, but there isn't a better way
         * to guess this.
         */
        translations = new int[] {
            JOptionPane.CLOSED_OPTION, callback.getDefaultOption()
        };
        break;
    default:
        throw new UnsupportedCallbackException(
            callback,
            "Unrecognized option type: " + confirmationOptionType);
    }

    int confirmationMessageType = callback.getMessageType();
    switch (confirmationMessageType) {
    case ConfirmationCallback.WARNING:
        messageType = JOptionPane.WARNING_MESSAGE;
        break;
    case ConfirmationCallback.ERROR:
        messageType = JOptionPane.ERROR_MESSAGE;
        break;
    case ConfirmationCallback.INFORMATION:
        messageType = JOptionPane.INFORMATION_MESSAGE;
        break;
    default:
        throw new UnsupportedCallbackException(
            callback,
            "Unrecognized message type: " + confirmationMessageType);
    }
}
 
Example 18
Project: sbc-qsystem   File: FAdmin.java   View Source Code Vote up 4 votes
@Action
public void addUser() {
    // Запросим название юзера и если оно уникально, то примем
    String userName = "";
    QOffice office = null;
    boolean flag = true;

    List<QOffice> offices = Spring.getInstance().getHt().findByCriteria(
        DetachedCriteria.forClass(QOffice.class)
            .add(Property.forName("deleted").isNull())
            .setFetchMode("services", FetchMode.EAGER)
            .setResultTransformer((Criteria.DISTINCT_ROOT_ENTITY))
    );

    while (flag) {
        JTextField userNameTextField = new JTextField();
        JComboBox officeDropdown = new JComboBox();

        for (QOffice dropdownOffice : offices) {
            officeDropdown.addItem(dropdownOffice);
        }

        Object[] message = {
            "Username:", userNameTextField,
            "Office:", officeDropdown
        };
        int option = JOptionPane
            .showConfirmDialog(this, message, getLocaleMessage("admin.add_user_dialog.title"),
                JOptionPane.OK_CANCEL_OPTION);

        if (option == JOptionPane.OK_OPTION) {
            userName = userNameTextField.getText();
            office = (QOffice) officeDropdown.getSelectedItem();

            if ("".equals(userName)) {
                flag = true;
            } else if (QUserList.getInstance().hasByName(userName)) {
                flag = true;
            } else if (userName.indexOf('\"') != -1) {
                flag = true;
            } else if (userName.length() > 150) {
                flag = true;
            } else {
                flag = false;
            }
        } else if (option == JOptionPane.CANCEL_OPTION) {
            return;
        }
    }
    QLog.l().logger().debug("Adding a user \"" + userName + "\"");
    final QUser user = new QUser();
    user.setPlanServices(new LinkedList<>());
    user.setName(userName);
    user.setOffice(office);
    user.setPassword("");
    user.setPoint("");
    user.setAdressRS(32);
    user.addPlanServiceByOffice();
    QUserList.getInstance().addElement(user);
    listUsers.setSelectedValue(user, true);
}
 
Example 19
Project: geomapapp   File: DSDPDemo.java   View Source Code Vote up 4 votes
public void exportSelectExcel(){
	if (table.getSelectedRowCount() == 0) {
		JOptionPane.showMessageDialog(null, "No data selected for export", "No Selection", JOptionPane.ERROR_MESSAGE);
		return;
	}

	JFileChooser jfc = new JFileChooser(System.getProperty("user.dir"));
	ExcelFileFilter eff = new ExcelFileFilter();
	jfc.setFileFilter(eff);
	File f=new File("dsdpTableSelection.xls");
	jfc.setSelectedFile(f);
	do {
		int c = jfc.showSaveDialog(null);
		if (c==JFileChooser.CANCEL_OPTION||c==JFileChooser.ERROR_OPTION) return;
		f = jfc.getSelectedFile();
		if (f.exists()) {
			c=JOptionPane.showConfirmDialog(null, "File Already Exists\nConfirm Overwrite");
			if (c==JOptionPane.OK_OPTION) break;
			if (c==JOptionPane.CANCEL_OPTION) return;
		}
	} while (f.exists());

	try {
		WritableWorkbook wb = Workbook.createWorkbook(f);
		WritableSheet sheet = wb.createSheet("First Sheet", 0);
		for (int i=0;i<table.getColumnCount();i++)
			sheet.addCell( new Label(i,0,table.getColumnName(i)) );
		int sel[] = table.getSelectedRows();
		for (int i=0;i<sel.length;i++) {
			for (int j=0; j<table.getColumnCount();j++) {
				Object o = table.getValueAt(sel[i], j);
				if (o == null || ( o instanceof String && ((String)o).equals("NaN") ) ) o = "";
				sheet.addCell( new Label(j,i+1,o.toString()) );
			}
		}
		wb.write();
		wb.close();
	} catch (Exception ex){
		ex.printStackTrace();
	}
}
 
Example 20
Project: geomapapp   File: UnknownDataSet.java   View Source Code Vote up 4 votes
public void exportExcel(String saveOption){
	//run standard checks before exporting
	if (!exportChecks(saveOption)) return;
	
	JFileChooser jfc = new JFileChooser(System.getProperty("user.home"));
	ExcelFileFilter eff = new ExcelFileFilter();
	jfc.setFileFilter(eff);
	File f=new File(desc.name.replace(":", "")+".xls");
	jfc.setSelectedFile(f);
	do {
		int c = jfc.showSaveDialog(null);
		if (c==JFileChooser.CANCEL_OPTION||c==JFileChooser.ERROR_OPTION) return;
		f = jfc.getSelectedFile();
		if (f.exists()) {
			c=JOptionPane.showConfirmDialog(null, "File Already Exists\nConfirm Overwrite");
			if (c==JOptionPane.OK_OPTION) break;
			if (c==JOptionPane.CANCEL_OPTION) return;
		}
	} while (f.exists());

	try { 
		WritableWorkbook wb = Workbook.createWorkbook(f);
		WritableSheet sheet = wb.createSheet("First Sheet", 0);
		//don't include Plot column
		for (int i=1;i<dataT.getColumnCount();i++)
			sheet.addCell( new Label(i-1,0,dataT.getColumnName(i)) );
		
		int[] ind;
		if (saveOption.equals("selection")) {
			ind = dataT.getSelectedRows();
		} else if (saveOption.equals("plottable")) {
			ind = getPlottableRows();
		} else {
			ind = new int[dataT.getRowCount()];
			for (int i=0; i<dataT.getRowCount(); i++) ind[i] = i;
		}
			
		for (int i=0;i<ind.length;i++) {
			for (int j=1; j<dataT.getColumnCount();j++) {
				Object o = dataT.getValueAt(ind[i], j);
				if (o instanceof String && ((String)o).equals("NaN")) o = "";
				sheet.addCell( new Label(j-1,i+1,o.toString()) );
			}
		}
		wb.write();
		wb.close();
	} catch (Exception ex){
		ex.printStackTrace();
	}
}