Example usage for javax.swing JTextField setCaretPosition

List of usage examples for javax.swing JTextField setCaretPosition

Introduction

In this page you can find the example usage for javax.swing JTextField setCaretPosition.

Prototype

@BeanProperty(bound = false, description = "the caret position")
public void setCaretPosition(int position) 

Source Link

Document

Sets the position of the text insertion caret for the TextComponent.

Usage

From source file:edu.ku.brc.specify.tasks.subpane.wb.SGRResultsForForm.java

public void refresh() {
    if (currentIndex < 0)
        return;/*from   w ww . ja  v a  2  s .c o m*/

    removeAll();
    repaint();

    if (!sgrPlugin.isReady()) {
        showMessage("SGR_NO_MATCHER");
        return;
    }

    setCursor(new Cursor(Cursor.WAIT_CURSOR));
    new SwingWorker<MatchResults, Void>() {
        private int index = currentIndex;

        @Override
        protected MatchResults doInBackground() throws Exception {
            int modelIndex = workbenchPaneSS.getSpreadSheet().convertRowIndexToModel(index);
            WorkbenchRow row = workbench.getRow(modelIndex);
            return isEmpty(row) ? null : sgrPlugin.doQuery(row);
        }

        @Override
        protected void done() {
            // if we changed indexes in the meantime, don't show this result.
            if (index != currentIndex)
                return;
            //removeAll();

            try {
                results = get();
            } catch (CancellationException e) {
                return;
            } catch (InterruptedException e) {
                return;
            } catch (ExecutionException e) {
                sgrFailed(e);
                setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                return;
            }

            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            if (results == null || results.matches.size() < 1) {
                showMessage("SGR_NO_RESULTS");
                return;
            }

            float maxScore = sgrPlugin.getColorizer().getMaxScore();
            if (maxScore == 0.0f)
                maxScore = 22.0f;

            StringBuilder columns = new StringBuilder("right:max(50dlu;p)");
            for (Match result : results) {
                columns.append(", 4dlu, 150dlu:grow");
            }

            String[] fields = columnOrdering.getFields();
            StringBuilder rows = new StringBuilder();
            for (int i = 0; i < fields.length - 1; i++) {
                rows.append("p, 4dlu,");
            }
            rows.append("p");

            FormLayout layout = new FormLayout(columns.toString(), rows.toString());
            PanelBuilder builder = new PanelBuilder(layout, SGRResultsForForm.this);
            CellConstraints cc = new CellConstraints();

            int y = 1;
            for (String heading : columnOrdering.getHeadings()) {
                builder.addLabel(heading + ":", cc.xy(1, y));
                y += 2;
            }

            int x = 3;
            for (Match result : results) {
                y = 1;
                for (String field : fields) {
                    String value;
                    Color color;
                    if (field.equals("id")) {
                        value = result.match.id;
                        color = SGRColors.colorForScore(result.score, maxScore);
                    } else if (field.equals("score")) {
                        value = String.format("%1$.2f", result.score);
                        color = SGRColors.colorForScore(result.score, maxScore);
                    } else {
                        value = StringUtils.join(result.match.getFieldValues(field).toArray(), "; ");
                        Float fieldContribution = result.fieldScoreContributions().get(field);
                        color = SGRColors.colorForScore(result.score, maxScore, fieldContribution);
                    }

                    JTextField textField = new JTextField(value);
                    textField.setBackground(color);
                    textField.setEditable(false);
                    textField.setCaretPosition(0);
                    builder.add(textField, cc.xy(x, y));
                    y += 2;
                }
                x += 2;
            }
            getParent().validate();
        }
    }.execute();
    UsageTracker.incrUsageCount("SGR.MatchRow");
}

From source file:com.ejie.uda.jsonI18nEditor.Editor.java

