List of usage examples for com.jgoodies.forms.builder ButtonBarBuilder addRelatedGap
@Override
public ButtonBarBuilder addRelatedGap()
From source file:Save_As_Dicom.java
License:Open Source License
public int setup(String path, ImagePlus ip) { this.ip = ip; this.path = path; anonDialog = new JDialog(); anonDialog.setModal(true);/*from ww w . ja v a2s .co m*/ anonDialog.setLayout(new BorderLayout()); multiSliceExport = new JCheckBox("Export as Multislice"); anonDialog.add(multiSliceExport, BorderLayout.NORTH); anonDialog.add(anonPanel, BorderLayout.CENTER); f = null; if (path != null && path != "") { f = new File(path); silent = true; } String macroOptions = Macro.getOptions(); if (macroOptions != null) { path = Macro.getValue(macroOptions, "filename", null); if (path != null) { f = new File(path); silent = true; } } anonPanel.setRemovePatient(!silent); anonPanel.setRemoveInstitution(!silent); anonPanel.setRemoveManufacturer(!silent); ButtonBarBuilder bb = new ButtonBarBuilder(); bb.addGlue(); cancelButton = new JButton("cancel"); cancelButton.addActionListener(this); bb.addGridded(cancelButton); bb.addRelatedGap(); okButton = new JButton("run"); okButton.addActionListener(this); bb.addGridded(okButton); JPanel buttonPanel = bb.getPanel(); buttonPanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3)); buttonPanel.setOpaque(false); anonDialog.add(buttonPanel, BorderLayout.SOUTH); anonDialog.pack(); return DOES_8G + DOES_16 + DOES_RGB; }
From source file:ca.sqlpower.architect.swingui.action.VisualMappingReportAction.java
License:Open Source License
public void actionPerformed(ActionEvent e) { try {/*from w w w . ja v a 2s . c o m*/ if (getSession() == null) return; final MappingReport mr; final List<SQLTable> selectedTables; final List<TablePane> selectedTablePanes = new ArrayList<TablePane>(); for (ContainerPane<?, ?> cp : getPlaypen().getSelectedContainers()) { if (cp instanceof TablePane) { selectedTablePanes.add((TablePane) cp); } } if (selectedTablePanes.size() == 0) { selectedTables = new ArrayList<SQLTable>(getPlaypen().getTables()); } else { if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(frame, Messages.getString("VisualMappingReportAction.viewOnlySelectedTables", //$NON-NLS-1$ String.valueOf(selectedTablePanes.size())), Messages.getString("VisualMappingReportAction.viewOnlySelectedTablesDialogTitle"), //$NON-NLS-1$ JOptionPane.YES_NO_OPTION)) { selectedTables = new ArrayList<SQLTable>(); for (TablePane tp : selectedTablePanes) { selectedTables.add(tp.getModel()); } } else { selectedTables = new ArrayList<SQLTable>(getPlaypen().getTables()); } } mr = new MappingReport(getSession(), selectedTables); final JFrame f = new JFrame(Messages.getString("VisualMappingReportAction.mappingReportDialogTitle")); //$NON-NLS-1$ f.setIconImage(ASUtils.getFrameIconImage()); // You call this a radar?? -- No sir, we call it Mr. Panel. JPanel mrPanel = new JPanel() { protected void paintComponent(java.awt.Graphics g) { super.paintComponent(g); try { mr.drawHighLevelReport((Graphics2D) g, null); } catch (SQLObjectException e1) { logger.error("ArchitectException while generating mapping diagram", e1); //$NON-NLS-1$ ASUtils.showExceptionDialogNoReport( Messages.getString("VisualMappingReportAction.couldNotGenerateMappingDiagram"), e1); //$NON-NLS-1$ } } }; mrPanel.setDoubleBuffered(true); mrPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); mrPanel.setPreferredSize(mr.getRequiredSize()); mrPanel.setOpaque(true); mrPanel.setBackground(Color.WHITE); ButtonBarBuilder buttonBar = new ButtonBarBuilder(); JButton csv = new JButton(new AbstractAction() { public void actionPerformed(ActionEvent e) { FileWriter output = null; try { ExportCSV export = new ExportCSV(selectedTables); File file = null; JFileChooser fileDialog = new JFileChooser( getSession().getRecentMenu().getMostRecentFile()); fileDialog.setSelectedFile(new File("map.csv")); //$NON-NLS-1$ if (fileDialog.showSaveDialog(f) == JFileChooser.APPROVE_OPTION) { file = fileDialog.getSelectedFile(); } else { return; } output = new FileWriter(file); output.write(export.getCSVMapping()); output.flush(); } catch (IOException e1) { throw new RuntimeException(e1); } catch (SQLObjectException e1) { throw new SQLObjectRuntimeException(e1); } finally { if (output != null) { try { output.close(); } catch (IOException e1) { logger.error("IO Error", e1); //$NON-NLS-1$ } } } } }); csv.setText(Messages.getString("VisualMappingReportAction.exportCSVOption")); //$NON-NLS-1$ buttonBar.addGriddedGrowing(csv); JButton close = new JButton(new AbstractAction() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); close.setText(Messages.getString("VisualMappingReportAction.closeOption")); //$NON-NLS-1$ buttonBar.addRelatedGap(); buttonBar.addGriddedGrowing(close); JPanel basePane = new JPanel(new BorderLayout(5, 5)); basePane.add(new JScrollPane(mrPanel), BorderLayout.CENTER); basePane.add(buttonBar.getPanel(), BorderLayout.SOUTH); f.setContentPane(basePane); f.pack(); f.setLocationRelativeTo(frame); f.setVisible(true); } catch (SQLObjectException e1) { throw new SQLObjectRuntimeException(e1); } }
From source file:ca.sqlpower.architect.swingui.CompareDMFrame.java
License:Open Source License
public JComponent mainFrame() { FormLayout layout = new FormLayout( "4dlu,fill:min(150dlu;default):grow, 6dlu, fill:min(150dlu;default):grow, 4dlu", // columns //$NON-NLS-1$ " min(300dlu;default), 6dlu, min(300dlu;default), 6dlu, min(300dlu;default), 3dlu, fill:min(300dlu;default):grow, 3dlu, 20dlu,6dlu,20dlu"); // rows //$NON-NLS-1$ CellConstraints cc = new CellConstraints(); JLabel titleLabel = new JLabel(title); Font oldFont = titleLabel.getFont(); Font titleFont = new Font(oldFont.getName(), oldFont.getStyle(), oldFont.getSize() * 2); titleLabel.setFont(titleFont);// w w w .ja v a2 s . co m JLabel subTitleLabel = new JLabel(whatTheHeckIsGoingOn); leftOutputArea = new JTextPane(); leftOutputArea.setMargin(new Insets(6, 10, 4, 6)); leftOutputArea.setDocument(sourceOutputText); leftOutputArea.setEditable(false); JPanel comparePanel = new JPanel(new GridLayout(1, 2)); JScrollPane sp = new JScrollPane(comparePanel); int lineHeight = 16; try { FontMetrics fm = leftOutputArea.getFontMetrics(leftOutputArea.getFont()); lineHeight = fm.getHeight() + 2; } catch (Exception e) { lineHeight = 16; } // If the increments are not set, klicking on the up or down arrow of the scrollbar // will scroll the display by one pixel, which is definitely not what the user wants // by setting unitIncrement to the font's height the display will scroll by approx. one line sp.getVerticalScrollBar().setUnitIncrement(lineHeight); // Clicking in the "empty" area of the scrollbar will scroll by 10 lines sp.getVerticalScrollBar().setBlockIncrement(lineHeight * 10); comparePanel.add(leftOutputArea); Action sourceCopy = new sourceCopyAction(sourceOutputText); Action sourceSave = new AbstractAction() { public void actionPerformed(ActionEvent e) { SPSUtils.saveDocument(CompareDMFrame.this, sourceOutputText, (FileExtensionFilter) SPSUtils.TEXT_FILE_FILTER); } }; CloseAction close = new CloseAction(); close.setDialog(this); SPSUtils.makeJDialogCancellable(this, close); ButtonBarBuilder sourcebbBuilder = new ButtonBarBuilder(); JButton copySource = new JButton(sourceCopy); copySource.setText(Messages.getString("CompareDMFrame.copy")); //$NON-NLS-1$ sourcebbBuilder.addGridded(copySource); sourcebbBuilder.addRelatedGap(); sourcebbBuilder.addGlue(); JButton sourceSaveButton = new JButton(sourceSave); sourceSaveButton.setText(Messages.getString("CompareDMFrame.save")); //$NON-NLS-1$ sourcebbBuilder.addGridded(sourceSaveButton); sourcebbBuilder.addRelatedGap(); sourcebbBuilder.addGlue(); ButtonBarBuilder closeBar = new ButtonBarBuilder(); JButton closeButton = new JButton(close); closeButton.setText(Messages.getString("CompareDMFrame.close")); //$NON-NLS-1$ closeBar.addGridded(closeButton); PanelBuilder pb; layout.setColumnGroups(new int[][] { { 2, 4 } }); JPanel p = logger.isDebugEnabled() ? new FormDebugPanel(layout) : new JPanel(layout); pb = new PanelBuilder(layout, p); pb.setDefaultDialogBorder(); rightOutputArea = new JTextPane(); rightOutputArea.setMargin(new Insets(6, 10, 4, 6)); rightOutputArea.setDocument(targetOutputText); rightOutputArea.setEditable(false); comparePanel.add(rightOutputArea); Action targetCopy = new targetCopyAction(targetOutputText); //Sets the target Buttons ButtonBarBuilder targetbbBuilder = new ButtonBarBuilder(); JButton copyTarget = new JButton(targetCopy); copyTarget.setText(Messages.getString("CompareDMFrame.copy")); //$NON-NLS-1$ targetbbBuilder.addGridded(copyTarget); targetbbBuilder.addRelatedGap(); targetbbBuilder.addGlue(); Action targetSaveAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { SPSUtils.saveDocument(CompareDMFrame.this, targetOutputText, (FileExtensionFilter) SPSUtils.TEXT_FILE_FILTER); } }; JButton targetSave = new JButton(targetSaveAction); targetSave.setText(Messages.getString("CompareDMFrame.save")); //$NON-NLS-1$ targetbbBuilder.addGridded(targetSave); targetbbBuilder.addRelatedGap(); targetbbBuilder.addGlue(); getRootPane().setDefaultButton(targetSave); pb.add(titleLabel, cc.xyw(2, 1, 3, "c,c")); //$NON-NLS-1$ pb.add(subTitleLabel, cc.xyw(2, 3, 3, "c,c")); //$NON-NLS-1$ pb.add(new JLabel(Messages.getString("CompareDMFrame.older")), cc.xy(2, 5)); //$NON-NLS-1$ pb.add(new JLabel(Messages.getString("CompareDMFrame.newer")), cc.xy(4, 5)); //$NON-NLS-1$ pb.add(sp, cc.xyw(2, 7, 3)); pb.add(sourcebbBuilder.getPanel(), cc.xy(2, 9, "l,c")); //$NON-NLS-1$ pb.add(targetbbBuilder.getPanel(), cc.xy(4, 9, "r,c")); //$NON-NLS-1$ pb.add(closeBar.getPanel(), cc.xy(4, 11, "r,c")); //$NON-NLS-1$ return pb.getPanel(); }
From source file:ca.sqlpower.architect.swingui.enterprise.ProjectSecurityPanel.java
License:Open Source License
/** * This rebuilds the panel based on the {@link #userModel} and {@link #groupModel}. * To do this it also removes all of the panels from the main {@link #panel} and * adds new ones to it.//from w w w .ja v a2 s .c o m */ private void refreshPanel() { userModel = new GroupOrUserTableModel(User.class); groupModel = new GroupOrUserTableModel(Group.class); CellConstraints cc = new CellConstraints(); DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout("pref", "pref:grow, 5dlu, pref:grow, pref:grow, 5dlu, pref:grow, pref:grow, 5dlu, pref:grow")); builder.add(panelLabel, cc.xy(1, 1)); // User list and headers JLabel userPermissions = new JLabel("User Permissions"); userPermissions.setFont( new Font(userPermissions.getFont().getFontName(), Font.BOLD, userPermissions.getFont().getSize())); builder.add(userPermissions, cc.xy(1, 3)); builder.add(userModel.getPanel(), cc.xy(1, 4)); // Group list and headers JLabel groupPermissions = new JLabel("Group Permissions"); groupPermissions.setFont(userPermissions.getFont()); builder.add(groupPermissions, cc.xy(1, 6)); builder.add(groupModel.getPanel(), cc.xy(1, 7)); JButton okButton = new JButton(new AbstractAction("OK") { public void actionPerformed(ActionEvent e) { userModel.applyChanges(); groupModel.applyChanges(); closeAction.actionPerformed(e); } }); JButton cancelButton = new JButton(new AbstractAction("Cancel") { public void actionPerformed(ActionEvent e) { userModel.discardChanges(); groupModel.discardChanges(); closeAction.actionPerformed(e); } }); ButtonBarBuilder buttonBuilder = ButtonBarBuilder.createLeftToRightBuilder(); buttonBuilder.addGlue(); buttonBuilder.addGridded(okButton); buttonBuilder.addRelatedGap(); buttonBuilder.addGridded(cancelButton); buttonBuilder.setDefaultButtonBarGapBorder(); builder.add(buttonBuilder.getPanel(), cc.xy(1, 9)); builder.setDefaultDialogBorder(); panel.removeAll(); panel.add(builder.getPanel()); panel.revalidate(); disableIfNecessary(); }
From source file:ca.sqlpower.architect.swingui.SQLScriptDialog.java
License:Open Source License
private JPanel buildPanel() { FormLayout sqlLayout = new FormLayout("4dlu, min:grow, 4dlu", //columns //$NON-NLS-1$ "pref, 4dlu, pref, 6dlu, fill:300dlu:grow,6dlu, pref, 6dlu, pref"); //rows //$NON-NLS-1$ CellConstraints cc = new CellConstraints(); sqlDoc = new DefaultStyledDocument(); SimpleAttributeSet att = new SimpleAttributeSet(); StyleConstants.setForeground(att, Color.black); for (DDLStatement ddl : statements) { try {// ww w . j av a2 s . com sqlDoc.insertString(sqlDoc.getLength(), ddl.getSQLText() + ddl.getSqlTerminator(), att); } catch (BadLocationException e) { ASUtils.showExceptionDialogNoReport(parent, Messages.getString("SQLScriptDialog.couldNotCreateDocument"), e); //$NON-NLS-1$ logger.error("Could not create document for results", e); //$NON-NLS-1$ } } sqlScriptArea = new JTextPane(); sqlScriptArea.setMargin(new Insets(6, 10, 4, 6)); sqlScriptArea.setDocument(sqlDoc); sqlScriptArea.setEditable(false); sqlScriptArea.setAutoscrolls(true); JScrollPane sp = new JScrollPane(sqlScriptArea); Action copy = new CopyAction(sqlDoc); Action execute = null; execute = new AbstractAction() { public void actionPerformed(ActionEvent e) { if (targetDataSource.get(JDBCDataSource.PL_UID) != null) { new Thread(executeTask).start(); ProgressWatcher.watchProgress(progressBar, executeTask, statusLabel); } else { JOptionPane.showMessageDialog(SQLScriptDialog.this, Messages.getString("SQLScriptDialog.noTargetDb"), //$NON-NLS-1$ Messages.getString("SQLScriptDialog.couldNotExecuteDialogTitle"), //$NON-NLS-1$ JOptionPane.ERROR_MESSAGE); } } }; Action save = new AbstractAction() { public void actionPerformed(ActionEvent e) { logger.info("SQL_FILE_FILTER:" + ((FileExtensionFilter) SPSUtils.SQL_FILE_FILTER).toString()); //$NON-NLS-1$ SPSUtils.saveDocument(parent, sqlDoc, (FileExtensionFilter) SPSUtils.SQL_FILE_FILTER); } }; CloseAction close = new CloseAction(); close.setWhatToClose(this); SPSUtils.makeJDialogCancellable(this, close); ButtonBarBuilder barBuilder = new ButtonBarBuilder(); JButton copyButton = new JButton(copy); copyButton.setText(Messages.getString("SQLScriptDialog.copyOption")); //$NON-NLS-1$ barBuilder.addGridded(copyButton); barBuilder.addRelatedGap(); barBuilder.addGlue(); executeButton = new JButton(execute); executeButton.setText(Messages.getString("SQLScriptDialog.executeOption")); //$NON-NLS-1$ barBuilder.addGridded(executeButton); barBuilder.addRelatedGap(); barBuilder.addGlue(); JButton saveButton = new JButton(save); saveButton.setText(Messages.getString("SQLScriptDialog.saveOption")); //$NON-NLS-1$ barBuilder.addGridded(saveButton); barBuilder.addRelatedGap(); barBuilder.addGlue(); addWindowListener(new CloseWindowAction()); JButton closeButton = new JButton(close); closeButton.setText(Messages.getString("SQLScriptDialog.closeOption")); //$NON-NLS-1$ barBuilder.addGridded(closeButton); getRootPane().setDefaultButton(executeButton); PanelBuilder pb; JPanel panel = logger.isDebugEnabled() ? new FormDebugPanel(sqlLayout) : new JPanel(sqlLayout); pb = new PanelBuilder(sqlLayout, panel); pb.setDefaultDialogBorder(); pb.add(new JLabel(header), cc.xy(2, 1)); // Prevent the user from being able to execute the script if // an invalid target database is selected. if (targetDataSource != null && targetDataSource.get(JDBCDataSource.PL_UID) != null) { pb.add(new JLabel(Messages.getString("SQLScriptDialog.yourTargetDbIs") + targetDataSource.getName()), //$NON-NLS-1$ cc.xy(2, 3)); executeButton.setEnabled(true); } else { pb.add(new JLabel(Messages.getString("SQLScriptDialog.yourTargetDbIsNotConfigured")), cc.xy(2, 3)); executeButton.setEnabled(false); } pb.add(sp, cc.xy(2, 5)); pb.add(barBuilder.getPanel(), cc.xy(2, 7, "c,c")); //$NON-NLS-1$ pb.add(progressBar, cc.xy(2, 9)); return pb.getPanel(); }
From source file:ca.sqlpower.architect.swingui.UserRepositoryDirectoryChooser.java
License:Open Source License
/** * This method allows the selection of the directory. Null is returned if the user cancelled. *//*from ww w . j a v a 2 s .co m*/ public RepositoryDirectory selectDirectory(Repository repo) { final JDialog chooserDialog = new JDialog(parent); chooserDialog.setTitle(Messages.getString("UserRepositoryDirectoryChooser.selectRepositoryDialogTitle")); //$NON-NLS-1$ FormLayout layout = new FormLayout("10dlu, 2dlu, fill:pref:grow, 12dlu", "pref, fill:pref:grow, pref"); //$NON-NLS-1$ //$NON-NLS-2$ DefaultFormBuilder builder = new DefaultFormBuilder(layout); builder.setDefaultDialogBorder(); builder.nextColumn(2); builder.append(Messages.getString("UserRepositoryDirectoryChooser.chooseDirectory")); //$NON-NLS-1$ builder.nextLine(); DefaultMutableTreeNode root = populateTree(repo.getDirectoryTree()); final JTree tree = new JTree(root); builder.append(""); //$NON-NLS-1$ JScrollPane scrollPane = new JScrollPane(tree); scrollPane.setPreferredSize(new Dimension(200, 350)); builder.append(scrollPane); ButtonBarBuilder buttonBar = new ButtonBarBuilder(); buttonBar.addGlue(); JButton okButton = new JButton(Messages.getString("UserRepositoryDirectoryChooser.okOption")); //$NON-NLS-1$ okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (tree.getSelectionPath() == null) { return; } directory = (RepositoryDirectory) ((DefaultMutableTreeNode) tree.getSelectionPath() .getLastPathComponent()).getUserObject(); chooserDialog.dispose(); } }); buttonBar.addGridded(okButton); buttonBar.addRelatedGap(); JButton cancelButton = new JButton(Messages.getString("UserRepositoryDirectoryChooser.cancelOption")); //$NON-NLS-1$ cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { directory = null; chooserDialog.dispose(); } }); buttonBar.addGridded(cancelButton); builder.nextLine(); builder.append(""); //$NON-NLS-1$ builder.add(buttonBar.getPanel()); chooserDialog.add(builder.getPanel()); chooserDialog.setModal(true); Runnable promptUser = new Runnable() { public void run() { chooserDialog.pack(); chooserDialog.setLocationRelativeTo(parent); chooserDialog.setVisible(true); } }; if (SwingUtilities.isEventDispatchThread()) { promptUser.run(); } else { try { SwingUtilities.invokeAndWait(promptUser); } catch (InterruptedException e) { ASUtils.showExceptionDialogNoReport(parent, "While queing the dialog's pack, setVisible and setLocation, we were interrupted", e); //$NON-NLS-1$ } catch (InvocationTargetException e) { ASUtils.showExceptionDialogNoReport(parent, "While queing the dialog's pack, setVisible and setLocation, an InvocationTargetException was thrown", //$NON-NLS-1$ e); } } return directory; }
From source file:ca.sqlpower.matchmaker.swingui.action.ShowMatchStatisticInfoAction.java
License:Open Source License
public void actionPerformed(ActionEvent e) { if (project == null) { JOptionPane.showMessageDialog(parent, "No project selected", "Error", JOptionPane.ERROR_MESSAGE); return;/*from ww w. jav a 2s . c o m*/ } MatchStatisticsPanel p = null; try { p = new MatchStatisticsPanel(swingSession, project); } catch (SQLException e1) { MMSUtils.showExceptionDialog(parent, "Could not get match statistics information", e1); return; } if (p == null) { JOptionPane.showMessageDialog(parent, "No match statistics available", "Error", JOptionPane.ERROR_MESSAGE); return; } if (d == null) { d = new JDialog(parent); JPanel panel = new JPanel(new BorderLayout()); final MatchStatisticsPanel p2 = p; JButton deleteAllButton = new JButton(new AbstractAction("Delete All") { public void actionPerformed(ActionEvent e) { // XXX Nothing to do at the moment since no statistics exist. } }); JButton deleteBackwardButton = new JButton(new AbstractAction("Delete Backward") { public void actionPerformed(ActionEvent e) { // XXX Nothing to do at the moment since no statistics exist. } }); Action closeAction = new CommonCloseAction(d); closeAction.putValue(Action.NAME, "Close"); JButton closeButton = new JButton(closeAction); ButtonBarBuilder bbb = new ButtonBarBuilder(); bbb.addRelatedGap(); bbb.addGridded(deleteAllButton); bbb.addRelatedGap(); bbb.addGridded(deleteBackwardButton); bbb.addGlue(); bbb.addGridded(closeButton); bbb.addRelatedGap(); panel.add(bbb.getPanel(), BorderLayout.SOUTH); SPSUtils.makeJDialogCancellable(d, closeAction); panel.add(p, BorderLayout.CENTER); panel.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12)); d.add(panel); d.setTitle("Match Statistics"); d.setPreferredSize(new Dimension(800, 600)); d.pack(); } d.setVisible(true); }
From source file:ca.sqlpower.matchmaker.swingui.address.AddressValidationEntryPanel.java
License:Open Source License
private void buildUI() { DefaultFormBuilder builder = new DefaultFormBuilder( new FormLayout("fill:pref:grow,4dlu,fill:pref", "pref,4dlu,pref,4dlu,fill:pref:grow"), panel); builder.setDefaultDialogBorder();/* w ww. j ava 2 s . co m*/ CellConstraints cc = new CellConstraints(); try { final Address address1; logger.debug("ADDRESS BEFORE PARSING IS : " + addressResult.getOutputAddress()); address1 = Address.parse(addressResult.getOutputAddress().getAddress(), addressResult.getOutputAddress().getMunicipality(), addressResult.getOutputAddress().getProvince(), addressResult.getOutputAddress().getPostalCode(), addressResult.getOutputAddress().getCountry(), addressDatabase); logger.debug("ADDRESS AFTER PARSING IS : " + address1); logger.debug("The output address is not empty."); logger.debug("The non-empty address is: " + address1); this.addressValidator = new AddressValidator(addressDatabase, address1); JButton saveButton = new JButton("Save"); selectedAddressLabel = new AddressLabel(addressResult.getOutputAddress(), null, true, addressValidator.isAddressValid()); selectedAddressLabel.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("currentAddress")) { // update the suggestionList Address address = (Address) evt.getNewValue(); if (address.getType() == null) { //unparsed address, needs to be parsed, This could also be a failed to parse address, won't hurt to try parsing again try { address = Address.parse(address.getAddress(), address.getMunicipality(), address.getProvince(), address.getPostalCode(), address.getCountry(), addressDatabase); } catch (RecognitionException e) { MMSUtils.showExceptionDialog(panel, "There was an error while trying to parse this address", e); } catch (DatabaseException e) { MMSUtils.showExceptionDialog(panel, "There was a database error while trying to parse this address", e); } } addressValidator = new AddressValidator(addressDatabase, address); suggestionList.setModel(new JList(addressValidator.getSuggestions().toArray()).getModel()); selectedAddressLabel.setAddressValid(addressValidator.isAddressValid()); updateProblemDetails(); save(); } } }); selectedAddressLabel.setFont(selectedAddressLabel.getFont() .deriveFont((float) (selectedAddressLabel.getFont().getSize() + 3))); JButton revertButton = new JButton("Revert"); revertButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { logger.debug("Revert Address: " + addressResult.toString()); Address address = Address.parse(addressResult.getInputAddress().getUnparsedAddressLine1(), addressResult.getInputAddress().getMunicipality(), addressResult.getInputAddress().getProvince(), addressResult.getInputAddress().getPostalCode(), addressResult.getInputAddress().getCountry(), addressDatabase); addressResult.setOutputAddress(selectedAddressLabel.getCurrentAddress()); selectedAddressLabel.setCurrentAddress(address); } catch (RecognitionException e1) { e1.printStackTrace(); } catch (DatabaseException e1) { throw new RuntimeException("A database exception occurred while parsing the address" + e1); } } }); saveButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { save(); } }); // undoButton = new JButton("Undo"); // redoButton = new JButton("Redo"); JLabel suggestLabel = new JLabel("Suggestions:"); suggestLabel.setFont(suggestLabel.getFont().deriveFont(Font.BOLD)); problemsBuilder = new DefaultFormBuilder(new FormLayout("fill:pref:grow")); updateProblemDetails(); suggestionList = new JList(addressValidator.getSuggestions().toArray()); logger.debug("There are " + addressValidator.getSuggestions().size() + " suggestions."); suggestionList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); suggestionList.setCellRenderer(new AddressListCellRenderer(address1, false)); suggestionList.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) { logger.debug("Mouse Clicked on suggestion list " + ((JList) e.getSource()).getSelectedValue()); final Address selected = (Address) ((JList) e.getSource()).getSelectedValue(); if (selected != null) { //XXX:This does not update the model currently selectedAddressLabel.setCurrentAddress(selected); } } }); JScrollPane scrollList = new JScrollPane(suggestionList); scrollList.setPreferredSize(new Dimension(230, 1000)); ButtonBarBuilder bbb = new ButtonBarBuilder(); bbb.addRelatedGap(); bbb.addGridded(revertButton); bbb.addRelatedGap(); bbb.addGridded(saveButton); bbb.addRelatedGap(); builder.add(bbb.getPanel(), cc.xy(1, 1)); builder.add(suggestLabel, cc.xy(3, 1)); builder.add(selectedAddressLabel, cc.xy(1, 3)); builder.add(problemsBuilder.getPanel(), cc.xy(1, 5)); builder.add(scrollList, cc.xywh(3, 3, 1, 3)); } catch (RecognitionException e1) { MMSUtils.showExceptionDialog(getPanel(), "There was an error while trying to parse this address", e1); } catch (DatabaseException e1) { MMSUtils.showExceptionDialog(getPanel(), "There was a database error while trying to parse this address", e1); } }
From source file:ca.sqlpower.matchmaker.swingui.engine.EngineSettingsPanel.java
License:Open Source License
/** * Builds the UI for this editor pane. This is broken into two parts, * the configuration and output. Configuration is done in this method * while the output section is handled by the EngineOutputPanel and * this method simply lays out the components that class provides. *///from www .j av a 2s.c o m private JPanel buildUI() { logger.debug("We are building the UI of an engine settings panel."); if (type == EngineType.ADDRESS_CORRECTION_ENGINE) { expiryDatePane = new JEditorPane(); expiryDatePane.setEditable(false); final AddressDatabase addressDatabase; try { addressDatabase = new AddressDatabase( new File(swingSession.getContext().getAddressCorrectionDataPath())); expiryDate = addressDatabase.getExpiryDate(); expiryDatePane.setText(DateFormat.getDateInstance().format(expiryDate)); } catch (DatabaseException e1) { MMSUtils.showExceptionDialog(parentFrame, "An error occured while loading the Address Correction Data", e1); expiryDatePane.setText("Database missing, expiry date invalid"); } logger.debug("We are adding the listener"); swingSession.getContext().addPreferenceChangeListener(new PreferenceChangeListener() { public void preferenceChange(PreferenceChangeEvent evt) { if (MatchMakerSessionContext.ADDRESS_CORRECTION_DATA_PATH.equals(evt.getKey())) { logger.debug("The new database path is: " + evt.getNewValue()); final AddressDatabase addressDatabase; try { addressDatabase = new AddressDatabase(new File(evt.getNewValue())); expiryDate = addressDatabase.getExpiryDate(); expiryDatePane.setText(DateFormat.getDateInstance().format(expiryDate)); } catch (DatabaseException ex) { MMSUtils.showExceptionDialog(parentFrame, "An error occured while loading the Address Correction Data", ex); expiryDate = null; expiryDatePane.setText("Database missing, expiry date invalid"); } } } }); // handler listens to expiryDatePane so whenever the expiryDatePane's text has been changed, the below method will be called. handler.addValidateObject(expiryDatePane, new Validator() { public ValidateResult validate(Object contents) { if (expiryDate == null) { return ValidateResult.createValidateResult(Status.FAIL, "Address Correction Database is missing. Please reset your Address Correction Data Path in Preferences."); } if (Calendar.getInstance().getTime().after(expiryDate)) { return ValidateResult.createValidateResult(Status.WARN, "Address Correction Database is expired. The results of this engine run cannot be SERP valid."); } return ValidateResult.createValidateResult(Status.OK, ""); } }); } File logFile = engineSettings.getLog(); logFilePath = new JTextField(logFile.getAbsolutePath()); handler.addValidateObject(logFilePath, new FileNameValidator("Log")); browseLogFileAction = new BrowseFileAction(parentFrame, logFilePath); appendToLog = new JCheckBox("Append to old Log File?", engineSettings.getAppendToLog()); recordsToProcess = new JSpinner(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 100)); if (engineSettings.getProcessCount() != null) { recordsToProcess.setValue(engineSettings.getProcessCount()); } spinnerUpdateManager = new SpinnerUpdateManager(recordsToProcess, engineSettings, "processCount", handler, this, refreshButton); debugMode = new JCheckBox("Debug Mode (Changes will be rolled back)", engineSettings.getDebug()); updaters.add(new CheckBoxModelUpdater(debugMode, "debug")); engineSettings.addSPListener(updaters.get(updaters.size() - 1)); itemListener = new ItemListener() { public void itemStateChanged(ItemEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { if (type == EngineType.MATCH_ENGINE || type == EngineType.ADDRESS_CORRECTION_ENGINE) { clearMatchPool.setSelected(false); // I've currently disabled the clear match pool option because the match // in debug mode, changes should be rolled back, but if the clearing of the match // pool is rolled back but the engine thinks that it is cleared, it can cause // unique key violations when it tries to insert 'new' matches. But if the engine // is made aware of the rollback, then it would be as if clear match pool wasn't // selected in the first place, so I don't see the point in enabling it in debug mode clearMatchPool.setEnabled(false); } recordsToProcess.setValue(new Integer(1)); engine.setMessageLevel(Level.ALL); messageLevel.setSelectedItem(engine.getMessageLevel()); } else { if (type == EngineType.MATCH_ENGINE || type == EngineType.ADDRESS_CORRECTION_ENGINE) { clearMatchPool.setEnabled(true); } recordsToProcess.setValue(new Integer(0)); } engineSettings.setDebug(debugMode.isSelected()); } }; debugMode.addItemListener(itemListener); if (type == EngineType.MATCH_ENGINE || type == EngineType.ADDRESS_CORRECTION_ENGINE) { if (type == EngineType.MATCH_ENGINE) { clearMatchPool = new JCheckBox("Clear match pool", ((MungeSettings) engineSettings).isClearMatchPool()); } else { clearMatchPool = new JCheckBox("Clear address pool", ((MungeSettings) engineSettings).isClearMatchPool()); } itemListener = new ItemListener() { public void itemStateChanged(ItemEvent e) { ((MungeSettings) engineSettings).setClearMatchPool(clearMatchPool.isSelected()); } }; clearMatchPool.addItemListener(itemListener); updaters.add(new CheckBoxModelUpdater(clearMatchPool, "clearMatchPool")); engineSettings.addSPListener(updaters.get(updaters.size() - 1)); if (debugMode.isSelected()) { clearMatchPool.setSelected(false); // See comment just above about why this is disabled clearMatchPool.setEnabled(false); } } if (engineSettings instanceof MungeSettings) { useBatchExecute = new JCheckBox("Batch execute SQL statments", ((MungeSettings) engineSettings).isUseBatchExecution()); itemListener = new ItemListener() { public void itemStateChanged(ItemEvent e) { ((MungeSettings) engineSettings).setUseBatchExecution(useBatchExecute.isSelected()); } }; useBatchExecute.addItemListener(itemListener); updaters.add(new CheckBoxModelUpdater(useBatchExecute, "useBatchExecution")); engineSettings.addSPListener(updaters.get(updaters.size() - 1)); } if (type == EngineType.ADDRESS_CORRECTION_ENGINE) { autoWriteAutoValidatedAddresses = new JCheckBox("Immediately commit auto-corrected addresses", ((MungeSettings) engineSettings).isAutoWriteAutoValidatedAddresses()); itemListener = new ItemListener() { public void itemStateChanged(ItemEvent e) { ((MungeSettings) engineSettings) .setAutoWriteAutoValidatedAddresses(autoWriteAutoValidatedAddresses.isSelected()); } }; autoWriteAutoValidatedAddresses.addItemListener(itemListener); updaters.add( new CheckBoxModelUpdater(autoWriteAutoValidatedAddresses, "autoWriteAutoValidatedAddresses")); engineSettings.addSPListener(updaters.get(updaters.size() - 1)); } messageLevel = new JComboBox(new Level[] { Level.OFF, Level.FATAL, Level.ERROR, Level.WARN, Level.INFO, Level.DEBUG, Level.ALL }); messageLevel.setSelectedItem(engine.getMessageLevel()); messageLevel.setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); setText(value == null ? null : value.toString()); return this; } }); messageLevelActionListener = new AbstractAction() { public void actionPerformed(ActionEvent e) { Level sel = (Level) messageLevel.getSelectedItem(); engine.setMessageLevel(sel); } }; messageLevel.addActionListener(messageLevelActionListener); String rowSpecs; if (type == EngineType.ADDRESS_CORRECTION_ENGINE) { rowSpecs = ADDRESS_CORRECTION_ENGINE_PANEL_ROW_SPECS; } else if (type == EngineType.VALIDATED_ADDRESS_COMMITING_ENGINE) { rowSpecs = ADDRESS_COMMITTING_ENGINE_PANEL_ROW_SPECS; } else if (type == EngineType.MERGE_ENGINE) { rowSpecs = MERGE_ENGINE_PANEL_ROW_SPECS; } else if (type == EngineType.CLEANSE_ENGINE) { rowSpecs = CLEANSE_ENGINE_PANEL_ROW_SPECS; } else { rowSpecs = MATCH_ENGINE_PANEL_ROW_SPECS; } String columnSpecs = "4dlu,fill:pref,4dlu,pref,pref,40dlu,fill:pref:grow,pref,4dlu"; FormLayout layout = new FormLayout(columnSpecs, rowSpecs); PanelBuilder pb; JPanel p = logger.isDebugEnabled() ? new FormDebugPanel(layout) : new JPanel(layout); pb = new PanelBuilder(layout, p); CellConstraints cc = new CellConstraints(); pb.add(status, cc.xyw(4, 2, 6, "l,c")); pb.add(refreshButton, cc.xy(6, 2, "l, c")); refreshButton.setVisible(false); int y = 4; pb.add(new JLabel("Log File:"), cc.xy(2, y, "r,f")); pb.add(logFilePath, cc.xyw(4, y, 4, "f,f")); pb.add(new JButton(browseLogFileAction), cc.xy(8, y, "l,f")); y += 2; pb.add(appendToLog, cc.xy(4, y, "l,t")); pb.add(new JButton(new ShowLogFileAction(logFilePath)), cc.xy(5, y, "r,t")); if (type == EngineType.MATCH_ENGINE || type == EngineType.CLEANSE_ENGINE) { y += 2; pb.add(new JLabel("Tranformations to run: "), cc.xy(2, y, "r,t")); final MungeProcessSelectionList selectionButton = new MungeProcessSelectionList(project) { @Override public boolean getValue(MungeProcess mp) { return mp.getActive(); } @Override public void setValue(MungeProcess mp, boolean value) { mp.setActive(value); } }; activeListener = new AbstractPoolingSPListener() { boolean isSelectionListUpdate = false; @Override protected void finalCommitImpl(TransactionEvent e) { if (isSelectionListUpdate) { selectionButton.checkModel(); } } @Override public void propertyChangeImpl(PropertyChangeEvent evt) { logger.debug("checking property with name " + evt.getPropertyName()); if (evt.getPropertyName().equals("active")) { isSelectionListUpdate = true; } else { isSelectionListUpdate = false; } } }; swingSession.getRootNode().addSPListener(activeListener); for (MungeProcess mp : project.getMungeProcesses()) { mp.addSPListener(activeListener); } newMungeProcessListener = new AbstractSPListener() { @Override public void childAdded(SPChildEvent e) { selectionButton.refreshList(); } @Override public void childRemoved(SPChildEvent e) { selectionButton.refreshList(); } }; project.addSPListener(newMungeProcessListener); pb.add(selectionButton, cc.xyw(4, y, 2, "l,c")); } y += 2; pb.add(new JLabel("# of records to process:"), cc.xy(2, y, "r,c")); pb.add(recordsToProcess, cc.xy(4, y, "l,c")); pb.add(new JLabel(" (Set to 0 to process all)"), cc.xy(5, y, "l, c")); if (type == EngineType.ADDRESS_CORRECTION_ENGINE) { pb.add(new JLabel("Address Filter Setting:"), cc.xy(7, y)); } if (engineSettings instanceof MungeSettings) { MungeSettings mungeSettings = (MungeSettings) engineSettings; y += 2; pb.add(useBatchExecute, cc.xyw(4, y, 2, "l,c")); if (type == EngineType.ADDRESS_CORRECTION_ENGINE) { final JLabel poolSettingLabel = new JLabel( mungeSettings.getPoolFilterSetting().getLongDescription()); SPListener poolFilterSettingChangeListener = new SPListener() { public void childAdded(SPChildEvent evt) { // no-op } public void childRemoved(SPChildEvent evt) { // no-op } public void propertyChanged(PropertyChangeEvent evt) { if (evt.getPropertyName() == "poolFilterSetting") { PoolFilterSetting newValue = (PoolFilterSetting) evt.getNewValue(); poolSettingLabel.setText(newValue.getLongDescription()); } } public void transactionStarted(TransactionEvent evt) { // no-op } public void transactionRollback(TransactionEvent evt) { // no-op } public void transactionEnded(TransactionEvent evt) { } }; mungeSettings.addSPListener(poolFilterSettingChangeListener); Font f = poolSettingLabel.getFont(); Font newFont = f.deriveFont(Font.ITALIC); poolSettingLabel.setFont(newFont); pb.add(poolSettingLabel, cc.xy(7, y)); } } if (type == EngineType.ADDRESS_CORRECTION_ENGINE) { y += 2; pb.add(autoWriteAutoValidatedAddresses, cc.xyw(4, y, 2, "l,c")); if (type == EngineType.ADDRESS_CORRECTION_ENGINE) { pb.add(new JLabel("Auto-correction Setting:"), cc.xy(7, y)); } } if (type == EngineType.MATCH_ENGINE || type == EngineType.ADDRESS_CORRECTION_ENGINE) { y += 2; pb.add(clearMatchPool, cc.xyw(4, y, 2, "l,c")); if (type == EngineType.ADDRESS_CORRECTION_ENGINE) { MungeSettings mungeSettings = (MungeSettings) engineSettings; final JLabel autoValidateSettingLabel = new JLabel( ((MungeSettings) engineSettings).getAutoValidateSetting().getLongDescription()); SPListener poolFilterSettingChangeListener = new SPListener() { public void childAdded(SPChildEvent evt) { // no-op } public void childRemoved(SPChildEvent evt) { // no-op } public void propertyChanged(PropertyChangeEvent evt) { if (evt.getPropertyName() == "autoValidateSetting") { AutoValidateSetting newValue = (AutoValidateSetting) evt.getNewValue(); autoValidateSettingLabel.setText(newValue.getLongDescription()); } } public void transactionStarted(TransactionEvent evt) { // no-op } public void transactionRollback(TransactionEvent evt) { // no-op } public void transactionEnded(TransactionEvent evt) { // no-op } }; mungeSettings.addSPListener(poolFilterSettingChangeListener); Font f = autoValidateSettingLabel.getFont(); Font newFont = f.deriveFont(Font.ITALIC); autoValidateSettingLabel.setFont(newFont); pb.add(autoValidateSettingLabel, cc.xy(7, y)); } } y += 2; pb.add(debugMode, cc.xyw(4, y, 2, "l,c")); if (type == EngineType.ADDRESS_CORRECTION_ENGINE) { final AddressValidationSettingsPanel avsp = new AddressValidationSettingsPanel( (MungeSettings) engineSettings); final JDialog validationSettingsDialog = DataEntryPanelBuilder.createDataEntryPanelDialog(avsp, swingSession.getFrame(), "Address Validation Settings", "OK", new Callable<Boolean>() { public Boolean call() throws Exception { boolean returnValue = avsp.applyChanges(); return returnValue; } }, new Callable<Boolean>() { public Boolean call() throws Exception { return true; } }); validationSettingsDialog.setLocationRelativeTo(pb.getPanel()); JButton addressValidationSettings = new JButton(new AbstractAction("Validation Settings...") { public void actionPerformed(ActionEvent e) { validationSettingsDialog.setVisible(true); } }); pb.add(addressValidationSettings, cc.xy(7, y, "l,c")); } y += 2; pb.add(new JLabel("Message Level:"), cc.xy(2, y, "r,t")); pb.add(messageLevel, cc.xy(4, y, "l,t")); abortButton = new JButton(new AbstractAction("Abort!") { public void actionPerformed(ActionEvent e) { engine.setCancelled(true); } }); abortButton.setEnabled(false); ButtonBarBuilder bbb = new ButtonBarBuilder(); bbb.addFixed(new JButton(new SaveAction())); bbb.addRelatedGap(); bbb.addFixed(new JButton(new ShowCommandAction(parentFrame, this, engine))); bbb.addRelatedGap(); bbb.addFixed(new JButton(runEngineAction)); bbb.addRelatedGap(); bbb.addFixed(abortButton); y += 2; pb.add(bbb.getPanel(), cc.xyw(2, y, 7, "r,c")); y += 2; pb.add(engineOutputPanel.getProgressBar(), cc.xyw(2, y, 7)); y += 2; pb.add(engineOutputPanel.getOutputComponent(), cc.xyw(2, y, 7)); y += 2; pb.add(engineOutputPanel.getButtonBar(), cc.xyw(2, y, 7)); refreshRunActionStatus(); return pb.getPanel(); }
From source file:ca.sqlpower.matchmaker.swingui.engine.ShowCommandAction.java
License:Open Source License
/** * Tells the editor to save its changes, then asks the engine for its command line. * Displays the resulting command line to the user in a pop-up dialog. *//*from www . ja v a2s . c o m*/ public void actionPerformed(ActionEvent e) { final String cmd = engine.createCommandLine(); final JDialog d = new JDialog(parent, "DQguru Engine Command Line"); FormLayout layout = new FormLayout("4dlu,fill:pref:grow,4dlu", // columns "4dlu,fill:pref:grow,4dlu,pref,4dlu"); // rows // 1 2 3 4 5 PanelBuilder pb; JPanel p = logger.isDebugEnabled() ? new FormDebugPanel(layout) : new JPanel(layout); pb = new PanelBuilder(layout, p); CellConstraints cc = new CellConstraints(); final JTextArea cmdText = new JTextArea(15, 60); cmdText.setText(cmd); cmdText.setEditable(false); cmdText.setWrapStyleWord(true); cmdText.setLineWrap(true); pb.add(new JScrollPane(cmdText), cc.xy(2, 2, "f,f")); ButtonBarBuilder bbBuilder = new ButtonBarBuilder(); Action saveAsAction = new AbstractAction("Save As...") { public void actionPerformed(ActionEvent e) { SPSUtils.saveDocument(d, cmdText.getDocument(), (FileExtensionFilter) SPSUtils.BATCH_FILE_FILTER); } }; JButton saveAsButton = new JButton(saveAsAction); bbBuilder.addGridded(saveAsButton); bbBuilder.addRelatedGap(); JButton copyButton = new JButton(new AbstractAction("Copy to Clipboard") { public void actionPerformed(ActionEvent e) { StringSelection selection = new StringSelection(cmdText.getText()); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(selection, selection); } }); bbBuilder.addGridded(copyButton); bbBuilder.addRelatedGap(); bbBuilder.addGlue(); JButton cancelButton = new JButton(new AbstractAction() { public void actionPerformed(ActionEvent e) { d.setVisible(false); } }); cancelButton.setText("Close"); bbBuilder.addGridded(cancelButton); pb.add(bbBuilder.getPanel(), cc.xy(2, 4)); d.add(pb.getPanel()); SPSUtils.makeJDialogCancellable(d, null); d.pack(); d.setLocationRelativeTo(parent); d.setVisible(true); }