List of usage examples for javax.swing JOptionPane ERROR_MESSAGE
int ERROR_MESSAGE
To view the source code for javax.swing JOptionPane ERROR_MESSAGE.
Click Source Link
From source file:gda.gui.beans.ScannableMotionUnitsBean.java
@Override protected void txtValueActionPerformed() { try {/*from www. j av a 2 s. c om*/ theScannable.moveTo(NumberUtils.createDouble(getTxtNoCommas())); } catch (Exception e) { logger.error("Exception while trying to move " + scannableName + ": " + e.getMessage()); JOptionPane.showMessageDialog(getTopLevelAncestor(), scannableName + ": " + e.getMessage(), "Error Message", JOptionPane.ERROR_MESSAGE); } }
From source file:utybo.easypastebin.windows.MainWindow.java
/** * Creates the window//from w ww.ja va 2s . c o m */ @SuppressWarnings({ "rawtypes", "unchecked" }) public MainWindow() { EasyPastebin.LOGGER.log("Initializing the window", SinkJLevel.INFO); setTitle("EasyPastebin"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 664, 431); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP); contentPane.add(tabbedPane, BorderLayout.CENTER); JPanel main = new JPanel(); tabbedPane.addTab("EasyPastebin", null, main, null); main.setLayout(null); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(62, 39, 312, 132); main.add(scrollPane); pasteContent = new JTextArea(); pasteContent.setFont(new Font("Monospaced", Font.PLAIN, 11)); pasteContent.setWrapStyleWord(true); pasteContent.setLineWrap(true); pasteContent.setToolTipText("Put your paste here!"); scrollPane.setViewportView(pasteContent); JLabel titleLabel = new JLabel("Title :"); titleLabel.setFont(new Font("Tahoma", Font.PLAIN, 12)); titleLabel.setBounds(10, 11, 42, 21); main.add(titleLabel); pasteTitle = new JTextField(); pasteTitle.setBounds(62, 12, 312, 20); main.add(pasteTitle); pasteTitle.setColumns(10); JLabel lblPaste = new JLabel("Paste :"); lblPaste.setForeground(Color.RED); lblPaste.setFont(new Font("Tahoma", Font.PLAIN, 12)); lblPaste.setBounds(10, 85, 53, 21); main.add(lblPaste); pasteExpireDate = new JComboBox(); pasteExpireDate.setFont(new Font("Tahoma", Font.PLAIN, 12)); pasteExpireDate.setModel(new DefaultComboBoxModel(EnumExpireDate.values())); pasteExpireDate.setBounds(468, 12, 155, 21); main.add(pasteExpireDate); JLabel lblExpireDate = new JLabel("Expire Date :"); lblExpireDate.setFont(new Font("Tahoma", Font.PLAIN, 12)); lblExpireDate.setBounds(384, 14, 81, 14); main.add(lblExpireDate); JLabel lblfieldsInRed = new JLabel("(Fields in red are required)"); lblfieldsInRed.setBounds(72, 182, 302, 14); main.add(lblfieldsInRed); btnSubmit = new JButton("Submit!"); btnSubmit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { EasyPastebin.LOGGER.log("Starting Submit script", SinkJLevel.INFO); btnSubmit.setEnabled(false); btnSubmit.setText("Please wait..."); boolean success = true; String paste = pasteContent.getText(); String title = pasteTitle.getText(); EnumExpireDate expireDate = (EnumExpireDate) pasteExpireDate.getSelectedItem(); if (paste.equals("") || paste.equals(" ") || paste.equals(null)) { pastebinUrl.setText("ERROR"); JOptionPane.showMessageDialog(null, "You cannot send empty pastes!", "Error while processing paste", JOptionPane.ERROR_MESSAGE); } else { try { EasyPastebin.LOGGER.log("Setting options", SinkJLevel.INFO); Map map = new HashMap<String, String>(); map.put("api_dev_key", HttpHelper.API_KEY); map.put("api_option", "paste"); map.put("api_paste_code", paste); if (!(expireDate.equals(null) || expireDate.equals(EnumExpireDate.NEVER))) map.put("api_paste_expire_date", expireDate.getRawName()); if (!(title.equals("") || title.equals(" ") || title.equals(null))) map.put("api_paste_name", title); EasyPastebin.LOGGER.log("Sending paste", SinkJLevel.INFO); String actionResult = HttpHelper.sendPost("http://pastebin.com/api/api_post.php", map) .asString(); EasyPastebin.LOGGER.log("Paste sent, checking output", SinkJLevel.INFO); // Exception handlers if (actionResult.equals("Bad API request, invalid api_option")) { success = false; EasyPastebin.LOGGER.log( "The output is an error message : " + actionResult + ". Submit script failed!", SinkJLevel.ERROR); JOptionPane.showMessageDialog(null, "Error while processing paste. Incorrect Pastebin option!", "Error", JOptionPane.ERROR_MESSAGE); } if (actionResult.equals("Bad API request, invalid api_dev_key")) { success = false; EasyPastebin.LOGGER.log( "The output is an error message : " + actionResult + ". Submit script failed!", SinkJLevel.ERROR); JOptionPane.showMessageDialog(null, "Error while processing paste. Incorrect dev key! Try again with a more recent version!", "Error", JOptionPane.ERROR_MESSAGE); } if (actionResult.equals("Bad API request, IP blocked")) { success = false; EasyPastebin.LOGGER.log( "The output is an error message : " + actionResult + ". Submit script failed!", SinkJLevel.ERROR); JOptionPane.showMessageDialog(null, "Error while processing paste. Your IP is blocked!", "Error", JOptionPane.ERROR_MESSAGE); } if (actionResult.equals( "Bad API request, maximum number of 25 unlisted pastes for your free account")) { success = false; EasyPastebin.LOGGER.log( "The output is an error message : " + actionResult + ". Submit script failed!", SinkJLevel.ERROR); } if (actionResult.equals( "Bad API request, maximum number of 10 private pastes for your free account")) { success = false; EasyPastebin.LOGGER.log( "The output is an error message : " + actionResult + ". Submit script failed!", SinkJLevel.ERROR); } if (actionResult.equals("Bad API request, api_paste_code was empty")) { success = false; EasyPastebin.LOGGER.log( "The output is an error message : " + actionResult + ". Submit script failed!", SinkJLevel.ERROR); } if (actionResult.equals("Bad API request, maximum paste file size exceeded")) { success = false; EasyPastebin.LOGGER.log( "The output is an error message : " + actionResult + ". Submit script failed!", SinkJLevel.ERROR); JOptionPane.showMessageDialog(null, "Error while processing paste. Your paste is too big!", "Error", JOptionPane.ERROR_MESSAGE); } if (actionResult.equals("Bad API request, invalid api_expire_date")) { success = false; EasyPastebin.LOGGER.log( "The output is an error message : " + actionResult + ". Submit script failed!", SinkJLevel.ERROR); JOptionPane.showMessageDialog(null, "Error while processing paste. Invalid expire date!", "Error", JOptionPane.ERROR_MESSAGE); } if (actionResult.equals("Bad API request, invalid api_paste_private")) { success = false; EasyPastebin.LOGGER.log( "The output is an error message : " + actionResult + ". Submit script failed!", SinkJLevel.ERROR); JOptionPane.showMessageDialog(null, "Error while processing paste. Invalid privacy value!", "Error", JOptionPane.ERROR_MESSAGE); } if (actionResult.equals("Bad API request, invalid api_paste_format")) { success = false; EasyPastebin.LOGGER.log( "The output is an error message : " + actionResult + ". Submit script failed!", SinkJLevel.ERROR); JOptionPane.showMessageDialog(null, "Error while processing paste. Invalid format!", "Error", JOptionPane.ERROR_MESSAGE); } // END // Starting display stuff if (success == false) { EasyPastebin.LOGGER.log("Submit script failed : success == false", SinkJLevel.ERROR); pastebinUrl.setText("ERROR"); } if (success == true) { EasyPastebin.LOGGER.log("Paste sent! Starting display script!", SinkJLevel.INFO); pastebinUrl.setText(actionResult); JOptionPane.showMessageDialog(null, "Paste successfully sent!", "Done!", JOptionPane.INFORMATION_MESSAGE); EasyPastebin.LOGGER.log("Display script finished! Paste URL is : " + actionResult, SinkJLevel.INFO); } } catch (ClientProtocolException e) { EasyPastebin.LOGGER.log("Unexpected error! " + e, SinkJLevel.ERROR); JOptionPane.showMessageDialog(null, "Error while processing paste : " + e, "Error", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } catch (IOException e) { EasyPastebin.LOGGER.log("Unexpected error! " + e, SinkJLevel.ERROR); JOptionPane.showMessageDialog(null, "Error while processing paste : " + e, "Error", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } catch (MissingParamException e) { EasyPastebin.LOGGER.log("Unexpected error! " + e, SinkJLevel.ERROR); JOptionPane.showMessageDialog(null, "Error while processing paste : " + e + "! This is a severe programming error! Try again with a more recent version!", "Error", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } EasyPastebin.LOGGER.log("Re-enabling the Submit button ", SinkJLevel.INFO); btnSubmit.setEnabled(true); btnSubmit.setText("Submit another paste!"); EasyPastebin.LOGGER.log("Finished submit script! Success : " + success, SinkJLevel.INFO); } }); btnSubmit.setBounds(386, 45, 237, 44); main.add(btnSubmit); pastebinUrl = new JTextField(); pastebinUrl.setText("The paste's URL will be shown here!"); pastebinUrl.setEditable(false); pastebinUrl.setBounds(384, 198, 239, 32); main.add(pastebinUrl); pastebinUrl.setColumns(10); JPanel about = new JPanel(); tabbedPane.addTab("About", null, about, null); JLabel label = new JLabel("EasyPastebin"); label.setBounds(12, 12, 623, 39); label.setHorizontalAlignment(SwingConstants.CENTER); label.setFont(new Font("Dialog", Font.PLAIN, 25)); JLabel lblTheEasiestWay = new JLabel("The easiest way to use Pastebin.com"); lblTheEasiestWay.setBounds(12, 63, 623, 32); lblTheEasiestWay.setFont(new Font("Dialog", Font.PLAIN, 16)); lblTheEasiestWay.setHorizontalAlignment(SwingConstants.CENTER); about.setLayout(null); about.add(label); about.add(lblTheEasiestWay); JButton btnForkM = new JButton("Fork me on Github!"); btnForkM.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { goToUrl("https://github.com/utybo/EasyPastebin"); } }); btnForkM.setBounds(12, 117, 623, 25); about.add(btnForkM); JButton btnCheckOutUtybos = new JButton("Check out utybo's projects!"); btnCheckOutUtybos.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { goToUrl("http://utybo.github.io/"); } }); btnCheckOutUtybos.setBounds(12, 154, 623, 25); about.add(btnCheckOutUtybos); JButton btnGoToPastebincom = new JButton("Go to Pastebin.com!"); btnGoToPastebincom.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { goToUrl("http://www.pastebin.com"); } }); btnGoToPastebincom.setBounds(12, 191, 623, 25); about.add(btnGoToPastebincom); JLabel lblcUtybo = new JLabel( "This soft was made by utybo. It uses Apache's libraries for the interaction with Pastebin's API"); lblcUtybo.setFont(new Font("Dialog", Font.PLAIN, 10)); lblcUtybo.setHorizontalAlignment(SwingConstants.CENTER); lblcUtybo.setBounds(12, 324, 623, 15); about.add(lblcUtybo); JLabel lblClickMeTo = new JLabel("Click me to go to Apache's licence official website"); lblClickMeTo.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { goToUrl("http://www.apache.org/licenses/LICENSE-2.0"); } }); lblClickMeTo.setHorizontalAlignment(SwingConstants.CENTER); lblClickMeTo.setFont(new Font("Dialog", Font.PLAIN, 10)); lblClickMeTo.setBounds(12, 342, 623, 15); about.add(lblClickMeTo); setVisible(true); EasyPastebin.LOGGER.log("Done!", SinkJLevel.INFO); }
From source file:model.finance_management.Profit_And_Loss_Comparison_Model.java
private CategoryDataset createDataset() { con = DBConnection.connect();//from w w w .j a v a2s. c o m DefaultCategoryDataset dataset = new DefaultCategoryDataset(); String series1 = "Income"; String series2 = "Expense"; String series3 = "Profit"; String daily = "SELECT SUM(incomes_management.Amount), SUM(expenses_management.Amount),SUBSTRING(incomes_management.`Date Modified`,1,10) FROM incomes_management,expenses_management WHERE SUBSTRING(incomes_management.`Date Modified`,1,10)=SUBSTRING(expenses_management.`Date Modified`,1,10) GROUP BY SUBSTRING(incomes_management.`Date Modified`,1,10)"; String monthly = "SELECT SUM(incomes_management.Amount), SUM(expenses_management.Amount),SUBSTRING(incomes_management.`Date Modified`,1,7) FROM incomes_management,expenses_management WHERE SUBSTRING(incomes_management.`Date Modified`,1,7)=SUBSTRING(expenses_management.`Date Modified`,1,7) GROUP BY SUBSTRING(incomes_management.`Date Modified`,1,7)"; String annually = "SELECT SUM(incomes_management.Amount), SUM(expenses_management.Amount),SUBSTRING(incomes_management.`Date Modified`,1,4) FROM incomes_management,expenses_management WHERE SUBSTRING(incomes_management.`Date Modified`,1,4)=SUBSTRING(expenses_management.`Date Modified`,1,4) GROUP BY SUBSTRING(incomes_management.`Date Modified`,1,4)"; if (Profit_And_Loss_Comparison_Frame.cmbTimePeriod.getSelectedItem().equals("Daily")) { try { pst = con.prepareStatement(daily); ResultSet rst = pst.executeQuery(); while (rst.next()) { String incomeamounts = rst.getString("SUM(incomes_management.Amount)"); String expenseamounts = rst.getString("SUM(expenses_management.Amount)"); String day = rst.getString("SUBSTRING(incomes_management.`Date Modified`,1,10)"); float incomevalue = Float.parseFloat(incomeamounts); float expensevalue = Float.parseFloat(expenseamounts); float profit = incomevalue - expensevalue; dataset.addValue(incomevalue, series1, day); dataset.addValue(expensevalue, series2, day); dataset.addValue(profit, series3, day); } } catch (SQLException | NumberFormatException e) { JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE); } } else if (Profit_And_Loss_Comparison_Frame.cmbTimePeriod.getSelectedItem().equals("Monthly")) { try { pst = con.prepareStatement(monthly); ResultSet rst = pst.executeQuery(); while (rst.next()) { String incomeamounts = rst.getString("SUM(incomes_management.Amount)"); String expenseamounts = rst.getString("SUM(expenses_management.Amount)"); String month = rst.getString("SUBSTRING(incomes_management.`Date Modified`,1,7)"); float incomevalue = Float.parseFloat(incomeamounts); float expensevalue = Float.parseFloat(expenseamounts); float profit = incomevalue - expensevalue; dataset.addValue(incomevalue, series1, month); dataset.addValue(expensevalue, series2, month); dataset.addValue(profit, series3, month); } } catch (SQLException | NumberFormatException e) { JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE); } } else if (Profit_And_Loss_Comparison_Frame.cmbTimePeriod.getSelectedItem().equals("Annually")) { try { pst = con.prepareStatement(annually); ResultSet rst = pst.executeQuery(); while (rst.next()) { String incomeamounts = rst.getString("SUM(incomes_management.Amount)"); String expenseamounts = rst.getString("SUM(expenses_management.Amount)"); String year = rst.getString("SUBSTRING(incomes_management.`Date Modified`,1,4)"); float incomevalue = Float.parseFloat(incomeamounts); float expensevalue = Float.parseFloat(expenseamounts); float profit = incomevalue - expensevalue; dataset.addValue(incomevalue, series1, year); dataset.addValue(expensevalue, series2, year); dataset.addValue(profit, series3, year); } } catch (SQLException | NumberFormatException e) { JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE); } } return dataset; }
From source file:licenceexecuter.LicenceExecuter.java
private ObKeyExecuter register(String newKey) { try {//from w w w . j a va 2 s .c o m ObKeyExecuter ob = ControllerKey.decrypt(newKey); if (new Date().before(ob.getDataValidade())) { updateKey(ob); JOptionPane.showMessageDialog(null, "NOVA CHAVE ATIVADA COM SUCESSO"); return ob; } else { JOptionPane.showMessageDialog(null, "NOVA CHAVE ESTA VENCIDA, IMPOSSIVEL CONTINUAR."); } } catch (Throwable t) { t.printStackTrace(); } JOptionPane.showMessageDialog(null, "CHAVE INV?LIDA", "ATENO", JOptionPane.ERROR_MESSAGE); return null; }
From source file:net.sf.webphotos.util.Util.java
/** * Retorna o diretrio raiz de albuns. Checa se a varivel albunsRoot j * possui o valor, caso no, busca o arquivo nas propriedades atravs do * mtodo//from w w w . ja va2s .c o m * {@link net.sf.webphotos.util.Util#getProperty(String) getProperty}(String * chave) e faz um teste para checar se um diretrio mesmo. Caso tudo * esteja correto, retorna o diretrio. * * @param param * @return Retorna um diretrio. */ public static File getFolder(String param) { File folder = new File(getProperty(param)); if (!folder.isDirectory()) { StringBuilder errMsg = new StringBuilder(); errMsg.append("O diretrio fornecido no parmetro albunsRoot (arquivo de configurao)\n"); errMsg.append("no pode ser utilizado, ou no existe.\n"); errMsg.append("O programa ser encerrado."); JOptionPane.showMessageDialog(null, errMsg.toString(), "Erro no arquivo de configurao", JOptionPane.ERROR_MESSAGE); //throw new RuntimeException(errMsg.toString()); System.exit(-1); } return folder; }
From source file:net.sf.jabref.external.ExternalFileMenuItem.java
public boolean openLink() { frame.output(Localization.lang("External viewer called") + "."); try {/* w w w . j a v a 2s . c o m*/ Optional<ExternalFileType> type = fileType; if (!this.fileType.isPresent()) { if (this.fieldName == null) { // We don't already know the file type, so we try to deduce it from the extension: File file = new File(link); // We try to check the extension for the file: String name = file.getName(); int pos = name.indexOf('.'); String extension = (pos >= 0) && (pos < (name.length() - 1)) ? name.substring(pos + 1).trim().toLowerCase() : null; // Now we know the extension, check if it is one we know about: type = ExternalFileTypes.getInstance().getExternalFileTypeByExt(extension); fileType = type; } else { JabRefDesktop.openExternalViewer(databaseContext, link, fieldName); return true; } } if (type.isPresent() && (type.get() instanceof UnknownExternalFileType)) { return JabRefDesktop.openExternalFileUnknown(frame, entry, databaseContext, link, (UnknownExternalFileType) type.get()); } else { return JabRefDesktop.openExternalFileAnyFormat(databaseContext, link, type); } } catch (IOException e1) { // See if we should show an error message concerning the application to open the // link with. We check if the file type is set, and if the file type has a non-empty // application link. If that link is referred by the error message, we can assume // that the problem is in the open-with-application setting: if ((fileType.isPresent()) && (!fileType.get().getOpenWithApplication().isEmpty()) && e1.getMessage().contains(fileType.get().getOpenWithApplication())) { JOptionPane.showMessageDialog(frame, Localization.lang("Unable to open link. " + "The application '%0' associated with the file type '%1' could not be called.", fileType.get().getOpenWithApplication(), fileType.get().getName()), Localization.lang("Could not open link"), JOptionPane.ERROR_MESSAGE); return false; } LOGGER.warn("Unable to open link", e1); } return false; }
From source file:de.main.sessioncreator.ReportingHelper.java
private void getCharterBackgroundW(File f) { fileHelper.charterList.clear();//from w ww.j a v a 2s . co m if (fileHelper.getFilesWithCharter(f, false)) { int i = 0; for (String charter : fileHelper.charterList) { if (charterMap.containsKey(charter.substring(0, charter.indexOf("(" + f)))) { i = charterMap.get(charter.substring(0, charter.indexOf("(" + f))); i++; charterMap.remove(charter.substring(0, charter.indexOf("(" + f))); charterMap.put(charter.substring(0, charter.indexOf("(" + f)), i); } else { charterMap.put(charter.substring(0, charter.indexOf("(" + f)), 1); } } } else { JOptionPane.showMessageDialog(null, "Directory '" + f + "' does not exsits, please edit the config.txt!", "Error", JOptionPane.ERROR_MESSAGE); } }
From source file:Demo.ScatterGraph.java
private void AddDataSet(int x, int y) { List<Integer> failIndexList = new ArrayList<Integer>(); // read fail index Scanner scan = null;//from w ww. j a v a2s .c om try { scan = new Scanner(new File("data/failIndex.dat")); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(this, "failIndex.dat File doesn't exist.", "Error", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } while (scan.hasNextLine()) { failIndexList.add(Integer.parseInt(scan.nextLine())); } // read X, Y double[] valueX = Utils.GetParaTab(paraType_list.get(x)); double[] valueY = Utils.GetParaTab(paraType_list.get(y)); // create data set double[][] dataSetPass = new double[2][sampleNb - failIndexList.size()]; double[][] dataSetFail = new double[2][failIndexList.size()]; int i_f = 0; int i_p = 0; for (int i = 0; i < sampleNb; i++) { if (failIndexList.contains(new Integer(i + 1))) { dataSetFail[0][i_f] = valueX[i]; dataSetFail[1][i_f] = valueY[i]; i_f++; } else { dataSetPass[0][i_p] = valueX[i]; dataSetPass[1][i_p] = valueY[i]; i_p++; } } dataSet.addSeries("pass", dataSetPass); dataSet.addSeries("fail", dataSetFail); }
From source file:com.emr.schemas.ForeignDataMover.java
private List getDatabaseTables(Connection con) { List tables = new ArrayList(); try {// ww w .j a v a 2 s .co m DatabaseMetaData dbmd = con.getMetaData(); String[] types = { "TABLE" }; ResultSet rs = dbmd.getTables(null, null, "%", types); while (rs.next()) { //Add table name to Jlist tables.add(rs.getString("TABLE_NAME")); } } catch (SQLException e) { String stacktrace = org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e); JOptionPane.showMessageDialog(this, "Could not fetch Tables for the KenyaEMR Database. Error Details: " + stacktrace, "Table Names Error", JOptionPane.ERROR_MESSAGE); } return tables; }
From source file:EditorPaneExample7.java
public EditorPaneExample7() { super("JEditorPane Example 7"); pane = new JEditorPane(); pane.setEditable(false); // Start read-only getContentPane().add(new JScrollPane(pane), "Center"); // Build the panel of controls JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridwidth = 1;/*from w w w . j av a2 s . c o m*/ c.gridheight = 1; c.anchor = GridBagConstraints.EAST; c.fill = GridBagConstraints.NONE; c.weightx = 0.0; c.weighty = 0.0; JLabel urlLabel = new JLabel("File name: ", JLabel.RIGHT); panel.add(urlLabel, c); JLabel loadingLabel = new JLabel("State: ", JLabel.RIGHT); c.gridy = 1; panel.add(loadingLabel, c); JLabel typeLabel = new JLabel("Type: ", JLabel.RIGHT); c.gridy = 2; panel.add(typeLabel, c); c.gridx = 1; c.gridy = 0; c.gridwidth = 1; c.weightx = 1.0; c.fill = GridBagConstraints.HORIZONTAL; textField = new JTextField(32); panel.add(textField, c); loadingState = new JLabel(spaces, JLabel.LEFT); loadingState.setForeground(Color.black); c.gridy = 1; c.gridwidth = 2; panel.add(loadingState, c); loadedType = new JLabel(spaces, JLabel.LEFT); loadedType.setForeground(Color.black); c.gridy = 2; panel.add(loadedType, c); getContentPane().add(panel, "South"); panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); saveButton = new JButton("Save"); plain = new JCheckBox("Plain Text"); html = new JCheckBox("HTML"); rtf = new JCheckBox("RTF"); panel.add(plain); panel.add(html); panel.add(rtf); ButtonGroup group = new ButtonGroup(); group.add(plain); group.add(html); group.add(rtf); plain.setSelected(true); panel.add(Box.createVerticalStrut(10)); panel.add(saveButton); panel.add(Box.createVerticalGlue()); panel.setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4)); getContentPane().add(panel, "East"); // Change page based on text field textField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { String fileName = textField.getText().trim(); file = new File(fileName); absolutePath = file.getAbsolutePath(); String url = "file:///" + absolutePath; try { // Check if the new page and the old // page are the same. URL newURL = new URL(url); URL loadedURL = pane.getPage(); if (loadedURL != null && loadedURL.sameFile(newURL)) { return; } // Try to display the page textField.setEnabled(false); // Disable input textField.paintImmediately(0, 0, textField.getSize().width, textField.getSize().height); saveButton.setEnabled(false); saveButton.paintImmediately(0, 0, saveButton.getSize().width, saveButton.getSize().height); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); // Busy cursor loadingState.setText("Loading..."); loadingState.paintImmediately(0, 0, loadingState.getSize().width, loadingState.getSize().height); loadedType.setText(""); loadedType.paintImmediately(0, 0, loadedType.getSize().width, loadedType.getSize().height); pane.setEditable(false); pane.setPage(url); loadedType.setText(pane.getContentType()); } catch (Exception e) { JOptionPane.showMessageDialog(pane, new String[] { "Unable to open file", url }, "File Open Error", JOptionPane.ERROR_MESSAGE); loadingState.setText("Failed"); textField.setEnabled(true); setCursor(Cursor.getDefaultCursor()); } } }); // Listen for page load to complete pane.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("page")) { loadingState.setText("Page loaded."); textField.setEnabled(true); // Allow entry of new file name textField.requestFocus(); setCursor(Cursor.getDefaultCursor()); // Allow editing and saving if appropriate pane.setEditable(file.canWrite()); saveButton.setEnabled(file.canWrite()); } } }); saveButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { Writer w = null; OutputStream os = System.out; String contentType; if (plain.isSelected()) { contentType = "text/plain"; w = new OutputStreamWriter(os); } else if (html.isSelected()) { contentType = "text/html"; w = new OutputStreamWriter(os); } else { contentType = "text/rtf"; } EditorKit kit = pane.getEditorKitForContentType(contentType); try { if (w != null) { kit.write(w, pane.getDocument(), 0, pane.getDocument().getLength()); w.flush(); } else { kit.write(os, pane.getDocument(), 0, pane.getDocument().getLength()); os.flush(); } } catch (Exception e) { System.out.println("Write failed"); } } }); }