private void setupUI() {
    setTitle(TITLE);//w  ww .j  av  a  2  s  .  co  m
    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    addWindowListener(new EditorWindowListener());

    setIconImages(Lists.newArrayList(getResourceImage("images/icon-512.png"),
            getResourceImage("images/icon-256.png"), getResourceImage("images/icon-128.png"),
            getResourceImage("images/icon-64.png"), getResourceImage("images/icon-48.png"),
            getResourceImage("images/icon-32.png"), getResourceImage("images/icon-24.png"),
            getResourceImage("images/icon-20.png"), getResourceImage("images/icon-16.png")));

    translationsPanel = new JPanel(new BorderLayout());
    translationTree = new TranslationTree(this);
    translationTree.addTreeSelectionListener(new TranslationTreeNodeSelectionListener());
    translationField = new TranslationField();
    translationField.addKeyListener(new TranslationFieldKeyListener());
    translationsPanel.add(new JScrollPane(translationTree));
    translationsPanel.add(translationField, BorderLayout.SOUTH);

    resourcesPanel = new JScrollablePanel(true, false);
    resourcesPanel.setLayout(new BoxLayout(resourcesPanel, BoxLayout.Y_AXIS));
    resourcesPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

    resourcesScrollPane = new JScrollPane(resourcesPanel);
    resourcesScrollPane.getViewport().setOpaque(false);

    contentPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, translationsPanel, resourcesScrollPane);
    editorMenu = new EditorMenu(this, translationTree);

    Container container = getContentPane();
    container.add(editorMenu, BorderLayout.NORTH);
    container.add(contentPane);

    // Instead of selecting text in text field when applying focus, set caret position to end of input
    KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("permanentFocusOwner",
            e -> {
                if (e.getNewValue() instanceof JTextField) {
                    JTextField field = (JTextField) e.getNewValue();
                    field.setCaretPosition(field.getText().length());
                }
            });
}

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

/**
 * Updates the UI from the data value (assume the data has changed but OK if it hasn't).
 * @param useSession indicates it should create a session
 *//* w  w w .j a  v  a  2s. c  o m*/
private void refreshUIFromData(final boolean useSession) {
    if (this.dataObj != null) {
        if (getter == null) {
            getter = new DataGetterForObj();
        }

        // NOTE: If there was a formatName defined for this then the value coming
        // in will already be correctly formatted.
        // So just set the value if there is a format name.
        Object newVal = this.dataObj;
        if (isEmpty(dataObjFormatterName)) {
            Object[] val = UIHelper.getFieldValues(fieldNames, this.dataObj, getter);

            UIFieldFormatterIFace uiFieldFormatter = textWithQuery.getUiFieldFormatter();
            if (uiFieldFormatter != null) {
                if (val != null && val.length > 0 && val[0] != null) {
                    newVal = uiFieldFormatter.formatFromUI(val[0]).toString();
                } else {
                    newVal = null;
                }
            } else {

                if (StringUtils.isNotEmpty(textWithQuery.getFormat())) {
                    newVal = UIHelper.getFormattedValue(textWithQuery.getFormat(), val);
                } else {
                    newVal = this.dataObj;
                }
            }
        } else {
            DataProviderSessionIFace localSession = null;
            try {
                localSession = DataProviderFactory.getInstance().createSession();
                newVal = DataObjFieldFormatMgr.getInstance().format(this.dataObj, dataObjFormatterName);
                if (newVal == null || "".equals(newVal.toString().trim())) {
                    newVal = this.tableInfo.getTitle() + ":" + dataObj.getId(); //fixes bug 10150. Kinder, gentler, more informative text might be preferable.
                }

            } catch (Exception ex) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ValComboBoxFromQuery.class, ex);
                ex.printStackTrace();
            } finally {
                if (localSession != null) {
                    localSession.close();
                }
            }
        }

        if (newVal != null && textWithQuery != null) {
            valState = UIValidatable.ErrorType.Valid;
            textWithQuery.setSelectedId(dataObj != null ? dataObj.getId() : null); // needs to be done before and after

            final JTextField tf = textWithQuery.getTextField();
            // rods 08/18/08 - doesn't seem to be needed it is already set correctly
            //
            // 02/06/09 - Commented out because it is causing the idList to be cleared
            // If you turn it back on make sure you turn on ignoreDocChange in the TextFieldWithQuery
            //
            // 02/10/09 - rods - Instead of call seTText directly on the TextField, it is called on the TextFieldWithQuery
            // which disables Doc change notifications
            textWithQuery.setText(newVal.toString());

            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    tf.setSelectionStart(-1);
                    tf.setSelectionEnd(-1);
                    tf.setCaretPosition(0);
                }

            });

            textWithQuery.setSelectedId(dataObj != null ? dataObj.getId() : null);

            if (editBtn != null) {
                editBtn.setEnabled(true);
            }
            if (cloneBtn != null) {
                //cloneBtn.setEnabled(false);
                cloneBtn.setEnabled(dataObj != null || textWithQuery.getSelectedId() != null);
            }
        } else {
            if (textWithQuery != null) {
                textWithQuery.clearSelection();
            }
            valState = UIValidatable.ErrorType.Incomplete;
        }

    } else {
        if (textWithQuery != null) {
            textWithQuery.clearSelection();
        }
        valState = UIValidatable.ErrorType.Incomplete;
        if (editBtn != null) {
            editBtn.setEnabled(false);
        }
        if (cloneBtn != null) {
            cloneBtn.setEnabled(false);
        }
        if (textWithQuery != null && textWithQuery.getTextField() != null) {
            textWithQuery.setText("");
            textWithQuery.getTextField().repaint();
        }
    }
    repaint();
}

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

