Example usage for java.beans PropertyChangeListener PropertyChangeListener

List of usage examples for java.beans PropertyChangeListener PropertyChangeListener

Introduction

In this page you can find the example usage for java.beans PropertyChangeListener PropertyChangeListener.

Prototype

PropertyChangeListener

Source Link

Usage

From source file:edu.ku.brc.af.ui.forms.IconViewObj.java

/**
 * /*from w  w  w.j ava 2s. c o m*/
 */
protected void initMainComp() {
    if (isEditing) {
        String delTTStr = ResultSetController.createTooltip("DeleteRecordTT", view.getObjTitle());
        String edtTTStr = ResultSetController.createTooltip("EditRecordTT", view.getObjTitle());
        String newTTStr = ResultSetController.createTooltip("NewRecordTT", view.getObjTitle());

        editBtn = UIHelper.createIconBtnTT("EditForm", IconManager.IconSize.Std16, edtTTStr, false, null);
        newBtn = UIHelper.createIconBtnTT("CreateObj", IconManager.IconSize.Std16, newTTStr, false, null);
        delBtn = UIHelper.createIconBtnTT("DeleteRecord", IconManager.IconSize.Std16, delTTStr, false, null);

        validationInfoBtn = FormViewObj.createValidationIndicator(mainComp, getValidator());

        editBtn.setEnabled(false);
        delBtn.setEnabled(false);
        newBtn.setEnabled(true);

    } else {
        String srchTTStr = ResultSetController.createTooltip("ShowRecordInfoTT", view.getObjTitle());
        viewBtn = UIHelper.createIconBtnTT("InfoIcon", IconManager.IconSize.Std16, srchTTStr, false, null);
        viewBtn.setEnabled(false);
    }

    altViewsList = new Vector<AltViewIFace>();
    switcherUI = FormViewObj.createMenuSwitcherPanel(mvParent, view, altView, altViewsList, mainComp, cellName,
            dataClass);

    Dimension maxSize = Thumbnailer.getInstance().getMaxSize();
    iconTray = new OrderedIconTray(IconTray.SINGLE_ROW, maxSize.width, maxSize.height);
    iconTray.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getPropertyName().equalsIgnoreCase("item order")) {
                rootHasChanged();
            }
        }
    });

    iconTray.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 1) {
                updateEnableUI();

            } else if (e.getClickCount() > 1) {
                doDoubleClick();
            }
        }

        @Override
        public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
                showContextMenu(e);
            }
        }

    });

    iconTray.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                updateEnableUI();
            }
        }
    });

    if (isEditing) {
        addActionListenerToEditButton();
        addActionListenerToNewButton();
        addActionListenerToDeleteButton();

        IconViewTransferHandler ivth = new IconViewTransferHandler(this);
        iconTray.setTransferHandler(ivth);

    } else {
        addActionListenerToViewButton();
    }

    mainComp = new RestrictablePanel();
    mainComp.setLayout(new BorderLayout());
    if (mvParent == null) {
        mainComp.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
    }

    boolean isAbove = mvParent.getSeparator() != null;

    int defCnt = (isEditing ? 3 : 1) + (switcherUI != null ? 1 : 0) + (validationInfoBtn != null ? 1 : 0);
    String colDef = (isAbove ? "1px," : "f:1px:g,") + UIHelper.createDuplicateJGoodiesDef("p", "1px", defCnt);
    PanelBuilder builder = new PanelBuilder(new FormLayout(colDef, "p"));
    CellConstraints cc = new CellConstraints();

    int x = 2;
    if (isEditing) {
        builder.add(editBtn, cc.xy(x, 1));
        x += 2;
        builder.add(newBtn, cc.xy(x, 1));
        x += 2;
        builder.add(delBtn, cc.xy(x, 1));
        x += 2;

        if (validationInfoBtn != null) // is null when genrating form images
        {
            builder.add(validationInfoBtn, cc.xy(x, 1));
            x += 2;
        }

    } else {
        builder.add(viewBtn, cc.xy(x, 1));
        x += 2;
    }

    if (switcherUI != null) {
        builder.add(switcherUI, cc.xy(x, 1));
        x += 2;
    }

    if (isAbove) {
        sepController = builder.getPanel();
    } else {
        southPanel = builder.getPanel();
        mainComp.add(southPanel, BorderLayout.SOUTH);
    }

    mainComp.add(iconTray, BorderLayout.CENTER);

}

From source file:EditorPaneExample20.java

