List of usage examples for java.awt.event WindowAdapter WindowAdapter
WindowAdapter
From source file:de.codesourcery.eve.skills.ui.frames.WindowManager.java
/** * Registers an new window.// w w w . j av a 2 s . com * * @param key * @param frame */ public void registerWindow(final String key, final Window frame) { if (frame == null) { throw new IllegalArgumentException("frame cannot be NULL"); } if (StringUtils.isBlank(key)) { throw new IllegalArgumentException("key cannot be blank / NULL"); } synchronized (windows) { final Window oldFrame = windows.get(key); if (oldFrame != null) { log.warn("registerWindow(): REPLACING existing window with key '" + key + "'"); unregisterWindow(key, oldFrame); } log.debug("registerWindow(): Registering window with key = " + key); windows.put(key, frame); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { unregisterWindow(key, frame); } }); if (frame instanceof IWindowManagerAware) { ((IWindowManagerAware) frame).windowManaged(); } } }
From source file:com.sshtools.sshvnc.SshVncFullScreenWindowContainer.java
public void init(final SshToolsApplication application, SshToolsApplicationPanel panel) throws SshToolsApplicationException { getContentPane().invalidate();//ww w . j a v a 2s .c om //setUndecorated(true); this.panel = panel; this.application = application; setJMenuBar(((SshVNCPanel) panel).getJMenuBar()); // We dont want the status bar, menu bar or tool bar showing in full screen mode by default ((SshVNCPanel) panel).setToolsVisible(false); panel.registerActionMenu(new SshToolsApplicationPanel.ActionMenu("File", "File", 'f', 0)); panel.registerAction(exitAction = new ExitAction(application, this)); panel.registerAction(newWindowAction = new NewWindowAction(application)); panel.registerAction(aboutAction = new AboutAction(this, application)); panel.registerAction(changelogAction = new ChangelogAction(this, application)); panel.registerAction(faqAction = new FAQAction()); panel.registerAction(beginnerAction = new BeginnerAction()); panel.registerAction(advancedAction = new AdvancedAction()); panel.registerAction(fullScreenAction = new FullScreenActionImpl(application, this)); getApplicationPanel().rebuildActionComponents(); JPanel p = new JPanel(new BorderLayout()); if (panel.getToolBar() != null) { JPanel t = new JPanel(new BorderLayout()); t.add(panel.getToolBar(), BorderLayout.NORTH); t.add(toolSeperator = new JSeparator(JSeparator.HORIZONTAL), BorderLayout.SOUTH); final SshToolsApplicationPanel pnl = panel; panel.getToolBar().addComponentListener(new ComponentAdapter() { public void componentHidden(ComponentEvent evt) { log.debug("Tool separator is now " + pnl.getToolBar().isVisible()); toolSeperator.setVisible(pnl.getToolBar().isVisible()); } }); p.add(t, BorderLayout.NORTH); } p.add(panel, BorderLayout.CENTER); if (panel.getStatusBar() != null) { p.add(panel.getStatusBar(), BorderLayout.SOUTH); } getContentPane().setLayout(new GridLayout(1, 1)); getContentPane().add(p); // Watch for the frame closing addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { application.closeContainer(SshVncFullScreenWindowContainer.this); } }); getContentPane().validate(); }
From source file:jatoo.app.App.java
public App(final String title) { this.title = title; ///*from www . j a v a 2s .co m*/ // load properties properties = new AppProperties(new File(getWorkingDirectory(), "app.properties")); properties.loadSilently(); // // resources texts = new ResourcesTexts(getClass(), new ResourcesTexts(App.class)); images = new ResourcesImages(getClass(), new ResourcesImages(App.class)); // // create & initialize the window if (isDialog()) { window = new JDialog((Frame) null, getTitle()); if (isUndecorated()) { ((JDialog) window).setUndecorated(true); ((JDialog) window).setBackground(new Color(0, 0, 0, 0)); } ((JDialog) window).setResizable(isResizable()); } else { window = new JFrame(getTitle()); if (isUndecorated()) { ((JFrame) window).setUndecorated(true); ((JFrame) window).setBackground(new Color(0, 0, 0, 0)); } ((JFrame) window).setResizable(isResizable()); } window.addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { System.exit(0); } @Override public void windowIconified(final WindowEvent e) { if (isHideWhenMinimized()) { hide(); } } }); // // set icon images // is either all icons from initializer package // or all icons from app package List<Image> windowIconImages = new ArrayList<>(); String[] windowIconImagesNames = new String[] { "016", "020", "022", "024", "032", "048", "064", "128", "256", "512" }; for (String size : windowIconImagesNames) { try { windowIconImages.add(new ImageIcon(getClass().getResource("app-icon-" + size + ".png")).getImage()); } catch (Exception e) { } } if (windowIconImages.size() == 0) { for (String size : windowIconImagesNames) { try { windowIconImages .add(new ImageIcon(App.class.getResource("app-icon-" + size + ".png")).getImage()); } catch (Exception e) { } } } window.setIconImages(windowIconImages); // // this is the place for to call init method // after all local components are created // from now (after init) is only configuration init(); // // set content pane ( and ansure transparency ) JComponent contentPane = getContentPane(); contentPane.setOpaque(false); ((RootPaneContainer) window).setContentPane(contentPane); // // pack the window right after the set of the content pane window.pack(); // // center window (as default in case restore fails) // and try to restore the last location window.setLocationRelativeTo(null); window.setLocation(properties.getLocation(window.getLocation())); if (!isUndecorated()) { if (properties.getLastUndecorated(isUndecorated()) == isUndecorated()) { if (isResizable() && isSizePersistent()) { final String currentLookAndFeel = String.valueOf(UIManager.getLookAndFeel()); if (properties.getLastLookAndFeel(currentLookAndFeel).equals(currentLookAndFeel)) { window.setSize(properties.getSize(window.getSize())); } } } } // // fix location if out of screen Rectangle intersection = window.getGraphicsConfiguration().getBounds().intersection(window.getBounds()); if ((intersection.width < window.getWidth() * 1 / 2) || (intersection.height < window.getHeight() * 1 / 2)) { UIUtils.setWindowLocationRelativeToScreen(window); } // // restore some properties setAlwaysOnTop(properties.isAlwaysOnTop()); setHideWhenMinimized(properties.isHideWhenMinimized()); setTransparency(properties.getTransparency(transparency)); // // null is also a good value for margins glue gaps (is [0,0,0,0]) Insets marginsGlueGaps = getMarginsGlueGaps(); if (marginsGlueGaps == null) { marginsGlueGaps = new Insets(0, 0, 0, 0); } // // glue to margins on Ctrl + ARROWS if (isGlueToMarginsOnCtrlArrows()) { UIUtils.setActionForCtrlDownKeyStroke(((RootPaneContainer) window).getRootPane(), new ActionGlueMarginBottom(window, marginsGlueGaps.bottom)); UIUtils.setActionForCtrlLeftKeyStroke(((RootPaneContainer) window).getRootPane(), new ActionGlueMarginLeft(window, marginsGlueGaps.left)); UIUtils.setActionForCtrlRightKeyStroke(((RootPaneContainer) window).getRootPane(), new ActionGlueMarginRight(window, marginsGlueGaps.right)); UIUtils.setActionForCtrlUpKeyStroke(((RootPaneContainer) window).getRootPane(), new ActionGlueMarginTop(window, marginsGlueGaps.top)); } // // drag to move ( when provided component is not null ) JComponent dragToMoveComponent = getDragToMoveComponent(); if (dragToMoveComponent != null) { // // move the window by dragging the UI component int marginsGlueRange = Math.min(window.getGraphicsConfiguration().getBounds().width, window.getGraphicsConfiguration().getBounds().height); marginsGlueRange /= 60; marginsGlueRange = Math.max(marginsGlueRange, 15); UIUtils.forwardDragAsMove(dragToMoveComponent, window, marginsGlueRange, marginsGlueGaps); // // window popup dragToMoveComponent.addMouseListener(new MouseAdapter() { public void mouseReleased(final MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { windowPopup = getWindowPopup(e.getLocationOnScreen()); windowPopup.setVisible(true); } } }); // // always dispose the popup when window lose the focus window.addFocusListener(new FocusAdapter() { public void focusLost(final FocusEvent e) { if (windowPopup != null) { windowPopup.setVisible(false); windowPopup = null; } } }); } // // tray icon if (hasTrayIcon()) { if (SystemTray.isSupported()) { Image trayIconImage = windowIconImages.get(0); Dimension trayIconSize = SystemTray.getSystemTray().getTrayIconSize(); for (Image windowIconImage : windowIconImages) { if (Math.abs(trayIconSize.width - windowIconImage.getWidth(null)) < Math .abs(trayIconImage.getWidth(null) - windowIconImage.getWidth(null))) { trayIconImage = windowIconImage; } } final TrayIcon trayIcon = new TrayIcon(trayIconImage); trayIcon.setPopupMenu(getTrayIconPopup()); trayIcon.addMouseListener(new MouseAdapter() { public void mouseClicked(final MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { if (e.getClickCount() >= 2) { if (window.isVisible()) { hide(); } else { show(); } } } } }); try { SystemTray.getSystemTray().add(trayIcon); } catch (AWTException e) { logger.error( "unexpected exception trying to add the tray icon ( the desktop system tray is missing? )", e); } } else { logger.error("the system tray is not supported on the current platform"); } } // // hidden or not if (properties.isVisible()) { window.setVisible(true); } // // close the splash screen // if there is one try { SplashScreen splash = SplashScreen.getSplashScreen(); if (splash != null) { splash.close(); } } catch (UnsupportedOperationException e) { getLogger().info("splash screen not supported", e); } // // add shutdown hook for #destroy() Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { App.this.destroy(); } }); // // after init afterInit(); }
From source file:me.philnate.textmanager.windows.MainWindow.java
/** * Initialize the contents of the frame. *//*from w ww . j a va 2 s .co m*/ private void initialize() { changeListener = new ChangeListener(); frame = new JFrame(); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { Starter.shutdown(); } }); frame.setBounds(100, 100, 1197, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new MigLayout("", "[grow]", "[][grow][::16px]")); customers = new CustomerComboBox(); customers.addItemListener(changeListener); frame.getContentPane().add(customers, "flowx,cell 0 0,growx"); jScrollPane = new JScrollPane(); billLines = new BillingItemTable(frame, true); jScrollPane.setViewportView(billLines); frame.getContentPane().add(jScrollPane, "cell 0 1,grow"); // for each file added through drag&drop create a new lineItem new FileDrop(jScrollPane, new FileDrop.Listener() { @Override public void filesDropped(File[] files) { for (File file : files) { addNewBillingItem(Document.loadAndSave(file)); } } }); monthChooser = new JMonthChooser(); monthChooser.addPropertyChangeListener(changeListener); frame.getContentPane().add(monthChooser, "cell 0 0"); yearChooser = new JYearChooser(); yearChooser.addPropertyChangeListener(changeListener); frame.getContentPane().add(yearChooser, "cell 0 0"); JButton btnAddLine = new JButton(); btnAddLine.setIcon(ImageRegistry.getImage("load.gif")); btnAddLine.setToolTipText(getCaption("mw.tooltip.add")); btnAddLine.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { addNewBillingItem(); } }); frame.getContentPane().add(btnAddLine, "cell 0 0"); JButton btnMassAdd = new JButton(); btnMassAdd.setIcon(ImageRegistry.getImage("load_all.gif")); btnMassAdd.setToolTipText(getCaption("mw.tooltip.massAdd")); btnMassAdd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { JFileChooser file = new DocXFileChooser(); switch (file.showOpenDialog(frame)) { case JFileChooser.APPROVE_OPTION: File[] files = file.getSelectedFiles(); if (null != files) { for (File fl : files) { addNewBillingItem(Document.loadAndSave(fl)); } } break; default: return; } } }); frame.getContentPane().add(btnMassAdd, "cell 0 0"); billNo = new JTextField(); // enable/disable build button based upon text in billNo billNo.getDocument().addDocumentListener(new DocumentListener() { @Override public void removeUpdate(DocumentEvent arg0) { setButtonStates(); } @Override public void insertUpdate(DocumentEvent arg0) { setButtonStates(); } @Override public void changedUpdate(DocumentEvent arg0) { setButtonStates(); } private void setButtonStates() { boolean notBlank = StringUtils.isNotBlank(billNo.getText()); build.setEnabled(notBlank); view.setEnabled(pdf.find(billNo.getText() + ".pdf").size() == 1); } }); frame.getContentPane().add(billNo, "cell 0 0"); billNo.setColumns(10); build = new JButton(); build.setEnabled(false);// disable build Button until there's some // billNo entered build.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (runningThread == null) { try { // check that billNo isn't empty or already used within // another Bill if (billNo.getText().trim().equals("")) { JOptionPane.showMessageDialog(frame, getCaption("mw.dialog.error.billNoBlank.msg"), getCaption("mw.dialog.error.billNoBlank.title"), JOptionPane.ERROR_MESSAGE); return; } try { bill.setBillNo(billNo.getText()).save(); } catch (DuplicateKey e) { // unset the internal value as this is already used bill.setBillNo(""); JOptionPane.showMessageDialog(frame, format(getCaption("mw.error.billNoUsed.msg"), billNo.getText()), getCaption("mw.dialog.error.billNoBlank.title"), JOptionPane.ERROR_MESSAGE); return; } PDFCreator pdf = new PDFCreator(bill); pdf.addListener(new ThreadCompleteListener() { @Override public void threadCompleted(NotifyingThread notifyingThread) { build.setToolTipText(getCaption("mw.tooltip.build")); build.setIcon(ImageRegistry.getImage("build.png")); runningThread = null; view.setEnabled(DB.pdf.find(billNo.getText() + ".pdf").size() == 1); } }); runningThread = new Thread(pdf); runningThread.start(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } build.setToolTipText(getCaption("mw.tooltip.build.cancel")); build.setIcon(ImageRegistry.getImage("cancel.gif")); } else { runningThread.interrupt(); runningThread = null; build.setToolTipText(getCaption("mw.tooltip.build")); build.setIcon(ImageRegistry.getImage("build.png")); } } }); build.setToolTipText(getCaption("mw.tooltip.build")); build.setIcon(ImageRegistry.getImage("build.png")); frame.getContentPane().add(build, "cell 0 0"); view = new JButton(); view.setToolTipText(getCaption("mw.tooltip.view")); view.setIcon(ImageRegistry.getImage("view.gif")); view.setEnabled(false); view.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { File file = new File(System.getProperty("user.dir"), format("template/%s.tmp.pdf", billNo.getText())); try { pdf.findOne(billNo.getText() + ".pdf").writeTo(file); new ProcessBuilder(Setting.find("pdfViewer").getValue(), file.getAbsolutePath()).start() .waitFor(); file.delete(); } catch (IOException | InterruptedException e1) { // TODO Auto-generated catch block LOG.warn("Error while building PDF", e1); } } }); frame.getContentPane().add(view, "cell 0 0"); statusBar = new JPanel(); statusBar.setBorder(new BevelBorder(BevelBorder.LOWERED)); statusBar.setLayout(new BoxLayout(statusBar, BoxLayout.X_AXIS)); GitRepositoryState state = DB.state; JLabel statusLabel = new JLabel(String.format("textManager Version v%s build %s", state.getCommitIdDescribe(), state.getBuildTime())); statusLabel.setHorizontalAlignment(SwingConstants.LEFT); statusBar.add(statusLabel); frame.add(statusBar, "cell 0 2,growx"); JMenuBar menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); JMenu menu = new JMenu(getCaption("mw.menu.edit")); JMenuItem itemCust = new JMenuItem(getCaption("mw.menu.edit.customer")); itemCust.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { new CustomerWindow(customers); } }); menu.add(itemCust); JMenuItem itemSetting = new JMenuItem(getCaption("mw.menu.edit.settings")); itemSetting.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { new SettingWindow(); } }); menu.add(itemSetting); JMenuItem itemImport = new JMenuItem(getCaption("mw.menu.edit.import")); itemImport.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { new ImportWindow(new ImportListener() { @Override public void entriesImported(List<BillingItem> items) { for (BillingItem item : items) { item.setCustomerId(customers.getSelectedCustomer().getId()) .setMonth(monthChooser.getMonth()).setYear(yearChooser.getYear()); item.save(); billLines.addRow(item); } } }, frame); } }); menu.add(itemImport); menuBar.add(menu); customers.loadCustomer(); fillTableModel(); }
From source file:com.sshtools.shift.FileTransferDialog.java
/** * Creates a new FileTransferDialog object. * * @param frame/*w ww. j a v a 2 s.c o m*/ * @param title * @param fileCount */ /*public FileTransferDialog(Frame frame, String title) { this(frame, title, op.getNewFiles().size() + op.getUpdatedFiles().size()); this.op = op; }*/ public FileTransferDialog(Frame frame, String title, int fileCount) { super("0% Complete - " + title); this.setIconImage(ShiftSessionPanel.FILE_BROWSER_ICON.getImage()); this.title = title; try { jbInit(); pack(); } catch (Exception ex) { ex.printStackTrace(); } this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { if (cancelled || completed) { setVisible(false); } else { if (JOptionPane.showConfirmDialog(FileTransferDialog.this, "Cancel the file operation(s)?", "Close Window", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE) == JOptionPane.YES_OPTION) { cancelOperation(); hide(); } } } }); }
From source file:EditorPaneExample11.java
public static void main(String[] args) { try {//from w w w. jav a2 s . c o m UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception evt) { } JFrame f = new EditorPaneExample11(); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { System.exit(0); } }); f.setSize(500, 400); f.setVisible(true); }
From source file:de.tor.tribes.ui.wiz.dep.DefensePlanerWizard.java
public static void show() { if (parent != null) { parent.toFront();/* ww w . jav a 2 s .co m*/ return; } parent = new JFrame(); parent.setTitle("Verteidigungsplaner"); WizardPanelProvider provider = new DefensePlanerWizard(); Wizard wizard = provider.createWizard(); parent.getContentPane().setLayout(new BorderLayout()); WizardDisplayer.installInContainer(parent, BorderLayout.CENTER, wizard, null, null, new WizardResultReceiver() { @Override public void finished(Object o) { parent.dispose(); parent = null; } @Override public void cancelled(Map map) { parent.dispose(); parent = null; } }); parent.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); parent.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); parent = null; } }); parent.pack(); parent.setVisible(true); new SOSGenerator().setVisible(true); }
From source file:edu.clemson.cs.nestbed.client.gui.TestbedManagerFrame.java
public TestbedManagerFrame() throws RemoteException, NotBoundException, MalformedURLException { super(WINDOW_TITLE); lookupRemoteManagers();// w w w . j av a 2 s.co m // TODO: testbedManager.addRemoteObserver(new TestbedObserver()); projectManager.addRemoteObserver(new ProjectObserver()); configManager.addRemoteObserver(new ProjectDeploymentConfigObserver()); createComponents(); setSize(WINDOW_WIDTH, WINDOW_HEIGHT); setJMenuBar(buildMenuBar()); Container c = getContentPane(); c.setLayout(new BorderLayout()); c.add(buildListPanel(), BorderLayout.CENTER); this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { doExit(); } }); }
From source file:es.emergya.ui.plugins.admin.aux1.RecursoDialog.java
public RecursoDialog(final Recurso rec, final AdminResources adminResources) { super();//from w ww. j ava 2 s.co m setAlwaysOnTop(true); setSize(600, 400); setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); if (cambios) { int res = JOptionPane.showConfirmDialog(RecursoDialog.this, "Existen cambios sin guardar. Seguro que desea cerrar la ventana?", "Cambios sin guardar", JOptionPane.OK_CANCEL_OPTION); if (res != JOptionPane.CANCEL_OPTION) { e.getWindow().dispose(); } } else { e.getWindow().dispose(); } } }); final Recurso r = (rec == null) ? null : RecursoConsultas.get(rec.getId()); if (r != null) { setTitle(i18n.getString("Resources.summary.titleWindow") + " " + r.getIdentificador()); } else { setTitle(i18n.getString("Resources.summary.titleWindow.new")); } setIconImage(getBasicWindow().getFrame().getIconImage()); JPanel base = new JPanel(); base.setBackground(Color.WHITE); base.setLayout(new BoxLayout(base, BoxLayout.Y_AXIS)); // Icono del titulo JPanel title = new JPanel(new FlowLayout(FlowLayout.LEADING)); title.setOpaque(false); JLabel labelTitulo = null; if (r != null) { labelTitulo = new JLabel(i18n.getString("Resources.summary"), LogicConstants.getIcon("tittleficha_icon_recurso"), JLabel.LEFT); } else { labelTitulo = new JLabel(i18n.getString("Resources.cabecera.nuevo"), LogicConstants.getIcon("tittleficha_icon_recurso"), JLabel.LEFT); } labelTitulo.setFont(LogicConstants.deriveBoldFont(12f)); title.add(labelTitulo); base.add(title); // Nombre JPanel mid = new JPanel(new SpringLayout()); mid.setOpaque(false); mid.add(new JLabel(i18n.getString("Resources.name"), JLabel.RIGHT)); final JTextField name = new JTextField(25); if (r != null) { name.setText(r.getNombre()); } name.getDocument().addDocumentListener(changeListener); name.setEditable(r == null); mid.add(name); // patrullas final JLabel labelSquads = new JLabel(i18n.getString("Resources.squad"), JLabel.RIGHT); mid.add(labelSquads); List<Patrulla> pl = PatrullaConsultas.getAll(); pl.add(0, null); final JComboBox squads = new JComboBox(pl.toArray()); squads.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXXXXXXX"); squads.addActionListener(changeSelectionListener); squads.setOpaque(false); labelSquads.setLabelFor(squads); if (r != null) { squads.setSelectedItem(r.getPatrullas()); } else { squads.setSelectedItem(null); } squads.setEnabled((r != null && r.getHabilitado() != null) ? r.getHabilitado() : true); mid.add(squads); // // Identificador // mid.setOpaque(false); // mid.add(new JLabel(i18n.getString("Resources.identificador"), // JLabel.RIGHT)); // final JTextField identificador = new JTextField(""); // if (r != null) { // identificador.setText(r.getIdentificador()); // } // identificador.getDocument().addDocumentListener(changeListener); // identificador.setEditable(r == null); // mid.add(identificador); // Espacio en blanco // mid.add(Box.createHorizontalGlue()); // mid.add(Box.createHorizontalGlue()); // Tipo final JLabel labelTipoRecursos = new JLabel(i18n.getString("Resources.type"), JLabel.RIGHT); mid.add(labelTipoRecursos); final JComboBox types = new JComboBox(RecursoConsultas.getTipos()); labelTipoRecursos.setLabelFor(types); types.addActionListener(changeSelectionListener); if (r != null) { types.setSelectedItem(r.getTipo()); } else { types.setSelectedItem(0); } // types.setEditable(true); types.setEnabled(true); mid.add(types); // Estado Eurocop mid.add(new JLabel(i18n.getString("Resources.status"), JLabel.RIGHT)); final JTextField status = new JTextField(); if (r != null && r.getEstadoEurocop() != null) { status.setText(r.getEstadoEurocop().getIdentificador()); } status.setEditable(false); mid.add(status); // Subflota y patrulla mid.add(new JLabel(i18n.getString("Resources.subfleet"), JLabel.RIGHT)); final JComboBox subfleets = new JComboBox(FlotaConsultas.getAllHabilitadas()); subfleets.addActionListener(changeSelectionListener); if (r != null) { subfleets.setSelectedItem(r.getFlotas()); } else { subfleets.setSelectedIndex(0); } subfleets.setEnabled(true); subfleets.setOpaque(false); mid.add(subfleets); // Referencia humana mid.add(new JLabel(i18n.getString("Resources.incidences"), JLabel.RIGHT)); final JTextField rhumana = new JTextField(); // if (r != null && r.getIncidencias() != null) { // rhumana.setText(r.getIncidencias().getReferenciaHumana()); // } rhumana.setEditable(false); mid.add(rhumana); // dispositivo mid.add(new JLabel(i18n.getString("Resources.device"), JLabel.RIGHT)); final PlainDocument plainDocument = new PlainDocument() { private static final long serialVersionUID = 4929271093724956016L; @Override public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { if (this.getLength() + str.length() <= LogicConstants.LONGITUD_ISSI) { super.insertString(offs, str, a); } } }; final JTextField issi = new JTextField(plainDocument, "", LogicConstants.LONGITUD_ISSI); plainDocument.addDocumentListener(changeListener); issi.setEditable(true); mid.add(issi); mid.add(new JLabel(i18n.getString("Resources.enabled"), JLabel.RIGHT)); final JCheckBox enabled = new JCheckBox("", true); enabled.addActionListener(changeSelectionListener); enabled.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (enabled.isSelected()) { squads.setSelectedIndex(0); } squads.setEnabled(enabled.isSelected()); } }); enabled.setEnabled(true); enabled.setOpaque(false); if (r != null) { enabled.setSelected(r.getHabilitado()); } else { enabled.setSelected(true); } if (r != null && r.getDispositivo() != null) { issi.setText( StringUtils.leftPad(String.valueOf(r.getDispositivo()), LogicConstants.LONGITUD_ISSI, '0')); } mid.add(enabled); // Fecha ultimo gps mid.add(new JLabel(i18n.getString("Resources.lastPosition"), JLabel.RIGHT)); JTextField lastGPS = new JTextField(); final Date lastGPSDateForRecurso = HistoricoGPSConsultas.lastGPSDateForRecurso(r); if (lastGPSDateForRecurso != null) { lastGPS.setText(SimpleDateFormat.getDateTimeInstance().format(lastGPSDateForRecurso)); } lastGPS.setEditable(false); mid.add(lastGPS); // Espacio en blanco mid.add(Box.createHorizontalGlue()); mid.add(Box.createHorizontalGlue()); // informacion adicional JPanel infoPanel = new JPanel(new SpringLayout()); final JTextField info = new JTextField(25); info.getDocument().addDocumentListener(changeListener); infoPanel.add(new JLabel(i18n.getString("Resources.info"))); infoPanel.add(info); infoPanel.setOpaque(false); info.setOpaque(false); SpringUtilities.makeCompactGrid(infoPanel, 1, 2, 6, 6, 6, 18); if (r != null) { info.setText(r.getInfoAdicional()); } else { info.setText(""); } info.setEditable(true); // Espacio en blanco mid.add(Box.createHorizontalGlue()); mid.add(Box.createHorizontalGlue()); SpringUtilities.makeCompactGrid(mid, 5, 4, 6, 6, 6, 18); base.add(mid); base.add(infoPanel); JPanel buttons = new JPanel(); buttons.setOpaque(false); JButton accept = null; if (r == null) { accept = new JButton("Crear", LogicConstants.getIcon("button_crear")); } else { accept = new JButton("Guardar", LogicConstants.getIcon("button_save")); } accept.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { if (cambios || r == null || r.getId() == null) { boolean shithappens = true; if ((r == null || r.getId() == null)) { // Estamos // creando // uno nuevo if (RecursoConsultas.alreadyExists(name.getText())) { shithappens = false; JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString("admin.recursos.popup.error.nombreUnico")); } else if (issi.getText() != null && issi.getText().length() > 0 && StringUtils .trimToEmpty(issi.getText()).length() != LogicConstants.LONGITUD_ISSI) { JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString(Locale.ROOT, "admin.recursos.popup.error.faltanCifras", LogicConstants.LONGITUD_ISSI)); shithappens = false; } else if (issi.getText() != null && issi.getText().length() > 0 && LogicConstants.isNumeric(issi.getText()) && RecursoConsultas.alreadyExists(new Integer(issi.getText()))) { shithappens = false; JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString("admin.recursos.popup.error.dispositivoUnico")); } } if (shithappens) { if (name.getText().isEmpty()) { JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString("admin.recursos.popup.error.nombreNulo")); } else if (issi.getText() != null && issi.getText().length() > 0 && StringUtils .trimToEmpty(issi.getText()).length() != LogicConstants.LONGITUD_ISSI) { JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString(Locale.ROOT, "admin.recursos.popup.error.faltanCifras", LogicConstants.LONGITUD_ISSI)); } else if (issi.getText() != null && issi.getText().length() > 0 && LogicConstants.isNumeric(issi.getText()) && r != null && r.getId() != null && RecursoConsultas.alreadyExists(new Integer(issi.getText()), r.getId())) { JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString("admin.recursos.popup.error.issiUnico")); } else if (issi.getText() != null && issi.getText().length() > 0 && !LogicConstants.isNumeric(issi.getText())) { JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString("admin.recursos.popup.error.noNumerico")); // } else if (identificador.getText().isEmpty()) // { // JOptionPane // .showMessageDialog( // RecursoDialog.this, // i18n.getString("admin.recursos.popup.error.identificadorNulo")); } else if (subfleets.getSelectedIndex() == -1) { JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString("admin.recursos.popup.error.noSubflota")); } else if (types.getSelectedItem() == null || types.getSelectedItem().toString().trim().isEmpty()) { JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString("admin.recursos.popup.error.noTipo")); } else { int i = JOptionPane.showConfirmDialog(RecursoDialog.this, i18n.getString("admin.recursos.popup.dialogo.guardar.titulo"), i18n.getString("admin.recursos.popup.dialogo.guardar.guardar"), JOptionPane.YES_NO_CANCEL_OPTION); if (i == JOptionPane.YES_OPTION) { Recurso recurso = r; if (r == null) { recurso = new Recurso(); } recurso.setInfoAdicional(info.getText()); if (issi.getText() != null && issi.getText().length() > 0) { recurso.setDispositivo(new Integer(issi.getText())); } else { recurso.setDispositivo(null); } recurso.setFlotas(FlotaConsultas.find(subfleets.getSelectedItem().toString())); if (squads.getSelectedItem() != null && enabled.isSelected()) { recurso.setPatrullas( PatrullaConsultas.find(squads.getSelectedItem().toString())); } else { recurso.setPatrullas(null); } recurso.setNombre(name.getText()); recurso.setHabilitado(enabled.isSelected()); // recurso.setIdentificador(identificador // .getText()); recurso.setTipo(types.getSelectedItem().toString()); dispose(); RecursoAdmin.saveOrUpdate(recurso); adminResources.refresh(null); PluginEventHandler.fireChange(adminResources); } else if (i == JOptionPane.NO_OPTION) { dispose(); } } } } else { log.debug("No hay cambios"); dispose(); } } catch (Throwable t) { log.error("Error guardando un recurso", t); } } }); buttons.add(accept); JButton cancelar = new JButton("Cancelar", LogicConstants.getIcon("button_cancel")); cancelar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (cambios) { if (JOptionPane.showConfirmDialog(RecursoDialog.this, "Existen cambios sin guardar. Seguro que desea cerrar la ventana?", "Cambios sin guardar", JOptionPane.OK_CANCEL_OPTION) != JOptionPane.CANCEL_OPTION) { dispose(); } } else { dispose(); } } }); buttons.add(cancelar); base.add(buttons); getContentPane().add(base); setLocationRelativeTo(null); cambios = false; if (r == null) { cambios = true; } pack(); int x; int y; Container myParent = getBasicWindow().getPluginContainer().getDetachedTab(0); Point topLeft = myParent.getLocationOnScreen(); Dimension parentSize = myParent.getSize(); Dimension mySize = getSize(); if (parentSize.width > mySize.width) { x = ((parentSize.width - mySize.width) / 2) + topLeft.x; } else { x = topLeft.x; } if (parentSize.height > mySize.height) { y = ((parentSize.height - mySize.height) / 2) + topLeft.y; } else { y = topLeft.y; } setLocation(x, y); cambios = false; }
From source file:gov.nij.er.ui.EntityResolutionDemo.java
private EntityResolutionDemo(boolean test) { addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent arg0) { exit();/*from w w w .j a v a 2s . co m*/ } }); setTitle("Entity Resolution Demo"); setJMenuBar(buildMenuBar()); createUIWidgets(); layoutUI(); setupWidgetModels(); setupWidgetListeners(); parametersTable.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(algorithmComboBox)); if (test) { loadTestRecords(); } updateUIForParameterChange(); setSize(800, 600); setVisible(true); }