/**
 * Helper class to set data into a component
 * @param comp the component to get the data
 * @param data the data to be set into the component
 *///from   www .  j a  v a2  s . com
public static void setDataIntoUIComp(final Component comp, final Object data, final String defaultValue) {
    if (comp instanceof GetSetValueIFace) {
        ((GetSetValueIFace) comp).setValue(data, defaultValue);

    } else if (comp instanceof MultiView) {
        ((MultiView) comp).setData(data);

    } else if (comp instanceof JTextField) {
        JTextField tf = (JTextField) comp;
        tf.setText(data == null ? "" : data.toString());
        tf.setCaretPosition(0);

    } else if (comp instanceof JTextArea) {
        //log.debug(name+" - "+comp.getPreferredSize()+comp.getSize());
        ((JTextArea) comp).setText(data == null ? "" : data.toString());

    } else if (comp instanceof JCheckBox) {
        //log.debug(name+" - "+comp.getPreferredSize()+comp.getSize());
        if (data != null) {
            ((JCheckBox) comp).setSelected((data instanceof Boolean) ? ((Boolean) data).booleanValue()
                    : data.toString().equalsIgnoreCase("true"));
        } else {
            ((JCheckBox) comp).setSelected(false);
        }

    } else if (comp instanceof JLabel) {
        ((JLabel) comp).setText(data == null ? "" : data.toString());

    } else if (comp instanceof JComboBox) {
        setComboboxValue((JComboBox) comp, data);

    } else if (comp instanceof JList) {
        setListValue((JList) comp, data);
    }

    // Reset it's state as not being changes,
    // because setting in data will cause the change flag to be set
    if (comp instanceof UIValidatable && StringUtils.isEmpty(defaultValue)) {
        ((UIValidatable) comp).setChanged(false);
    }
}

From source file:base.BasePlayer.Main.java