public EditorPaneExample20() {
    super("JEditorPane Example 20");

    pane = new JEditorPane();
    pane.setEditable(true); // Editable
    getContentPane().add(new JScrollPane(pane), "Center");

    // Add a menu bar
    menuBar = new JMenuBar();
    setJMenuBar(menuBar);//from  www. ja va2  s. c o  m

    // Populate it
    createMenuBar();

    // Build the panel of controls
    JPanel panel = new JPanel();

    panel.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.gridwidth = 1;
    c.gridheight = 1;
    c.anchor = GridBagConstraints.EAST;
    c.fill = GridBagConstraints.NONE;
    c.weightx = 0.0;
    c.weighty = 0.0;

    JLabel urlLabel = new JLabel("URL: ", 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.gridy = 3;
    panel.add(new JLabel(LOAD_TIME), c);

    c.gridy = 4;
    c.gridwidth = 2;
    c.weightx = 1.0;
    c.anchor = GridBagConstraints.WEST;
    onlineLoad = new JCheckBox("Online Load");
    panel.add(onlineLoad, c);
    onlineLoad.setSelected(true);
    onlineLoad.setForeground(typeLabel.getForeground());

    c.gridy = 5;
    c.gridwidth = 2;
    c.weightx = 1.0;
    c.anchor = GridBagConstraints.WEST;
    editableBox = new JCheckBox("Editable JEditorPane");
    panel.add(editableBox, c);
    editableBox.setSelected(true);
    editableBox.setForeground(typeLabel.getForeground());

    c.gridy = 6;
    c.weightx = 0.0;
    JButton saveButton = new JButton("Save");
    panel.add(saveButton, c);
    saveButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            EditorKit kit = pane.getEditorKit();
            try {
                if (kit instanceof RTFEditorKit) {
                    kit.write(System.out, pane.getDocument(), 0, pane.getDocument().getLength());
                    System.out.flush();
                } else {
                    if (writer == null) {
                        writer = new OutputStreamWriter(System.out);
                        pane.write(writer);
                        writer.flush();
                    }
                    kit.write(writer, pane.getDocument(), 0, pane.getDocument().getLength());
                    writer.flush();
                }
            } catch (Exception e) {
                System.out.println("Write failed");
            }
        }
    });

    c.gridx = 1;
    insertButton = new JButton("Insert HTML");
    panel.add(insertButton, c);
    insertButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            if (insertFrame == null) {
                insertFrame = new HTMLInsertFrame("HTML Insertion", pane);
                Point pt = EditorPaneExample20.this.getLocationOnScreen();
                Dimension d = EditorPaneExample20.this.getSize();
                insertFrame.setLocation(pt.x + d.width, pt.y);
                insertFrame.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent evt) {
                        insertFrame.dispose();
                        insertFrame = null;
                        setInsertButtonState();
                    }
                });
                insertButton.setEnabled(false);
                insertFrame.setVisible(true);
            }
        }
    });
    insertButton.setEnabled(false);

    c.gridx = 1;
    c.gridy = 0;
    c.weightx = 1.0;
    c.anchor = GridBagConstraints.EAST;
    c.fill = GridBagConstraints.HORIZONTAL;

    urlCombo = new JComboBox();
    panel.add(urlCombo, c);
    urlCombo.setEditable(true);
    loadingState = new JLabel(spaces, JLabel.LEFT);
    loadingState.setForeground(Color.black);
    c.gridy = 1;
    panel.add(loadingState, c);
    loadedType = new JLabel(spaces, JLabel.LEFT);
    loadedType.setForeground(Color.black);
    c.gridy = 2;
    panel.add(loadedType, c);
    timeLabel = new JLabel("");
    c.gridy = 3;
    panel.add(timeLabel, c);

    getContentPane().add(panel, "South");

    // Register a custom EditorKit for HTML
    ClassLoader loader = getClass().getClassLoader();
    if (loader != null) {
        // Java 2
        JEditorPane.registerEditorKitForContentType("text/html", "AdvancedSwing.Chapter4.EnhancedHTMLEditorKit",
                loader);
    } else {
        // JDK 1.1
        JEditorPane.registerEditorKitForContentType("text/html",
                "AdvancedSwing.Chapter4.EnhancedHTMLEditorKit");
    }

    // Allocate the empty tree model
    DefaultMutableTreeNode emptyRootNode = new DefaultMutableTreeNode("Empty");
    emptyModel = new DefaultTreeModel(emptyRootNode);

    // Create and place the heading tree
    tree = new JTree(emptyModel);
    tree.setPreferredSize(new Dimension(200, 200));
    getContentPane().add(new JScrollPane(tree), "East");

    // Change page based on combo selection
    urlCombo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            if (populatingCombo == true) {
                return;
            }
            Object selection = urlCombo.getSelectedItem();
            loadNewPage(selection);
        }
    });

    // Change editability based on the checkbox
    editableBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            pane.setEditable(editableBox.isSelected());
            pane.revalidate();
            pane.repaint();
        }
    });

    // Listen for page load to complete
    pane.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getPropertyName().equals("page")) {
                loadComplete();
                displayLoadTime();
                populateCombo(findLinks(pane.getDocument(), null));
                TreeNode node = buildHeadingTree(pane.getDocument());
                tree.setModel(new DefaultTreeModel(node));

                createMenuBar();
                enableMenuBar(true);
                getRootPane().revalidate();

                enableInput();
                loadingPage = false;
            }
        }
    });

    // Listener for tree selection
    tree.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent evt) {
            TreePath path = evt.getNewLeadSelectionPath();
            if (path != null) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                Object userObject = node.getUserObject();
                if (userObject instanceof Heading) {
                    Heading heading = (Heading) userObject;
                    try {
                        Rectangle textRect = pane.modelToView(heading.getOffset());
                        textRect.y += 3 * textRect.height;
                        pane.scrollRectToVisible(textRect);
                    } catch (BadLocationException e) {
                    }
                }
            }
        }
    });

    // Listener for hypertext events
    pane.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(HyperlinkEvent evt) {
            // Ignore hyperlink events if the frame is busy
            if (loadingPage == true) {
                return;
            }
            if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                JEditorPane sp = (JEditorPane) evt.getSource();
                if (evt instanceof HTMLFrameHyperlinkEvent) {
                    HTMLDocument doc = (HTMLDocument) sp.getDocument();
                    doc.processHTMLFrameHyperlinkEvent((HTMLFrameHyperlinkEvent) evt);
                } else {
                    loadNewPage(evt.getURL());
                }
            } else if (evt.getEventType() == HyperlinkEvent.EventType.ENTERED) {
                pane.setCursor(handCursor);
            } else if (evt.getEventType() == HyperlinkEvent.EventType.EXITED) {
                pane.setCursor(defaultCursor);
            }
        }
    });
}

From source file:net.sourceforge.squirrel_sql.client.Application.java

/**
 * Application is starting up.//www  .ja  va 2 s . c o  m
 */
public void startup() {

    final ApplicationArguments args = ApplicationArguments.getInstance();

    // Setup the applications Look and Feel.
    setupLookAndFeel(args);

    editWhereCols.setApplication(this);

    // TODO: Make properties file Application.properties so we can use class
    // name to generate properties file name.
    _resources = new SquirrelResources(SquirrelResources.BUNDLE_BASE_NAME);
    _prefs = SquirrelPreferences.load();
    _desktopStyle = new DesktopStyle(_prefs);
    Locale.setDefault(constructPreferredLocale(_prefs));
    preferencesHaveChanged(null);
    _prefs.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            preferencesHaveChanged(evt);
        }
    });

    SquirrelSplashScreen splash = null;
    if (args.getShowSplashScreen()) {
        splash = new SquirrelSplashScreen(_prefs, 17);
    }

    executeStartupTasks(splash, args);
}

From source file:fi.smaa.jsmaa.gui.views.CriterionView.java

private JComponent buildThresholdsPart() {
    FormLayout layout = new FormLayout("right:pref, 3dlu, left:pref", "p, 3dlu, p");

    PanelBuilder builder = new PanelBuilder(layout);
    CellConstraints cc = new CellConstraints();

    final OutrankingCriterion outrCrit = (OutrankingCriterion) criterion;

    ValueHolder indifHolder = new ValueHolder(outrCrit.getIndifMeasurement());
    indifHolder.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            outrCrit.setIndifMeasurement((CardinalMeasurement) evt.getNewValue());
        }//from   w  w w.java2  s.co  m
    });
    ValueHolder prefHolder = new ValueHolder(outrCrit.getPrefMeasurement());
    prefHolder.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            outrCrit.setPrefMeasurement((CardinalMeasurement) evt.getNewValue());
        }
    });

    MeasurementPanel.MeasurementType[] measVals = new MeasurementPanel.MeasurementType[] {
            MeasurementType.EXACT, MeasurementType.INTERVAL, MeasurementType.GAUSSIAN };
    JPanel indifPanel = new MeasurementPanel(indifHolder, measVals);
    JPanel prefPanel = new MeasurementPanel(prefHolder, measVals);

    builder.addLabel("Indifference:", cc.xy(1, 1));
    builder.add(indifPanel, cc.xy(3, 1));

    builder.addLabel("Preference:", cc.xy(1, 3));
    builder.add(prefPanel, cc.xy(3, 3));

    return builder.getPanel();
}

From source file:org.zkoss.ganttz.TaskComponent.java