void setMenuBar() {
    //filemenu.addMouseListener(this);

    //toolmenu.addMouseListener(this);
    filemenu = new JMenu("File");
    toolmenu = new JMenu("Tools");
    help = new JMenu("Help");
    about = new JMenu("About");
    menubar = new JMenuBar();
    //help.addMouseListener(this);
    exit = new JMenuItem("Exit");
    manual = new JButton("Online manual");
    manual.addActionListener(new ActionListener() {

        @Override/* w  w  w . j a v  a  2  s. co  m*/
        public void actionPerformed(ActionEvent arg0) {
            Main.gotoURL("https://baseplayer.fi/BPmanual");
        }

    });
    //   opensamples = new JMenuItem("Add samples");
    zoomout = new JButton("Zoom out");
    back = new JButton("<<");
    forward = new JButton(">>");
    manage = new JButton("Variant Manager");
    openvcfs = new JMenuItem("Add VCFs", open);
    openbams = new JMenuItem("Add BAMs", open);
    average = new JMenuItem("Coverage calculator");
    update = new JMenuItem("Update");
    update.setVisible(false);
    errorlog = new JMenuItem("View log");
    //helpLabel = new JLabel("This is pre-release version of BasePlayer\nContact: help@baseplayer.fi\n\nUniversity of Helsinki");

    addURL = new JMenu("Add from URL");
    urlField = new JTextField("Enter URL");
    addtracks = new JMenuItem("Add tracks");
    fromURL = new JMenuItem("Add track from URL");
    addcontrols = new JMenuItem("Add controls");
    pleiadesButton = new JMenuItem("PLEIADES");
    saveProject = new JMenuItem("Save project");
    saveProjectAs = new JMenuItem("Save project as...");
    openProject = new JMenuItem("Open project");
    clear = new JMenuItem("Clear data");
    clearMemory = new JMenuItem("Clean memory");
    //   welcome = new JMenuItem("Welcome screen");
    filemenu.add(openvcfs);
    filemenu.add(openbams);
    variantCaller = new JMenuItem("Variant Caller");
    tbrowser = new JMenuItem("Table Browser");
    bconvert = new JMenuItem("BED converter");
    peakCaller = new JMenuItem("Peak Caller");
    addtracks = new JMenuItem("Add tracks", open);
    filemenu.add(addtracks);
    addcontrols = new JMenuItem("Add controls", open);
    filemenu.add(addcontrols);
    filemenu.add(fromURL);
    if (pleiades) {
        pleiadesButton.setPreferredSize(buttonDimension);
        pleiadesButton.addActionListener(this);

        filemenu.add(pleiadesButton);
    }

    filemenu.add(new JSeparator());
    openProject = new JMenuItem("Open project", open);
    filemenu.add(openProject);
    saveProject = new JMenuItem("Save project", save);
    filemenu.add(saveProject);
    saveProjectAs = new JMenuItem("Save project as...", save);
    filemenu.add(saveProjectAs);
    filemenu.add(new JSeparator());
    filemenu.add(genome);
    filemenu.add(update);
    filemenu.add(clear);
    filemenu.add(new JSeparator());
    filemenu.add(exit);
    exit.addActionListener(this);
    menubar.add(filemenu);
    manage.addActionListener(this);
    manage.addMouseListener(this);
    update.addActionListener(this);
    average.addActionListener(this);
    average.setEnabled(false);
    average.setToolTipText("No bam/cram files opened");
    tbrowser.addActionListener(this);
    bconvert.addActionListener(this);
    toolmenu.add(tbrowser);
    toolmenu.add(average);
    toolmenu.add(variantCaller);
    toolmenu.add(bconvert);
    fromURL.addMouseListener(this);
    fromURL.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {

            final JPopupMenu menu = new JPopupMenu();
            final JTextField area = new JTextField();
            JButton add = new JButton("Fetch");
            JLabel label = new JLabel("Paste track URL below");
            JScrollPane menuscroll = new JScrollPane();
            add.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        String urltext = area.getText().trim();
                        Boolean size = true;
                        if (urltext.contains("pleiades")) {
                            openPleiades(urltext);
                            return;
                        }
                        if (!FileRead.isTrackFile(urltext)) {
                            showError("The file format is not supported.\n"
                                    + "Supported formats: bed, bigwig, bigbed, gff, bedgraph", "Error");
                            return;

                        }
                        if (!urltext.toLowerCase().endsWith(".bw") && !urltext.toLowerCase().endsWith(".bigwig")
                                && !urltext.toLowerCase().endsWith(".bb")
                                && !urltext.toLowerCase().endsWith(".bigbed")) {
                            URL url = null;
                            try {
                                url = new URL(urltext);
                            } catch (Exception ex) {
                                menu.setVisible(false);
                                Main.showError("Please paste whole url (protocol included)", "Error");
                                return;
                            }
                            URL testurl = url;
                            HttpURLConnection huc = (HttpURLConnection) testurl.openConnection();
                            huc.setRequestMethod("HEAD");
                            int responseCode = huc.getResponseCode();

                            if (responseCode != 404) {

                                SeekableStream stream = SeekableStreamFactory.getInstance().getStreamFor(url);
                                TabixReader tabixReader = null;
                                String index = null;

                                try {
                                    if (stream.length() / (double) 1048576 >= Settings.settings
                                            .get("bigFile")) {
                                        size = false;
                                    }
                                    tabixReader = new TabixReader(urltext, urltext + ".tbi", stream);

                                    index = urltext + ".tbi";
                                    testurl = new URL(index);
                                    huc = (HttpURLConnection) testurl.openConnection();
                                    huc.setRequestMethod("HEAD");
                                    responseCode = huc.getResponseCode();

                                    if (responseCode == 404) {
                                        menu.setVisible(false);
                                        Main.showError("Index file (.tbi) not found in the URL.", "Error");

                                        return;
                                    }

                                } catch (Exception ex) {
                                    try {
                                        tabixReader = new TabixReader(urltext,
                                                urltext.substring(0, urltext.indexOf(".gz")) + ".tbi", stream);
                                        index = urltext.substring(0, urltext.indexOf(".gz")) + ".tbi";
                                    } catch (Exception exc) {
                                        menu.setVisible(false);
                                        Main.showError("Could not read tabix file.", "Error");
                                    }
                                }
                                if (tabixReader != null && index != null) {
                                    stream.close();
                                    tabixReader.close();
                                    menu.setVisible(false);
                                    FileRead filereader = new FileRead();
                                    filereader.readBED(urltext, index, size);

                                }

                            } else {
                                menu.setVisible(false);
                                Main.showError("Not a valid URL", "Error");
                            }

                        } else {
                            URL url = null;
                            try {
                                url = new URL(urltext);
                            } catch (Exception ex) {
                                Main.showError("Please paste whole url (protocol included)", "Error");
                                return;
                            }
                            final URL testurl = url;
                            HttpURLConnection huc = (HttpURLConnection) testurl.openConnection();
                            huc.setRequestMethod("HEAD");
                            int responseCode = huc.getResponseCode();

                            if (responseCode != 404) {
                                menu.setVisible(false);
                                FileRead filereader = new FileRead();

                                filereader.readBED(urltext, "nan", true);

                            } else {
                                menu.setVisible(false);
                                Main.showError("Not a valid URL", "Error");
                            }

                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }

            });
            area.setFont(Main.menuFont);
            //area.setText("https://baseplayer.fi/tracks/Mappability_1000Genomes_pilot_mask.bed.gz");
            menu.add(label);
            menu.add(menuscroll);
            menu.add(add);
            area.setPreferredSize(new Dimension(300, Main.defaultFontSize + 8));

            area.setCaretPosition(0);
            area.revalidate();
            menuscroll.getViewport().add(area);
            area.requestFocus();
            menu.pack();

            menu.show(frame, mouseX + 20, fromURL.getY());
        }

    });
    //toolmenu.add(peakCaller);
    variantCaller.setToolTipText("No bam/cram files opened");
    variantCaller.addActionListener(this);
    variantCaller.setEnabled(false);
    peakCaller.setEnabled(true);
    peakCaller.addActionListener(this);
    settings.addActionListener(this);
    clearMemory.addActionListener(this);
    errorlog.addActionListener(this);
    toolmenu.add(clearMemory);
    toolmenu.add(errorlog);
    toolmenu.add(new JSeparator());
    toolmenu.add(settings);
    menubar.add(toolmenu);
    menubar.add(manage);
    area = new JEditorPane();

    String infotext = "<html><h2>BasePlayer</h2>This is a version " + version
            + " of BasePlayer (<a href=https://baseplayer.fi>https://baseplayer.fi</a>)<br/> Author: Riku Katainen <br/> University of Helsinki<br/>"
            + "Tumor Genomics Group (<a href=http://research.med.helsinki.fi/gsb/aaltonen/>http://research.med.helsinki.fi/gsb/aaltonen/</a>) <br/> "
            + "Contact: help@baseplayer.fi <br/> <br/>"

            + "Supported filetype for variants is VCF and VCF.gz (index file will be created if missing)<br/> "
            + "Supported filetypes for reads are BAM and CRAM. Index files required (.bai or .crai). <br/> "
            + "Supported filetypes for additional tracks are BED(.gz), GFF.gz, BedGraph, BigWig, BigBed.<br/> (tabix index required for bgzipped files). <br/><br/> "

            + "For optimal usage, you should have vcf.gz and bam -files for each sample. <br/> "
            + "e.g. in case you have a sample named as sample1, name all files similarly and <br/>"
            + "place in the same folder:<br/>" + "sample1.vcf.gz<br/>" + "sample1.vcf.gz.tbi<br/>"
            + "sample1.bam<br/>" + "sample1.bam.bai<br/><br/>"
            + "When you open sample1.vcf.gz, sample1.bam is recognized and opened<br/>"
            + "on the same track.<br/><br/>"
            + "Instructional videos can be viewed at our <a href=https://www.youtube.com/channel/UCywq-T7W0YPzACyB4LT7Q3g> Youtube channel</a>";
    area = new JEditorPane();
    area.setEditable(false);
    area.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
    area.setText(infotext);
    area.setFont(Main.menuFont);
    area.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(HyperlinkEvent hyperlinkEvent) {
            HyperlinkEvent.EventType type = hyperlinkEvent.getEventType();
            final URL url = hyperlinkEvent.getURL();
            if (type == HyperlinkEvent.EventType.ACTIVATED) {
                Main.gotoURL(url.toString());
            }
        }
    });

    about.add(area);
    about.addMouseListener(this);
    help.add(about);
    help.add(manual);
    menubar.add(help);
    JLabel emptylab = new JLabel("  ");
    emptylab.setEnabled(false);
    emptylab.setOpaque(false);
    menubar.add(emptylab);

    chromosomeDropdown.setBorder(BorderFactory.createMatteBorder(1, 0, 1, 1, Color.lightGray));
    chromosomeDropdown.setBorder(BorderFactory.createCompoundBorder(chromosomeDropdown.getBorder(),
            BorderFactory.createEmptyBorder(0, 0, 0, 0)));

    chromlabel.setToolTipText("Current chromosome");
    chromlabel.setFocusable(false);
    chromlabel.addMouseListener(this);
    chromlabel.setBackground(Color.white);
    chromlabel.setEditable(false);
    chromlabel.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 0, Color.lightGray));
    chromlabel.setBorder(BorderFactory.createCompoundBorder(chromlabel.getBorder(),
            BorderFactory.createEmptyBorder(0, 0, 0, 0)));
    menubar.add(chromlabel);
    chromosomeDropdown.setBackground(Color.white);
    chromosomeDropdown.setToolTipText("Current chromosome");
    menubar.add(chromosomeDropdown);
    JLabel empty3 = new JLabel("  ");
    empty3.setEnabled(false);
    empty3.setOpaque(false);
    menubar.add(empty3);
    menubar.add(back);
    menubar.add(searchField);
    searchField.setForeground(Color.gray);
    searchField.setBorder(BorderFactory.createCompoundBorder(searchField.getBorder(),
            BorderFactory.createEmptyBorder(0, 0, 0, 0)));

    searchField.addMouseListener(this);
    menubar.add(back);
    menubar.add(searchField);
    searchField.setForeground(Color.gray);

    back.addMouseListener(this);
    back.setToolTipText("Back");
    forward.addMouseListener(this);
    forward.setToolTipText("Forward");
    back.setEnabled(false);
    forward.setEnabled(false);

    searchField.addMouseListener(this);

    menubar.add(back);
    menubar.add(searchField);
    searchField.setForeground(Color.gray);
    back.addMouseListener(this);
    forward.addMouseListener(this);
    back.setEnabled(false);
    forward.setEnabled(false);
    forward.setMargin(new Insets(0, 2, 0, 2));
    back.setMargin(new Insets(0, 2, 0, 2));
    menubar.add(forward);
    JLabel empty4 = new JLabel("  ");
    empty4.setOpaque(false);
    empty4.setEnabled(false);
    menubar.add(empty4);
    menubar.add(zoomout);
    JLabel empty5 = new JLabel("  ");
    empty5.setEnabled(false);
    empty5.setOpaque(false);
    menubar.add(empty5);
    positionField.setEditable(false);
    positionField.setBackground(new Color(250, 250, 250));

    positionField.setMargin(new Insets(0, 2, 0, 0));
    positionField.setBorder(BorderFactory.createCompoundBorder(widthLabel.getBorder(),
            BorderFactory.createEmptyBorder(0, 0, 0, 0)));
    menubar.add(positionField);
    widthLabel.setEditable(false);
    widthLabel.setBackground(new Color(250, 250, 250));
    widthLabel.setMargin(new Insets(0, 2, 0, 0));
    widthLabel.setBorder(BorderFactory.createCompoundBorder(widthLabel.getBorder(),
            BorderFactory.createEmptyBorder(0, 0, 0, 0)));
    JLabel empty6 = new JLabel("  ");
    empty6.setEnabled(false);
    empty6.setOpaque(false);
    menubar.add(empty6);
    menubar.add(widthLabel);
    JLabel empty7 = new JLabel("  ");
    empty7.setOpaque(false);
    empty7.setEnabled(false);
    menubar.add(empty7);
}