public final void afterCompose() {
    updateProperties();//from   ww  w .  j  ava 2  s  .  c om
    if (propertiesListener == null) {

        propertiesListener = new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                updateProperties();
            }
        };
    }

    this.task.addFundamentalPropertiesChangeListener(propertiesListener);

    if (showingAdvancePropertyListener == null) {

        showingAdvancePropertyListener = new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if (isInPage() && !(task instanceof Milestone)) {
                    updateCompletionAdvance();
                }
            }
        };
    }

    this.task.addAdvancesPropertyChangeListener(showingAdvancePropertyListener);

    if (showingReportedHoursPropertyListener == null) {

        showingReportedHoursPropertyListener = new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if (isInPage() && !(task instanceof Milestone)) {
                    updateCompletionReportedHours();
                }
            }
        };
    }

    this.task.addReportedHoursPropertyChangeListener(showingReportedHoursPropertyListener);

    if (showingMoneyCostBarPropertyListener == null) {

        showingMoneyCostBarPropertyListener = new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if (isInPage() && !(task instanceof Milestone)) {
                    updateCompletionMoneyCostBar();
                }
            }
        };
    }

    this.task.addMoneyCostBarPropertyChangeListener(showingMoneyCostBarPropertyListener);

    if (criticalPathPropertyListener == null) {

        criticalPathPropertyListener = new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                updateClass();
            }

        };
    }

    this.task.addCriticalPathPropertyChangeListener(criticalPathPropertyListener);

    updateClass();
}

From source file:ca.uhn.hl7v2.testpanel.ui.v2tree.Hl7V2MessageTree.java

/** Creates new TreePanel */
public Hl7V2MessageTree(Controller theController) {
    addKeyListener(new KeyAdapter() {
        @Override//from  w w w  .j  a  va 2s .com
        public void keyPressed(KeyEvent e) {
            handleKeyPress(e);
        }
    });

    setFont(new Font("LUCIDA", Font.PLAIN, 9));

    myController = theController;

    myPipeParser = new PipeParser();
    myPipeParser.setValidationContext(new ValidationContextImpl());

    setRenderDataProvider(new TreeRenderDataProvider());

    setShowGrid(true);
    setGridColor(new Color(0.9f, 0.9f, 0.9f));
    setRowHeight(16);

    setRowSelectionAllowed(true);

    setSelectionModel(new MySelectionModel());

    ValueCellEditor valueCellEditor = new ValueCellEditor(getFont());
    setDefaultEditor(String.class, valueCellEditor);

    valueCellEditor.addCellEditorListener(new CellEditorListener() {

        public void editingCanceled(ChangeEvent theE) {
            ourLog.info("No longer editing");
            myCurrentlyEditing = false;
        }

        public void editingStopped(ChangeEvent theE) {
            ourLog.info("No longer editing");
            myCurrentlyEditing = false;
        }
    });

    myHighlitedPathListener = new PropertyChangeListener() {

        public void propertyChange(PropertyChangeEvent theEvt) {
            if (myController.isMessageEditorInFollowMode()) {
                if (Hl7V2MessageTree.this.hasFocus() == false) {
                    synchronizeTreeWithHighlitedPath();
                }
            }
        }

    };

    myParsedMessagesListener = new PropertyChangeListener() {

        public void propertyChange(PropertyChangeEvent theEvt) {
            myUpdaterThread.scheduleUpdate();
        }
    };

    myValidationContextListener = new PropertyChangeListener() {

        public void propertyChange(PropertyChangeEvent theEvt) {
            myUpdaterThread.scheduleUpdate();
        }
    };

    myMessageEncodingListener = new PropertyChangeListener() {

        public void propertyChange(PropertyChangeEvent theEvt) {
            myUpdaterThread.scheduleUpdate();
        }
    };

    getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    myUpdaterThread = new UpdaterThread();
    myUpdaterThread.start();
}

From source file:edu.ku.brc.specify.tools.schemalocale.SchemaLocalizerFrame.java

/**
 * /*from   w  w  w .ja  v a 2  s. c o  m*/
 */
protected void buildUI() {
    SchemaLocalizerXMLHelper slxh = new SchemaLocalizerXMLHelper(schemaType, tableMgr);
    localizableIO = slxh;
    localizableIO.load(false);

    //stripToSingleLocale("pt", slxh);

    LocalizableStrFactory localizableStrFactory = new LocalizableStrFactory() {
        public LocalizableStrIFace create() {
            SpLocaleItemStr str = new SpLocaleItemStr();
            str.initialize();
            return str;
        }

        public LocalizableStrIFace create(String text, Locale locale) {
            return new SpLocaleItemStr(text, locale); // no initialize needed for this constructor
        }
    };

    LocalizerBasePanel.setLocalizableStrFactory(localizableStrFactory);
    SchemaLocalizerXMLHelper.setLocalizableStrFactory(localizableStrFactory);

    schemaLocPanel = new SchemaLocalizerPanel(null, dataObjFieldFormatMgrCache, uiFieldFormatterMgrCache,
            webLinkMgrCache, schemaType);
    schemaLocPanel.setLocalizableIO(localizableIO);
    schemaLocPanel.setStatusBar(statusBar);

    boolean useDisciplines = AppPreferences.getLocalPrefs().getBoolean("SCHEMA_DISP", false);
    schemaLocPanel.setUseDisciplines(useDisciplines);

    // rods - for now 
    //schemaLocPanel.setIncludeHiddenUI(true);
    schemaLocPanel.buildUI();
    schemaLocPanel.setHasChanged(localizableIO.didModelChangeDuringLoad());

    statusBar.setSectionText(1,
            schemaType == SpLocaleContainer.CORE_SCHEMA ? getResourceString("SchemaLocalizerFrame.FULL_SCHEMA") //$NON-NLS-1$
                    : getResourceString("SchemaLocalizerFrame.WB_SCHEMA")); //$NON-NLS-1$

    UIRegistry.setStatusBar(statusBar);

    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    String title = "File"; //$NON-NLS-1$
    String mneu = "F"; //$NON-NLS-1$
    JMenu fileMenu = UIHelper.createLocalizedMenu(menuBar, title, mneu);

    title = "Save"; //$NON-NLS-1$
    mneu = "S"; //$NON-NLS-1$
    JMenuItem saveMenuItem = UIHelper.createLocalizedMenuItem(fileMenu, title, mneu, "", false, //$NON-NLS-1$
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    write();
                }
            });
    saveMenuItem.setEnabled(false);

    title = "Export"; //$NON-NLS-1$
    mneu = "E"; //$NON-NLS-1$
    UIHelper.createLocalizedMenuItem(fileMenu, title, mneu, "", true, new ActionListener() //$NON-NLS-1$
    {
        public void actionPerformed(ActionEvent e) {
            export();
        }
    });

    title = "SchemaLocalizerFrame.ExportLOCALE"; //$NON-NLS-1$
    mneu = "SchemaLocalizerFrame.ExportLOCALEMnu"; //$NON-NLS-1$
    UIHelper.createLocalizedMenuItem(fileMenu, title, mneu, "", true, new ActionListener() //$NON-NLS-1$
    {
        public void actionPerformed(ActionEvent e) {
            exportSingleLocale();
        }
    });

    title = "Exit"; //$NON-NLS-1$
    mneu = "x"; //$NON-NLS-1$
    if (!UIHelper.isMacOS()) {
        fileMenu.addSeparator();

        UIHelper.createLocalizedMenuItem(fileMenu, title, mneu, "", true, new ActionListener() //$NON-NLS-1$
        {
            public void actionPerformed(ActionEvent e) {
                shutdown();
            }
        });
    }
    /*
    JMenu toolMenu = UIHelper.createMenu(menuBar, "Tools", "T");
    UIHelper.createMenuItem(toolMenu, "Create Resource Files", "C", "", true, new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
        createResourceFiles();
    }
    });
    */

    menuBar.add(SchemaI18NService.getInstance().createLocaleMenu(this, new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getPropertyName().equals("locale")) //$NON-NLS-1$
            {
                schemaLocPanel.localeChanged((Locale) evt.getNewValue());
                statusBar.setSectionText(0, SchemaI18NService.getCurrentLocale().getDisplayName());
            }
        }
    }));

    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

    setSize(800, 600);

    JPanel mainPanel = new JPanel(new BorderLayout());
    mainPanel.add(schemaLocPanel, BorderLayout.CENTER);
    mainPanel.add(statusBar, BorderLayout.SOUTH);

    mainPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
    setContentPane(mainPanel);

    statusBar.setSectionText(0, SchemaI18NService.getCurrentLocale().getDisplayName());

    schemaLocPanel.setSaveMenuItem(saveMenuItem);

    schemaLocPanel.getContainerList().setEnabled(true);

    AppPreferences localPrefs = AppPreferences.getLocalPrefs();
    localPrefs.setDirPath(UIRegistry.getAppDataDir());

    ImageIcon helpIcon = IconManager.getIcon("AppIcon", IconSize.Std16); //$NON-NLS-1$
    HelpMgr.initializeHelp("SpecifyHelp", helpIcon.getImage()); //$NON-NLS-1$

    AppPrefsCache.setUseLocalOnly(true);
    SpecifyAppPrefs.loadColorAndFormatPrefs();

    if (localizableIO.didModelChangeDuringLoad()) {
        saveMenuItem.setEnabled(true);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame(getResourceString("SchemaLocalizerFrame.CHG_TO_SCHEMA")); //$NON-NLS-1$
                frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

                JTextPane tp = new JTextPane();
                JScrollPane js = new JScrollPane();
                js.getViewport().add(tp);

                tp.setContentType("text/html");
                tp.setText(((SchemaLocalizerXMLHelper) localizableIO).getChangesBuffer());

                frame.setContentPane(js);
                frame.pack();
                frame.setSize(400, 500);
                frame.setVisible(true);
            }
        });
    }
}