From source file:org.yccheok.jstock.gui.AutoCompleteJComboBox.java

private DocumentListener getDocumentListener() {
    return new DocumentListener() {
        private volatile boolean ignore = false;

        @Override//  w w w  .  jav  a 2  s  . c o  m
        public void insertUpdate(DocumentEvent e) {
            try {
                final String string = e.getDocument().getText(0, e.getDocument().getLength()).trim();
                handle(string);
            } catch (BadLocationException ex) {
                log.error(null, ex);
            }
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            try {
                final String string = e.getDocument().getText(0, e.getDocument().getLength()).trim();
                handle(string);
            } catch (BadLocationException ex) {
                log.error(null, ex);
            }
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            try {
                final String string = e.getDocument().getText(0, e.getDocument().getLength()).trim();
                handle(string);
            } catch (BadLocationException ex) {
                log.error(null, ex);
            }
        }

        private void _handle(final String string) {
            // We are no longer busy.
            busySubject.notify(AutoCompleteJComboBox.this, false);

            if (AutoCompleteJComboBox.this.getSelectedItem() != null) {
                // Remember to use toString(). As getSelectedItem() can be
                // either StockInfo, or ResultSet.
                if (AutoCompleteJComboBox.this.getSelectedItem().toString().equals(string)) {
                    // We need to differentiate, whether "string" is from user
                    // typing, or drop down list selection. This is because when
                    // user perform selection, document change event will be triggered
                    // too. When string is from drop down list selection, user
                    // are not expecting any auto complete suggestion. Return early.
                    return;
                }
            }

            if (string.isEmpty()) {
                // Empty string. Return early. Do not perform hidePopup and
                // removeAllItems right here. As when user performs list
                // selection, previous text field item will be removed, and
                // cause us fall into this scope. We do not want to hidePopup
                // and removeAllItems when user is selecting his item.
                //
                // hidePopup and removeAllItems when user clears off all items
                // in text field, will be performed through keyReleased.
                return;
            }

            // Use to avoid endless DocumentEvent triggering.
            ignore = true;
            // During _handle operation, there will be a lot of ListDataListeners
            // trying to modify the content of our text field. We will not allow
            // them to do so.
            //
            // Without setReadOnly(true), when we type the first character "w", IME
            // will suggest ... However, when we call removeAllItems and addItem,
            // JComboBox will "commit" this suggestion to JComboBox's text field.
            // Hence, if we continue to type second character "m", the string displayed
            // at JComboBox's text field will be ...
            //
            AutoCompleteJComboBox.this.jComboBoxEditor.setReadOnly(true);

            // Must hide popup. If not, the pop up windows will not be
            // resized.
            AutoCompleteJComboBox.this.hidePopup();
            AutoCompleteJComboBox.this.removeAllItems();

            boolean shouldShowPopup = false;

            if (AutoCompleteJComboBox.this.stockInfoDatabase != null) {
                java.util.List<StockInfo> stockInfos = greedyEnabled
                        ? stockInfoDatabase.greedySearchStockInfos(string)
                        : stockInfoDatabase.searchStockInfos(string);

                sortStockInfosIfPossible(stockInfos);

                if (stockInfos.isEmpty() == false) {
                    // Change to offline mode before adding any item.
                    changeMode(Mode.Offline);
                }

                for (StockInfo stockInfo : stockInfos) {
                    AutoCompleteJComboBox.this.addItem(stockInfo);
                    shouldShowPopup = true;
                }

                if (shouldShowPopup) {
                    AutoCompleteJComboBox.this.showPopup();
                } else {

                } // if (shouldShowPopup)
            } // if (AutoCompleteJComboBox.this.stockInfoDatabase != null)

            if (shouldShowPopup == false) {
                // OK. We found nothing from offline database. Let's
                // ask help from online database.
                // We are busy contacting server right now.

                // TODO
                // Only enable ajaxYahooSearchEngineMonitor, till we solve
                // http://sourceforge.net/apps/mediawiki/jstock/index.php?title=TechnicalDisability
                busySubject.notify(AutoCompleteJComboBox.this, true);

                canRemoveAllItems = true;
                ajaxYahooSearchEngineMonitor.clearAndPut(string);
                ajaxGoogleSearchEngineMonitor.clearAndPut(string);
            }

            // When we are in windows look n feel, the text will always be selected. We do not want that.
            final Component component = AutoCompleteJComboBox.this.getEditor().getEditorComponent();
            if (component instanceof JTextField) {
                JTextField jTextField = (JTextField) component;
                jTextField.setSelectionStart(jTextField.getText().length());
                jTextField.setSelectionEnd(jTextField.getText().length());
                jTextField.setCaretPosition(jTextField.getText().length());
            }

            // Restore.
            AutoCompleteJComboBox.this.jComboBoxEditor.setReadOnly(false);
            ignore = false;
        }

        private void handle(final String string) {
            if (ignore) {
                return;
            }

            // Submit to GUI event queue. Used to avoid
            // Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Attempt to mutate in notification
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    _handle(string);
                }
            });
        }
    };
}

From source file:org.yccheok.jstock.gui.NewBuyTransactionJDialog.java

private MouseListener getJFormattedTextFieldMouseListener() {
    MouseListener ml = new MouseAdapter() {
        @Override//from www .j a  v a  2  s  .c om
        public void mousePressed(final MouseEvent e) {
            if (e.getClickCount() == 2) {
                // Ignore double click.
                return;
            }

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    JTextField tf = (JTextField) e.getSource();
                    int offset = tf.viewToModel(e.getPoint());
                    tf.setCaretPosition(offset);
                }
            });
        }
    };
    return ml;
}