From source file:gtu._work.etc._3DSMovieRenamer.java

private void initGUI() {
    try {//from   www.  j  ava  2 s .c o m
        final SwingActionUtil swingUtil = (SwingActionUtil) SwingActionUtil.newInstance(this);

        BorderLayout thisLayout = new BorderLayout();
        getContentPane().setLayout(thisLayout);
        this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        this.setTitle("3DS Rename");
        {
            jTabbedPane1 = new JTabbedPane();
            getContentPane().add(jTabbedPane1, BorderLayout.CENTER);
            {
                jPanel1 = new JPanel();
                BorderLayout jPanel1Layout = new BorderLayout();
                jPanel1.setLayout(jPanel1Layout);
                jTabbedPane1.addTab("vid list", null, jPanel1, null);
                {
                    openDir = new JButton();
                    jPanel1.add(openDir, BorderLayout.NORTH);
                    openDir.setText("open dir");
                    openDir.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            swingUtil.invokeAction("openDir.actionPerformed", evt);
                        }
                    });
                }
                {
                    ListModel vidListModel = new DefaultListModel();
                    vidList = new JList();
                    jPanel1.add(vidList, BorderLayout.CENTER);
                    vidList.setModel(vidListModel);
                    vidList.addMouseListener(new MouseAdapter() {
                        public void mouseClicked(MouseEvent evt) {
                            swingUtil.invokeAction("vidList.mouseClicked", evt);
                        }
                    });
                    vidList.addKeyListener(new KeyAdapter() {
                        public void keyPressed(KeyEvent evt) {
                            swingUtil.invokeAction("vidList.keyPressed", evt);
                        }
                    });
                }
                {
                    jPanel3 = new JPanel();
                    jPanel1.add(jPanel3, BorderLayout.SOUTH);
                    jPanel3.setPreferredSize(new java.awt.Dimension(445, 34));
                    {
                        renameText = new JTextField();
                        jPanel3.add(renameText);
                        renameText.setPreferredSize(new java.awt.Dimension(187, 24));
                    }
                    {
                        renameBtn = new JButton();
                        jPanel3.add(renameBtn);
                        renameBtn.setText("rename");
                        renameBtn.setPreferredSize(new java.awt.Dimension(106, 24));
                        renameBtn.addMouseListener(new MouseAdapter() {
                            public void mouseClicked(MouseEvent evt) {
                                swingUtil.invokeAction("renameBtn.mouseClicked", evt);
                            }
                        });
                    }
                    {
                        forceChange = new JCheckBox();
                        jPanel3.add(forceChange);
                        forceChange.setText("force");
                        forceChange.setPreferredSize(new java.awt.Dimension(64, 21));
                    }
                }
            }
            {
                jPanel2 = new JPanel();
                BorderLayout jPanel2Layout = new BorderLayout();
                jPanel2.setLayout(jPanel2Layout);
                jTabbedPane1.addTab("copy", null, jPanel2, null);
                {
                    jScrollPane1 = new JScrollPane();
                    jPanel2.add(jScrollPane1, BorderLayout.CENTER);
                    {
                        ListModel copyToListModel = new DefaultListModel();
                        copyToList = new JList();
                        jScrollPane1.setViewportView(copyToList);
                        copyToList.setModel(copyToListModel);
                        copyToList.addMouseListener(new MouseAdapter() {
                            public void mouseClicked(MouseEvent evt) {
                                swingUtil.invokeAction("copyToList.mouseClicked", evt);
                            }
                        });
                    }
                }
            }
            {
                jPanel4 = new JPanel();
                BorderLayout jPanel4Layout = new BorderLayout();
                jPanel4.setLayout(jPanel4Layout);
                jTabbedPane1.addTab("BT Movie", null, jPanel4, null);
                {
                    jScrollPane2 = new JScrollPane();
                    jPanel4.add(jScrollPane2, BorderLayout.WEST);
                    jScrollPane2.setPreferredSize(new java.awt.Dimension(254, 355));
                    {
                        btDirTree = new JTree();
                        jScrollPane2.setViewportView(btDirTree);
                        btDirTree.addMouseListener(new MouseAdapter() {
                            public void mouseClicked(MouseEvent evt) {
                                swingUtil.invokeAction(evt);
                            }
                        });
                        btDirTree.addPropertyChangeListener(new PropertyChangeListener() {
                            public void propertyChange(PropertyChangeEvent evt) {
                                swingUtil.invokeAction(evt);
                            }
                        });
                        JTreeUtil.newInstance(btDirTree).fileSystem(DEFAULT_BT_DIR);
                    }
                }
                {
                    jPanel5 = new JPanel();
                    BorderLayout jPanel5Layout = new BorderLayout();
                    jPanel5.setLayout(jPanel5Layout);
                    jPanel4.add(jPanel5, BorderLayout.CENTER);
                    {
                        jScrollPane3 = new JScrollPane();
                        jPanel5.add(jScrollPane3, BorderLayout.CENTER);
                        jScrollPane3.setPreferredSize(new java.awt.Dimension(427, 355));
                        {
                            DefaultListModel btMovListModel = new DefaultListModel();
                            btMovList = new JList();
                            jScrollPane3.setViewportView(btMovList);
                            btMovList.setModel(btMovListModel);
                            btMovList.addMouseListener(new MouseAdapter() {
                                public void mouseClicked(MouseEvent evt) {
                                    swingUtil.invokeAction(evt);
                                }
                            });
                            btMovList.addKeyListener(new KeyAdapter() {
                                public void keyPressed(KeyEvent evt) {
                                    JListUtil.newInstance(btMovList).defaultJListKeyPressed(evt);
                                }
                            });
                        }
                    }
                }
            }
            {
                jPanel6 = new JPanel();
                FlowLayout jPanel6Layout = new FlowLayout();
                jTabbedPane1.addTab("common", null, jPanel6, null);
                jPanel6.setLayout(jPanel6Layout);
                {
                    execute3dsVidTransfer = new JButton();
                    jPanel6.add(execute3dsVidTransfer);
                    execute3dsVidTransfer.setText("execute 3ds video transfer");
                    execute3dsVidTransfer.setPreferredSize(new java.awt.Dimension(207, 42));
                    execute3dsVidTransfer.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            String bat = "C:/apps/_movie/3DSVideov1.00/3DS Video.exe";
                            try {
                                Runtime.getRuntime().exec(String.format("cmd /c call \"%s\"", bat));
                            } catch (IOException e) {
                                JCommonUtil.handleException(e);
                            }
                        }
                    });
                }
                {
                    openMovieAppDir = new JButton();
                    jPanel6.add(openMovieAppDir);
                    openMovieAppDir.setText("open movie app dir");
                    openMovieAppDir.setPreferredSize(new java.awt.Dimension(207, 42));
                    openMovieAppDir.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                Desktop.getDesktop().open(new File("C:/apps/_movie"));
                            } catch (IOException e) {
                                JCommonUtil.handleException(e);
                            }
                        }
                    });
                }
            }
            {
                jPanel7 = new JPanel();
                BorderLayout jPanel7Layout = new BorderLayout();
                jTabbedPane1.addTab("fake rename", null, jPanel7, null);
                jPanel7.setLayout(jPanel7Layout);
                {
                    openFakeRenameDir = new JButton();
                    jPanel7.add(openFakeRenameDir, BorderLayout.NORTH);
                    openFakeRenameDir.setText("open dir");
                    openFakeRenameDir.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            File file = JCommonUtil._jFileChooser_selectDirectoryOnly();
                            if (file != null) {
                                DefaultListModel model = new DefaultListModel();
                                for (File f : file.listFiles()) {
                                    model.addElement(f);
                                }
                                openFakeRenameDirList.setModel(model);
                            }
                        }
                    });
                }
                {
                    DefaultListModel openFakeRenameDirListModel = new DefaultListModel();
                    openFakeRenameDirList = new JList();
                    jPanel7.add(openFakeRenameDirList, BorderLayout.CENTER);
                    openFakeRenameDirList.setModel(openFakeRenameDirListModel);
                    openFakeRenameDirList.addMouseListener(new MouseAdapter() {
                        public void mouseClicked(MouseEvent evt) {
                            File file = (File) JListUtil.getLeadSelectionObject(openFakeRenameDirList);
                            try {
                                Process process = Runtime.getRuntime()
                                        .exec(String.format("cmd /c call \"%s\"", file));
                                InputStream ins = process.getInputStream();
                                while (ins.read() != -1) {
                                    //TODO
                                }
                                ins.close();
                                System.out.println("done...");
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    openFakeRenameDirList.addKeyListener(new KeyAdapter() {
                        public void keyPressed(KeyEvent evt) {
                            JListUtil.newInstance(openFakeRenameDirList).defaultJListKeyPressed(evt);
                        }
                    });
                }
                {
                    jPanel8 = new JPanel();
                    jPanel7.add(jPanel8, BorderLayout.SOUTH);
                    jPanel8.setPreferredSize(new java.awt.Dimension(681, 43));
                    {
                        openFakeRenameDir_newName = new JTextField();
                        jPanel8.add(openFakeRenameDir_newName);
                        openFakeRenameDir_newName.setPreferredSize(new java.awt.Dimension(287, 27));
                    }
                    {
                        fakeRenameExecute = new JButton();
                        jPanel8.add(fakeRenameExecute);
                        fakeRenameExecute.setText("execute");
                        fakeRenameExecute.setPreferredSize(new java.awt.Dimension(95, 27));
                        fakeRenameExecute.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent evt) {
                                DefaultListModel model = (DefaultListModel) openFakeRenameDirList.getModel();
                                //TODO
                            }
                        });
                    }
                }
            }

            swingUtil.addAction("copyToList.mouseClicked", new Action() {
                public void action(EventObject evt) throws Exception {
                    try {
                        if (((MouseEvent) evt).getButton() == 3) {
                            JMenuItem reloadMenu = new JMenuItem();
                            reloadMenu.setText("reload SD card directory");
                            reloadMenu.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                    DefaultListModel copyToListModel = new DefaultListModel();
                                    for (final File f : load3DSDir.listFiles(new FilenameFilter() {
                                        public boolean accept(File paramFile, String paramString) {
                                            if (paramFile.isDirectory()
                                                    && paramString.matches(CUSTOM_3DS_DIR_PATTERN)) {
                                                return true;
                                            }
                                            return false;
                                        }
                                    })) {
                                        copyToListModel.addElement(f);
                                    }
                                    copyToList.setModel(copyToListModel);
                                }
                            });
                            JMenuItem copyAllToMenu = new JMenuItem();
                            {
                                copyAllToMenu.setText(
                                        String.format("move %d vids to...", vidList.getModel().getSize()));
                                final File toDir = (File) JListUtil.getLeadSelectionObject(copyToList);
                                if (toDir == null || !toDir.exists() || !toDir.isDirectory()) {
                                    copyAllToMenu.setEnabled(false);
                                }
                                if (vidList.getModel().getSize() == 0) {
                                    copyAllToMenu.setText("copy no file...");
                                    copyAllToMenu.setEnabled(false);
                                }
                                copyAllToMenu.addActionListener(new ActionListener() {
                                    public void actionPerformed(ActionEvent e) {
                                        DefaultListModel model = JListUtil.newInstance(vidList).getModel();
                                        if (JOptionPaneUtil.ComfirmDialogResult.YES_OK_OPTION != JOptionPaneUtil
                                                .newInstance().iconWaringMessage().confirmButtonYesNo()
                                                .showConfirmDialog("are you sure copy files : "
                                                        + model.getSize() + "\n to dir : " + toDir,
                                                        "COPY VIDS")) {
                                            return;
                                        }
                                        for (int ii = 0; ii < model.getSize(); ii++) {
                                            File src = (File) model.getElementAt(ii);
                                            src.renameTo(new File(toDir, src.getName()));
                                        }
                                        JOptionPaneUtil.newInstance().iconInformationMessage()
                                                .showMessageDialog("copy completed!", "SUCCESS");
                                        loadDirVids();
                                    }
                                });
                            }

                            JPopupMenuUtil.newInstance(copyToList).applyEvent((MouseEvent) evt)
                                    .addJMenuItem(reloadMenu, copyAllToMenu).show();
                        }
                    } catch (Exception ex) {
                        JCommonUtil.handleException(ex);
                    }
                }
            });
            swingUtil.addAction("openDir.actionPerformed", new Action() {
                public void action(EventObject evt) throws Exception {
                    File file = JFileChooserUtil.newInstance().selectDirectoryOnly().showOpenDialog()
                            .getApproveSelectedFile();
                    if (file == null) {
                        JOptionPaneUtil.newInstance().iconErrorMessage()
                                .showMessageDialog("dir not corrent!, set desktop", getTitle());
                        loadDir = FileUtil.DESKTOP_DIR;
                    } else {
                        loadDir = file;
                    }
                    loadDirVids();
                }
            });
            swingUtil.addAction("vidList.mouseClicked", new Action() {
                //                    final String player = "C:/Program Files (x86)/GRETECH/GomPlayer/GOM.EXE";

                public void action(EventObject evt) throws Exception {
                    int pos = -1;
                    if ((pos = vidList.getLeadSelectionIndex()) == -1) {
                        return;
                    }
                    MouseEvent mevt = (MouseEvent) evt;

                    final File selectItem = (File) vidList.getModel().getElementAt(pos);

                    List<JMenuItem> menuList = new ArrayList<JMenuItem>();
                    JMenuItem simpleRenamer = new JMenuItem();
                    final String simpleRenamePrefix = RandomUtil.upperCase(3);
                    simpleRenamer.setText("Rename : " + simpleRenamePrefix);
                    simpleRenamer.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent paramActionEvent) {
                            String value = StringUtils.defaultString(JOptionPaneUtil.newInstance()
                                    .showInputDialog("3 char prefix?", "AVI PREFIX"), simpleRenamePrefix);
                            if (value != null && value.matches("[a-zA-Z]{3}")) {
                                selectItem.renameTo(getNewFile(selectItem.getParentFile(), value));
                                loadDirVids();
                            } else {
                                JOptionPaneUtil.newInstance().iconErrorMessage()
                                        .showMessageDialog("prefix is not correct!", "ERROR");
                            }
                        }
                    });
                    menuList.add(simpleRenamer);
                    if (load3DSDir == null) {
                        reload3DSDir();
                        if (load3DSDir == null) {
                            JMenuItem disable = new JMenuItem();
                            disable.setText("MOVE : SD card is not set!");
                            disable.setEnabled(false);
                            menuList.add(disable);
                        }
                    } else {
                        for (final File f : load3DSDir.listFiles(new FilenameFilter() {
                            public boolean accept(File paramFile, String paramString) {
                                if (paramFile.isDirectory() && paramString.matches(CUSTOM_3DS_DIR_PATTERN)) {
                                    return true;
                                }
                                return false;
                            }
                        })) {
                            JMenuItem copyTo = new JMenuItem();
                            copyTo.setText("MOVE : " + f.getName());
                            copyTo.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent paramActionEvent) {
                                    if (JOptionPaneUtil.ComfirmDialogResult.YES_OK_OPTION == JOptionPaneUtil
                                            .newInstance().iconQuestionMessage().confirmButtonYesNo()
                                            .showConfirmDialog(//
                                                    "are you sure move file\n" + //
                                    selectItem + "\n" + //
                                    "to\n" + //
                                    "dir : " + f + "  ??"//
                                    , "COPY FILE")) {

                                        File copyToNewDirFile = new File(f, selectItem.getName());
                                        if (copyToNewDirFile.exists()) {
                                            JOptionPaneUtil.newInstance().iconErrorMessage().showMessageDialog(
                                                    "target dir file already exist!, need rename!",
                                                    "FILE ALREADY EXIST");
                                            return;
                                        }
                                        selectItem.renameTo(copyToNewDirFile);
                                        loadDirVids();

                                        JOptionPaneUtil.newInstance().iconErrorMessage()
                                                .showMessageDialog("move completed!", "MOVE FILE");
                                    }
                                }
                            });
                            menuList.add(copyTo);
                        }
                    }
                    JPopupMenuUtil.newInstance(vidList).applyEvent(mevt)
                            .addJMenuItem(menuList.toArray(new JMenuItem[menuList.size()])).show();

                    if (mevt.getClickCount() != 2) {
                        return;
                    }
                    String clkItemPath = selectItem.getAbsolutePath();
                    String command = "cmd /c call \"" + clkItemPath + "\"";
                    System.out.println(command);
                    Runtime.getRuntime().exec(command);
                }
            });
            swingUtil.addAction("vidList.keyPressed", new Action() {
                public void action(EventObject evt) throws Exception {
                    JListUtil.newInstance(vidList).defaultJListKeyPressed(evt);
                }
            });
            swingUtil.addAction("renameBtn.mouseClicked", new Action() {

                Pattern aviNamePattern = Pattern.compile("^([a-zA-Z]{3})_\\d{4}\\.[aA][vV][iI]$");

                public void action(EventObject evt) throws Exception {
                    String name = StringUtils.defaultIfEmpty(renameText.getText(), RandomUtil.upperCase(3));
                    System.out.println("name = " + name + ", force : " + forceChange.isSelected());
                    if (!name.matches("[a-zA-Z]{3}")) {
                        renameText.setText("");
                        JOptionPaneUtil.newInstance().iconErrorMessage()
                                .showMessageDialog("rename must eng 3 char!", "ERROR");
                        return;
                    }
                    DefaultListModel model = (DefaultListModel) vidList.getModel();
                    boolean matchOk = false;
                    if (model.size() != 0) {
                        File oldFile = null;
                        Matcher matcher = null;
                        for (int ii = 0; ii < model.getSize(); ii++) {
                            oldFile = (File) model.getElementAt(ii);

                            if (!oldFile.exists()) {
                                JOptionPaneUtil.newInstance().iconErrorMessage().showMessageDialog(
                                        "file not exeist : \n" + oldFile.getAbsolutePath(), getTitle());
                                return;
                            }
                            matcher = aviNamePattern.matcher(oldFile.getName());
                            matchOk = matcher.find();
                            System.out.println("matchOk = " + matchOk);
                            if (matchOk && !forceChange.isSelected()) {
                                oldFile.renameTo(getNewFile(oldFile.getParentFile(), matcher.group(1)));
                            } else {
                                oldFile.renameTo(getNewFile(oldFile.getParentFile(), name));
                            }
                        }
                        JOptionPaneUtil.newInstance().iconInformationMessage().showMessageDialog("success!",
                                getTitle());
                    }
                    loadDirVids();
                }
            });

            ToolTipManager.sharedInstance().setInitialDelay(0);
            swingUtil.addAction(btMovList, MouseEvent.class, new Action() {
                public void action(EventObject evt) throws Exception {
                    final File file = (File) JListUtil.getLeadSelectionObject(btMovList);
                    if (JMouseEventUtil.buttonLeftClick(1, evt)) {
                        btMovList.setToolTipText(
                                DateFormatUtils.format(file.lastModified(), "yyyy/MM/dd HH:mm:ss") + " length:"
                                        + (file.length() / 1024) + "k");
                    }

                    final Object[] objects = btMovList.getSelectedValues();
                    JPopupMenuUtil.newInstance(btMovList).applyEvent(evt)//
                            .addJMenuItem("move out", (objects != null && objects.length > 0),
                                    new ActionListener() {
                                        public void actionPerformed(ActionEvent paramActionEvent) {
                                            List<File> list = new ArrayList<File>();
                                            for (Object val : objects) {
                                                list.add((File) val);
                                            }
                                            if (!JCommonUtil._JOptionPane_showConfirmDialog_yesNoOption(
                                                    "sure move file from\n" + list.toString().replace(',', '\n')
                                                            + "\nto\n" + DEFAULT_BT_DIR,
                                                    "MOVE")) {
                                                return;
                                            }
                                            StringBuilder sb = new StringBuilder();
                                            File moveTo = null;
                                            for (File file : list) {
                                                sb.append((file.renameTo(
                                                        moveTo = new File(DEFAULT_BT_DIR, file.getName()))
                                                        && moveTo.exists()) ? "" : file + "\n");
                                            }
                                            JCommonUtil._jOptionPane_showMessageDialog_info(
                                                    sb.length() == 0 ? "move success!" : "move failed!\n" + sb);
                                        }
                                    })
                            .addJMenuItem("delete this", file.exists(), new ActionListener() {
                                public void actionPerformed(ActionEvent paramActionEvent) {
                                    if (!JCommonUtil._JOptionPane_showConfirmDialog_yesNoOption(
                                            "sure delete file \n" + file, "DELETE")) {
                                        return;
                                    }
                                    boolean result = file.delete();
                                    System.out.println("!!!!!" + result + "..." + file.exists());
                                    JCommonUtil._jOptionPane_showMessageDialog_info(
                                            result ? "delete success!" : "delete failed!");
                                }
                            }).show();

                    if (JMouseEventUtil.buttonLeftClick(2, evt)) {
                        Runtime.getRuntime().exec(String.format("cmd /c call \"%s\"", file));
                    }
                }
            });
            swingUtil.addAction(btDirTree, MouseEvent.class, new Action() {

                File getSingleFile() {
                    return ((JFile) JTreeUtil.newInstance(btDirTree).getSelectItem().getUserObject()).getFile();
                }

                public void action(EventObject evt) throws Exception {
                    int selectCount = btDirTree.getSelectionModel().getSelectionCount();
                    if (selectCount == 1) {
                        final File file = getSingleFile();
                        JPopupMenuUtil.newInstance(btDirTree).applyEvent(evt).addJMenuItem("delete this",
                                selectCount == 1 && file.exists(), new ActionListener() {
                                    public void actionPerformed(ActionEvent paramActionEvent) {
                                        if (file.isFile()) {
                                            if (JCommonUtil._JOptionPane_showConfirmDialog_yesNoOption(
                                                    "sure delete FILE : \n" + file, "WARNING")) {
                                                file.delete();
                                                JCommonUtil._jOptionPane_showMessageDialog_info(
                                                        (file.exists() ? "delete failed!" : "delete success!"));
                                            }
                                        }
                                        if (file.isDirectory()) {
                                            StringBuilder sb = new StringBuilder();
                                            if (JCommonUtil._JOptionPane_showConfirmDialog_yesNoOption(
                                                    "sure delete DIR : \n" + file, "WARNING")) {
                                                List<Boolean> delL = new ArrayList<Boolean>();
                                                for (File f : file.listFiles()) {
                                                    if (fileExtensionPattern.matcher(f.getName()).find()
                                                            || f.length() > 1000000L) {
                                                        if (!JCommonUtil
                                                                ._JOptionPane_showConfirmDialog_yesNoOption(
                                                                        "delete this : \n" + f,
                                                                        "CHECK AGAIN")) {
                                                            continue;
                                                        }
                                                        delL.add(f.delete());
                                                    }
                                                    delL.add(f.delete());
                                                }
                                                for (File f : file.listFiles()) {
                                                    if (f.exists()) {
                                                        sb.append(f + "\n");
                                                    }
                                                }
                                                System.out.println("delL.contains(false)==================>"
                                                        + delL.contains(false));
                                            }
                                            if (!file.delete()) {
                                                sb.append(file + "\n");
                                            }
                                            JCommonUtil._jOptionPane_showMessageDialog_info(
                                                    sb.length() > 0 ? "delete failed!\nlist:\n" + sb
                                                            : "delete success!");
                                            if (sb.length() == 0) {
                                                DefaultMutableTreeNode node = JTreeUtil.newInstance(btDirTree)
                                                        .getSelectItem();
                                                System.out.println(
                                                        JTreeUtil.newInstance(btDirTree).removeNode(node));
                                            }
                                        }
                                    }
                                }).addJMenuItem("open dir", new ActionListener() {
                                    public void actionPerformed(ActionEvent paramActionEvent) {
                                        File openTarget = file;
                                        if (file.isFile()) {
                                            openTarget = file.getParentFile();
                                        }
                                        try {
                                            Desktop.getDesktop().open(openTarget);
                                        } catch (IOException e) {
                                            JCommonUtil.handleException(e);
                                        }
                                    }
                                }).show();
                    }
                }
            });
            swingUtil.addAction(btDirTree, PropertyChangeEvent.class, new Action() {
                public void action(EventObject evt) throws Exception {
                    List<File> list = new ArrayList<File>();
                    for (DefaultMutableTreeNode node : JTreeUtil.newInstance(btDirTree).getSelectItems()) {
                        JFile jfile = (JFile) node.getUserObject();
                        if (jfile.getFile().isDirectory()) {
                            for (File f : jfile.getFile().listFiles(new FilenameFilter() {
                                public boolean accept(File paramFile, String paramString) {
                                    return fileExtensionPattern.matcher(paramString).find();
                                }
                            })) {
                                System.out.println(f.getName() + "...." + f.length());
                                list.add(f);
                            }
                        }
                    }
                    Collections.sort(list, new Comparator<File>() {
                        public int compare(File paramT1, File paramT2) {
                            return paramT1.lastModified() > paramT2.lastModified() ? -1 : 1;
                        }
                    });
                    btMovList.setModel(JListUtil.createModel(list.iterator()));
                }
            });
        }
        this.setSize(702, 422);

        loadDirVids();
        reload3DSDir();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.opencastproject.staticfiles.endpoint.StaticFileRestService.java

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)// ww w . ja va  2  s .  co  m
@Path("")
@RestQuery(name = "postStaticFile", description = "Post a new static resource", bodyParameter = @RestParameter(description = "The static resource file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE), reponses = {
        @RestResponse(description = "Returns the id of the uploaded static resource", responseCode = HttpServletResponse.SC_CREATED),
        @RestResponse(description = "No filename or file to upload found", responseCode = HttpServletResponse.SC_BAD_REQUEST),
        @RestResponse(description = "The upload size is too big", responseCode = HttpServletResponse.SC_BAD_REQUEST) }, returnDescription = "")
public Response postStaticFile(@Context HttpServletRequest request) {
    if (maxUploadSize > 0 && request.getContentLength() > maxUploadSize) {
        logger.warn("Preventing upload of static file as its size {} is larger than the max size allowed {}",
                request.getContentLength(), maxUploadSize);
        return Response.status(Status.BAD_REQUEST).build();
    }
    ProgressInputStream inputStream = null;
    try {
        String filename = null;
        if (ServletFileUpload.isMultipartContent(request)) {
            boolean isDone = false;
            for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) {
                FileItemStream item = iter.next();
                if (item.isFormField()) {
                    continue;
                } else {
                    logger.debug("Processing file item");
                    filename = item.getName();
                    inputStream = new ProgressInputStream(item.openStream());
                    inputStream.addPropertyChangeListener(new PropertyChangeListener() {
                        @Override
                        public void propertyChange(PropertyChangeEvent evt) {
                            long totalNumBytesRead = (Long) evt.getNewValue();
                            if (totalNumBytesRead > maxUploadSize) {
                                logger.warn("Upload limit of {} bytes reached, returning a bad request.",
                                        maxUploadSize);
                                throw new WebApplicationException(Status.BAD_REQUEST);
                            }
                        }
                    });
                    isDone = true;
                }
                if (isDone)
                    break;
            }
        } else {
            logger.warn("Request is not multi part request, returning a bad request.");
            return Response.status(Status.BAD_REQUEST).build();
        }

        if (filename == null) {
            logger.warn("Request was missing the filename, returning a bad request.");
            return Response.status(Status.BAD_REQUEST).build();
        }

        if (inputStream == null) {
            logger.warn("Request was missing the file, returning a bad request.");
            return Response.status(Status.BAD_REQUEST).build();
        }

        String uuid = staticFileService.storeFile(filename, inputStream);
        try {
            return Response.created(getStaticFileURL(uuid)).entity(uuid).build();
        } catch (NotFoundException e) {
            logger.error("Previous stored file with uuid {} couldn't beren found: {}", uuid,
                    ExceptionUtils.getStackTrace(e));
            return Response.serverError().build();
        }
    } catch (WebApplicationException e) {
        return e.getResponse();
    } catch (Exception e) {
        logger.error("Unable to store file because: {}", ExceptionUtils.getStackTrace(e));
        return Response.serverError().build();
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:org.kalypso.ui.wizard.shape.ImportShapeFileImportPage.java

private WorkspaceFileBinding createStyleFileControls(final Composite parent) {
    final Label styleLabel = new Label(parent, SWT.NONE);
    styleLabel.setText(Messages.getString("org.kalypso.ui.wizard.shape.ImportShapeFileImportPage.6")); //$NON-NLS-1$

    final IObservableValue modelFile = BeansObservables.observeValue(m_data.getStyleFile(),
            FileAndHistoryData.PROPERTY_PATH);
    final IObservableValue modelHistory = BeansObservables.observeValue(m_data.getStyleFile(),
            FileAndHistoryData.PROPERTY_HISTORY);

    final String dialogMessage = Messages.getString("org.kalypso.ui.wizard.shape.ImportShapeFileImportPage.14"); //$NON-NLS-1$
    final String[] extensions = new String[] { "sld" }; //$NON-NLS-1$

    final WorkspaceFileBinding fileBinding = new WorkspaceFileBinding(m_binding, modelFile, dialogMessage,
            extensions);/*from www.  ja  v  a  2  s .c o  m*/
    fileBinding.setInputContainer(m_project);

    final Control fileField = fileBinding.createFileFieldWithHistory(parent, modelHistory);
    fileField.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));

    final Button searchButton = fileBinding.createFileSearchButton(parent);

    /* file is optional iff import type is 'existing' */
    fileBinding.setIsOptional(m_data.getStyleImportType() != StyleImport.selectExisting);

    // final DataBindingContext bindingContext = m_binding.getBindingContext();
    m_data.addPropertyChangeListener(ImportShapeFileData.PROPERTY_STYLE_IMPORT_TYPE,
            new PropertyChangeListener() {
                @Override
                public void propertyChange(final PropertyChangeEvent evt) {
                    final IObservableValue validationStatus = fileBinding.getFileBinding()
                            .getValidationStatus();

                    fileBinding.setIsOptional(evt.getNewValue() != StyleImport.selectExisting);

                    // If style file is currently bad, clear it now, else the error message remains
                    final IStatus value = (IStatus) validationStatus.getValue();
                    if (value != null && !value.isOK() && evt.getNewValue() != StyleImport.selectExisting)
                        modelFile.setValue(null);

                    // we need to force revalidation here, but how...?!
                    fileBinding.getFileBinding().validateTargetToModel();
                }
            });

    /* Enablement */
    final IObservableValue modelEnablement = BeansObservables.observeValue(m_data,
            ImportShapeFileData.PROPERTY_STYLE_CONTROLS_ENABLED);

    final IObservableValue targetLabelEnablement = SWTObservables.observeEnabled(styleLabel);
    m_binding.bindValue(targetLabelEnablement, modelEnablement);

    final IObservableValue targetFieldEnablement = SWTObservables.observeEnabled(fileField);
    m_binding.bindValue(targetFieldEnablement, modelEnablement);

    final IObservableValue targetButtonEnablement = SWTObservables.observeEnabled(searchButton);
    m_binding.bindValue(targetButtonEnablement, modelEnablement);

    return fileBinding;
}