Example usage for javax.swing JTextField getText

List of usage examples for javax.swing JTextField getText

Introduction

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

Prototype

public String getText() 

Source Link

Document

Returns the text contained in this TextComponent.

Usage

From source file:com.floreantpos.bo.ui.explorer.ModifierExplorer.java

private JPanel buildSearchForm() {
    List<MenuModifierGroup> grpName;
    JPanel panel = new JPanel();
    panel.setLayout(new MigLayout("", "[][]30[][]30[]", "[]20[]")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    JLabel nameLabel = new JLabel(Messages.getString("ModifierExplorer.3")); //$NON-NLS-1$
    JLabel groupLabel = new JLabel(Messages.getString("ModifierExplorer.4")); //$NON-NLS-1$
    final JTextField nameField = new JTextField(15);
    grpName = MenuModifierGroupDAO.getInstance().findAll();
    final JComboBox cbGroup = new JComboBox();
    cbGroup.addItem(Messages.getString("ModifierExplorer.5")); //$NON-NLS-1$
    for (MenuModifierGroup s : grpName) {
        cbGroup.addItem(s);//from  ww w .j  a v a  2  s .c  o  m
    }

    JButton searchBttn = new JButton(Messages.getString("ModifierExplorer.6")); //$NON-NLS-1$
    panel.add(nameLabel, "align label"); //$NON-NLS-1$
    panel.add(nameField);
    panel.add(groupLabel);
    panel.add(cbGroup);
    panel.add(searchBttn);

    TitledBorder title;
    Border loweredetched;
    loweredetched = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
    title = BorderFactory.createTitledBorder(loweredetched, Messages.getString("ModifierExplorer.8")); //$NON-NLS-1$
    title.setTitleJustification(TitledBorder.LEFT);
    panel.setBorder(title);
    searchBttn.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            List<MenuModifier> modifierList;
            String txName = nameField.getText();
            Object selectedItem = cbGroup.getSelectedItem();
            if (selectedItem instanceof MenuModifierGroup) {
                modifierList = ModifierDAO.getInstance().findModifier(txName, (MenuModifierGroup) selectedItem);
            } else {
                modifierList = ModifierDAO.getInstance().findModifier(txName, null);
            }

            setModifierList(modifierList);
        }
    });
    return panel;
}

From source file:EditorPaneTest.java

public EditorPaneFrame() {
    setTitle("EditorPaneTest");
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    final Stack<String> urlStack = new Stack<String>();
    final JEditorPane editorPane = new JEditorPane();
    final JTextField url = new JTextField(30);

    // set up hyperlink listener

    editorPane.setEditable(false);/*from ww w.jav  a 2s.  c o  m*/
    editorPane.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(HyperlinkEvent event) {
            if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                try {
                    // remember URL for back button
                    urlStack.push(event.getURL().toString());
                    // show URL in text field
                    url.setText(event.getURL().toString());
                    editorPane.setPage(event.getURL());
                } catch (IOException e) {
                    editorPane.setText("Exception: " + e);
                }
            }
        }
    });

    // set up checkbox for toggling edit mode

    final JCheckBox editable = new JCheckBox();
    editable.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            editorPane.setEditable(editable.isSelected());
        }
    });

    // set up load button for loading URL

    ActionListener listener = new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            try {
                // remember URL for back button
                urlStack.push(url.getText());
                editorPane.setPage(url.getText());
            } catch (IOException e) {
                editorPane.setText("Exception: " + e);
            }
        }
    };

    JButton loadButton = new JButton("Load");
    loadButton.addActionListener(listener);
    url.addActionListener(listener);

    // set up back button and button action

    JButton backButton = new JButton("Back");
    backButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            if (urlStack.size() <= 1)
                return;
            try {
                // get URL from back button
                urlStack.pop();
                // show URL in text field
                String urlString = urlStack.peek();
                url.setText(urlString);
                editorPane.setPage(urlString);
            } catch (IOException e) {
                editorPane.setText("Exception: " + e);
            }
        }
    });

    add(new JScrollPane(editorPane), BorderLayout.CENTER);

    // put all control components in a panel

    JPanel panel = new JPanel();
    panel.add(new JLabel("URL"));
    panel.add(url);
    panel.add(loadButton);
    panel.add(backButton);
    panel.add(new JLabel("Editable"));
    panel.add(editable);

    add(panel, BorderLayout.SOUTH);
}

From source file:edu.ku.brc.af.ui.PasswordStrengthUI.java

/**
 * Hooks up a Password field to the Strength UI
 * @param pwdTF the password text field to be be hooked up to this
 * @param btn optional button that will be enabled when the PasswordText is not empty
 *//*  ww w.j  a  v a  2s . com*/
public void setPasswordField(final JTextField pwdTF, final JButton btn) {
    DocumentListener listener = new DocumentAdaptor() {
        @Override
        protected void changed(DocumentEvent e) {
            String txt = ((JTextField) pwdTF).getText();

            if (StringUtils.isEmpty(txt)) {
                initialSet = true;
                doPainting = false;
                for (JCheckBox cbx : cbxs) {
                    cbx.setSelected(false);
                }

            } else if (initialSet) {
                initialSet = false;
            } else {
                doPainting = true;
            }

            if (btn != null) {
                btn.setEnabled(!txt.isEmpty());
            }

            if (doPainting) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        checkStrength(pwdTF.getText()); // ignore return boolean
                        colorPanel.repaint();
                    }
                });
            }
        }
    };

    pwdTF.getDocument().addDocumentListener(listener);
}

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

/**
 * /*from   w  w  w. j a v a2s  .co m*/
 */
protected void showGotoRecDlg() {
    JTextField tf = UIHelper.createTextField(5);

    CellConstraints cc = new CellConstraints();
    DefaultFormBuilder p = new DefaultFormBuilder(new FormLayout("p,2px,f:p:g", "p"));
    p.add(UIHelper.createI18NLabel("RS_NUM_LBL"), cc.xy(1, 1));
    p.add(tf, cc.xy(3, 1));
    p.setDefaultDialogBorder();

    CustomDialog dlg = new CustomDialog((Frame) null, "", true, CustomDialog.OKCANCEL, p.getPanel());
    dlg.setCustomTitleBar(getResourceString("RS_JUMP_TITLE"));

    UIHelper.centerAndShow(dlg);
    if (!dlg.isCancelled()) {
        String recNumStr = tf.getText();
        if (!recNumStr.isEmpty() && StringUtils.isNumeric(recNumStr)) {
            try {
                int recNum = Integer.parseInt(recNumStr);
                if (recNum > 0 && recNum <= lastInx) {
                    setIndex(recNum - 1);
                }
            } catch (Exception ex) {
            }
        }
    }
}

From source file:e3fraud.gui.MainWindow.java

public void actionPerformed(ActionEvent e) {

    //Handle open button action.
    if (e.getSource() == openButton) {
        int returnVal = fc.showOpenDialog(MainWindow.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //parse file
            this.baseModel = FileParser.parseFile(file);
            log.append(currentTime.currentTime() + " Opened: " + file.getName() + "." + newline);
        } else {/* w  ww  .j a va2s  .  c  o m*/
            log.append(currentTime.currentTime() + " Open command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());

        //handle Generate button
    } else if (e.getSource() == generateButton) {
        if (this.baseModel != null) {
            //have the user indicate the ToA via pop-up
            JFrame frame1 = new JFrame("Select Target of Assessment");
            Map<String, Resource> actorsMap = this.baseModel.getActorsMap();
            String selectedActorString = (String) JOptionPane.showInputDialog(frame1,
                    "Which actor's perspective are you taking?", "Choose main actor",
                    JOptionPane.QUESTION_MESSAGE, null, actorsMap.keySet().toArray(),
                    actorsMap.keySet().toArray()[0]);
            if (selectedActorString == null) {
                log.append(currentTime.currentTime() + " Attack generation cancelled!" + newline);
            } else {
                lastSelectedActorString = selectedActorString;
                //have the user select a need via pop-up
                JFrame frame2 = new JFrame("Select graph parameter");
                Map<String, Resource> needsMap = this.baseModel.getNeedsMap();
                String selectedNeedString = (String) JOptionPane.showInputDialog(frame2,
                        "What do you want to use as parameter?", "Choose need to parametrize",
                        JOptionPane.QUESTION_MESSAGE, null, needsMap.keySet().toArray(),
                        needsMap.keySet().toArray()[0]);
                if (selectedNeedString == null) {
                    log.append("Attack generation cancelled!" + newline);
                } else {
                    lastSelectedNeedString = selectedNeedString;
                    //have the user select occurence interval via pop-up
                    JTextField xField = new JTextField("1", 4);
                    JTextField yField = new JTextField("500", 4);
                    JPanel myPanel = new JPanel();
                    myPanel.add(new JLabel("Mininum occurences:"));
                    myPanel.add(xField);
                    myPanel.add(Box.createHorizontalStrut(15)); // a spacer
                    myPanel.add(new JLabel("Maximum occurences:"));
                    myPanel.add(yField);
                    int result = JOptionPane.showConfirmDialog(null, myPanel,
                            "Please Enter occurence rate interval", JOptionPane.OK_CANCEL_OPTION);

                    if (result == JOptionPane.CANCEL_OPTION) {
                        log.append("Attack generation cancelled!" + newline);
                    } else if (result == JOptionPane.OK_OPTION) {
                        startValue = Integer.parseInt(xField.getText());
                        endValue = Integer.parseInt(yField.getText());

                        selectedNeed = needsMap.get(selectedNeedString);
                        selectedActor = actorsMap.get(selectedActorString);

                        //Have a Worker thread to the time-consuming generation and raking (to not freeze the GUI)
                        GenerationWorker generationWorker = new GenerationWorker(baseModel, selectedActorString,
                                selectedActor, selectedNeed, selectedNeedString, startValue, endValue, log,
                                lossButton, gainButton, lossGainButton, gainLossButton, groupingButton,
                                collusionsButton) {
                            //make it so that when Worker is done
                            @Override
                            protected void done() {
                                try {
                                    progressBar.setVisible(false);
                                    System.err.println("I made it invisible");
                                    //the Worker's result is retrieved
                                    treeModel.setRoot(get());
                                    tree.setModel(treeModel);

                                    tree.updateUI();
                                    tree.collapseRow(1);
                                    //tree.expandRow(0);
                                    tree.setRootVisible(false);
                                    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                                } catch (InterruptedException | ExecutionException ex) {
                                    Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
                                    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                                    log.append("Out of memory; please increase heap size of JVM");
                                    PopUps.infoBox(
                                            "Encountered an error. Most likely out of memory; try increasing the heap size of JVM",
                                            "Error");
                                }
                            }
                        };
                        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                        progressBar.setVisible(true);
                        progressBar.setIndeterminate(true);
                        progressBar.setString("generating...");
                        generationWorker.addPropertyChangeListener(new PropertyChangeListener() {
                            public void propertyChange(PropertyChangeEvent evt) {
                                if ("phase".equals(evt.getPropertyName())) {
                                    progressBar.setMaximum(100);
                                    progressBar.setIndeterminate(false);
                                    progressBar.setString("ranking...");
                                } else if ("progress".equals(evt.getPropertyName())) {
                                    progressBar.setValue((Integer) evt.getNewValue());
                                }
                            }
                        });
                        generationWorker.execute();
                    }
                }
            }
        } else {
            log.append("Load a model file first!" + newline);
        }
    } //handle the refresh button
    else if (e.getSource() == refreshButton) {
        if (lastSelectedNeedString != null && lastSelectedActorString != null) {
            Map<String, Resource> actorsMap = this.baseModel.getActorsMap();
            Map<String, Resource> needsMap = this.baseModel.getNeedsMap();
            selectedNeed = needsMap.get(lastSelectedNeedString);
            selectedActor = actorsMap.get(lastSelectedActorString);

            //Have a Worker thread to the time-consuming generation and raking (to not freeze the GUI)
            GenerationWorker generationWorker = new GenerationWorker(baseModel, lastSelectedActorString,
                    selectedActor, selectedNeed, lastSelectedNeedString, startValue, endValue, log, lossButton,
                    gainButton, lossGainButton, gainLossButton, groupingButton, collusionsButton) {
                //make it so that when Worker is done
                @Override
                protected void done() {
                    try {
                        progressBar.setVisible(false);
                        //the Worker's result is retrieved
                        treeModel.setRoot(get());
                        tree.setModel(treeModel);
                        tree.updateUI();
                        tree.collapseRow(1);
                        //tree.expandRow(0);
                        tree.setRootVisible(false);
                        setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                    } catch (InterruptedException | ExecutionException ex) {
                        Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
                        setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                        log.append("Most likely out of memory; please increase heap size of JVM");
                        PopUps.infoBox(
                                "Encountered an error. Most likely out of memory; try increasing the heap size of JVM",
                                "Error");
                    }
                }
            };
            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            progressBar.setVisible(true);
            progressBar.setIndeterminate(true);
            progressBar.setString("generating...");
            generationWorker.addPropertyChangeListener(new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent evt) {
                    if ("phase".equals(evt.getPropertyName())) {
                        progressBar.setMaximum(100);
                        progressBar.setIndeterminate(false);
                        progressBar.setString("ranking...");
                    } else if ("progress".equals(evt.getPropertyName())) {
                        progressBar.setValue((Integer) evt.getNewValue());
                    }
                }
            });
            generationWorker.execute();

        } else {
            log.append(currentTime.currentTime() + " Nothing to refresh. Generate models first" + newline);
        }

    } //handle show ideal graph button
    else if (e.getSource() == idealGraphButton) {
        if (this.baseModel != null) {
            graph1 = GraphingTool.generateGraph(baseModel, selectedNeed, startValue, endValue, true);//expected graph 
            ChartFrame chartframe1 = new ChartFrame("Ideal results", graph1);
            chartframe1.setPreferredSize(new Dimension(CHART_WIDTH, CHART_HEIGHT));
            chartframe1.pack();
            chartframe1.setLocationByPlatform(true);
            chartframe1.setVisible(true);
        } else {
            log.append(currentTime.currentTime() + " Load a model file first!" + newline);
        }
    } //Handle the graph extend button//Handle the graph extend button
    else if (e.getSource() == expandButton) {
        //make sure there is a graph to show
        if (graph2 == null) {
            log.append(currentTime.currentTime() + " No graph to display. Select one first." + newline);
        } else {
            //this makes sure both graphs have the same y axis:
            //            double lowerBound = min(graph1.getXYPlot().getRangeAxis().getRange().getLowerBound(), graph2.getXYPlot().getRangeAxis().getRange().getLowerBound());
            //            double upperBound = max(graph1.getXYPlot().getRangeAxis().getRange().getUpperBound(), graph2.getXYPlot().getRangeAxis().getRange().getUpperBound());
            //            graph1.getXYPlot().getRangeAxis().setRange(lowerBound, upperBound);
            //            graph2.getXYPlot().getRangeAxis().setRange(lowerBound, upperBound);
            chartPane.removeAll();
            chartPanel = new ChartPanel(graph2);
            chartPanel.setPreferredSize(new Dimension(CHART_WIDTH, CHART_HEIGHT));
            chartPane.add(chartPanel);
            chartPane.add(collapseButton);
            extended = true;
            this.setPreferredSize(new Dimension(this.getWidth() + CHART_WIDTH, this.getHeight()));
            JFrame frame = (JFrame) getRootPane().getParent();
            frame.pack();
        }
    } //Handle the graph collapse button//Handle the graph collapse button
    else if (e.getSource() == collapseButton) {
        System.out.println("resizing by -" + CHART_WIDTH);
        chartPane.removeAll();
        chartPane.add(expandButton);
        this.setPreferredSize(new Dimension(this.getWidth() - CHART_WIDTH, this.getHeight()));
        chartPane.repaint();
        chartPane.revalidate();
        extended = false;
        JFrame frame = (JFrame) getRootPane().getParent();
        frame.pack();
    }
}

From source file:Graphics.SimulationGUI.java

private int convert(JTextField textField) {
    return Integer.parseInt(textField.getText());
}

From source file:Graphics.SimulationGUI.java

private boolean valideInput(JTextField textField) {
    try {//from  ww w.  j a v  a 2 s  .c  o  m
        Integer.parseInt(textField.getText());
    } catch (NumberFormatException e) {
        return false;
    }
    return true;
}

From source file:com.tascape.qa.th.android.driver.App.java

/**
 * The method starts a GUI to let an user inspect element tree and take screenshot when the user is interacting
 * with the app-under-test manually. Please make sure to set timeout long enough for manual interaction.
 *
 * @param timeoutMinutes timeout in minutes to fail the manual steps
 *
 * @throws Exception if case of error/*from www  .j  a v a 2  s.  c om*/
 */
public void interactManually(int timeoutMinutes) throws Exception {
    LOG.info("Start manual UI interaction");
    long end = System.currentTimeMillis() + timeoutMinutes * 60000L;

    AtomicBoolean visible = new AtomicBoolean(true);
    AtomicBoolean pass = new AtomicBoolean(false);
    String tName = Thread.currentThread().getName() + "m";
    SwingUtilities.invokeLater(() -> {
        JDialog jd = new JDialog((JFrame) null, "Manual Device UI Interaction - " + device.getProductDetail());
        jd.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);

        JPanel jpContent = new JPanel(new BorderLayout());
        jd.setContentPane(jpContent);
        jpContent.setPreferredSize(new Dimension(1088, 828));
        jpContent.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        JPanel jpInfo = new JPanel();
        jpContent.add(jpInfo, BorderLayout.PAGE_START);
        jpInfo.setLayout(new BorderLayout());
        {
            JButton jb = new JButton("PASS");
            jb.setForeground(Color.green.darker());
            jb.setFont(jb.getFont().deriveFont(Font.BOLD));
            jpInfo.add(jb, BorderLayout.LINE_START);
            jb.addActionListener(event -> {
                pass.set(true);
                jd.dispose();
                visible.set(false);
            });
        }
        {
            JButton jb = new JButton("FAIL");
            jb.setForeground(Color.red);
            jb.setFont(jb.getFont().deriveFont(Font.BOLD));
            jpInfo.add(jb, BorderLayout.LINE_END);
            jb.addActionListener(event -> {
                pass.set(false);
                jd.dispose();
                visible.set(false);
            });
        }

        JLabel jlTimeout = new JLabel("xxx seconds left", SwingConstants.CENTER);
        jpInfo.add(jlTimeout, BorderLayout.CENTER);
        jpInfo.add(jlTimeout, BorderLayout.CENTER);
        new SwingWorker<Long, Long>() {
            @Override
            protected Long doInBackground() throws Exception {
                while (System.currentTimeMillis() < end) {
                    Thread.sleep(1000);
                    long left = (end - System.currentTimeMillis()) / 1000;
                    this.publish(left);
                }
                return 0L;
            }

            @Override
            protected void process(List<Long> chunks) {
                Long l = chunks.get(chunks.size() - 1);
                jlTimeout.setText(l + " seconds left");
                if (l < 850) {
                    jlTimeout.setForeground(Color.red);
                }
            }
        }.execute();

        JPanel jpResponse = new JPanel(new BorderLayout());
        JPanel jpProgress = new JPanel(new BorderLayout());
        jpResponse.add(jpProgress, BorderLayout.PAGE_START);

        JTextArea jtaJson = new JTextArea();
        jtaJson.setEditable(false);
        jtaJson.setTabSize(4);
        Font font = jtaJson.getFont();
        jtaJson.setFont(new Font("Courier New", font.getStyle(), font.getSize()));

        JTree jtView = new JTree();

        JTabbedPane jtp = new JTabbedPane();
        jtp.add("tree", new JScrollPane(jtView));
        jtp.add("json", new JScrollPane(jtaJson));

        jpResponse.add(jtp, BorderLayout.CENTER);

        JPanel jpScreen = new JPanel();
        jpScreen.setMinimumSize(new Dimension(200, 200));
        jpScreen.setLayout(new BoxLayout(jpScreen, BoxLayout.PAGE_AXIS));
        JScrollPane jsp1 = new JScrollPane(jpScreen);
        jpResponse.add(jsp1, BorderLayout.LINE_START);

        JPanel jpJs = new JPanel(new BorderLayout());
        JTextArea jtaJs = new JTextArea();
        jpJs.add(new JScrollPane(jtaJs), BorderLayout.CENTER);

        JSplitPane jSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, jpResponse, jpJs);
        jSplitPane.setResizeWeight(0.88);
        jpContent.add(jSplitPane, BorderLayout.CENTER);

        JPanel jpLog = new JPanel();
        jpLog.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0));
        jpLog.setLayout(new BoxLayout(jpLog, BoxLayout.LINE_AXIS));

        JCheckBox jcbTap = new JCheckBox("Enable Click", null, false);
        jpLog.add(jcbTap);
        jpLog.add(Box.createHorizontalStrut(8));

        JButton jbLogUi = new JButton("Log Screen");
        jpResponse.add(jpLog, BorderLayout.PAGE_END);
        {
            jpLog.add(jbLogUi);
            jbLogUi.addActionListener((ActionEvent event) -> {
                jtaJson.setText("waiting for screenshot...");
                Thread t = new Thread(tName) {
                    @Override
                    public void run() {
                        LOG.debug("\n\n");
                        try {
                            WindowHierarchy wh = device.loadWindowHierarchy();
                            jtView.setModel(getModel(wh));

                            jtaJson.setText("");
                            jtaJson.append(wh.root.toJson().toString(2));
                            jtaJson.append("\n");

                            File png = device.takeDeviceScreenshot();
                            BufferedImage image = ImageIO.read(png);

                            int w = device.getDisplayWidth();
                            int h = device.getDisplayHeight();

                            BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
                            Graphics2D g2 = resizedImg.createGraphics();
                            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                            g2.drawImage(image, 0, 0, w, h, null);
                            g2.dispose();

                            JLabel jLabel = new JLabel(new ImageIcon(resizedImg));
                            jpScreen.removeAll();
                            jsp1.setPreferredSize(new Dimension(w + 30, h));
                            jpScreen.add(jLabel);

                            jLabel.addMouseListener(new MouseAdapter() {
                                @Override
                                public void mouseClicked(MouseEvent e) {
                                    LOG.debug("clicked at {},{}", e.getPoint().getX(), e.getPoint().getY());
                                    if (jcbTap.isSelected()) {
                                        device.click(e.getPoint().x, e.getPoint().y);
                                        device.waitForIdle();
                                        jbLogUi.doClick();
                                    }
                                }
                            });
                        } catch (Exception ex) {
                            LOG.error("Cannot log screen", ex);
                            jtaJson.append("Cannot log screen");
                        }
                        jtaJson.append("\n\n\n");
                        LOG.debug("\n\n");

                        jd.setSize(jd.getBounds().width + 1, jd.getBounds().height + 1);
                        jd.setSize(jd.getBounds().width - 1, jd.getBounds().height - 1);
                    }
                };
                t.start();
            });
        }
        jpLog.add(Box.createHorizontalStrut(38));
        {
            JButton jbLogMsg = new JButton("Log Message");
            jpLog.add(jbLogMsg);
            JTextField jtMsg = new JTextField(10);
            jpLog.add(jtMsg);
            jtMsg.addFocusListener(new FocusListener() {
                @Override
                public void focusLost(final FocusEvent pE) {
                }

                @Override
                public void focusGained(final FocusEvent pE) {
                    jtMsg.selectAll();
                }
            });
            jtMsg.addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(java.awt.event.KeyEvent e) {
                    if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
                        jbLogMsg.doClick();
                    }
                }
            });
            jbLogMsg.addActionListener(event -> {
                Thread t = new Thread(tName) {
                    @Override
                    public void run() {
                        String msg = jtMsg.getText();
                        if (StringUtils.isNotBlank(msg)) {
                            LOG.info("{}", msg);
                            jtMsg.selectAll();
                        }
                    }
                };
                t.start();
                try {
                    t.join();
                } catch (InterruptedException ex) {
                    LOG.error("Cannot take screenshot", ex);
                }
                jtMsg.requestFocus();
            });
        }
        jpLog.add(Box.createHorizontalStrut(38));
        {
            JButton jbClear = new JButton("Clear");
            jpLog.add(jbClear);
            jbClear.addActionListener(event -> {
                jtaJson.setText("");
            });
        }

        JPanel jpAction = new JPanel();
        jpContent.add(jpAction, BorderLayout.PAGE_END);
        jpAction.setLayout(new BoxLayout(jpAction, BoxLayout.LINE_AXIS));
        jpJs.add(jpAction, BorderLayout.PAGE_END);

        jd.pack();
        jd.setVisible(true);
        jd.setLocationRelativeTo(null);

        jbLogUi.doClick();
    });

    while (visible.get()) {
        if (System.currentTimeMillis() > end) {
            LOG.error("Manual UI interaction timeout");
            break;
        }
        Thread.sleep(500);
    }

    if (pass.get()) {
        LOG.info("Manual UI Interaction returns PASS");
    } else {
        Assert.fail("Manual UI Interaction returns FAIL");
    }
}

From source file:krasa.formatter.plugin.ProjectSettingsForm.java

public ProjectSettingsForm(final Project project) {
    DONATEButton.setBorder(BorderFactory.createEmptyBorder());
    DONATEButton.setContentAreaFilled(false);
    this.project = project;
    JToggleButton[] modifiableButtons = new JToggleButton[] { useDefaultFormatter, useEclipseFormatter,
            optimizeImportsCheckBox, enableJavaFormatting, doNotFormatOtherFilesRadioButton,
            formatOtherFilesWithExceptionsRadioButton, formatSelectedTextInAllFileTypes, enableJSFormatting,
            enableCppFormatting, importOrderConfigurationManualRadioButton,
            importOrderConfigurationFromFileRadioButton, enableGWTNativeMethodsCheckBox };
    for (JToggleButton button : modifiableButtons) {
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                updateComponents();//w w w.  j a  v  a2 s . c  o  m
            }
        });
    }

    JTextField[] modifiableFields = new JTextField[] { pathToEclipsePreferenceFileJava,
            pathToEclipsePreferenceFileJS, pathToEclipsePreferenceFileCpp, disabledFileTypes, importOrder,
            pathToImportOrderPreferenceFile };
    for (JTextField field : modifiableFields) {
        field.getDocument().addDocumentListener(new DocumentAdapter() {
            protected void textChanged(DocumentEvent e) {
                updateComponents();
            }
        });
    }

    eclipsePreferenceFilePathJavaBrowse.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            browseForFile(pathToEclipsePreferenceFileJava);
        }
    });
    pathToImportOrderPreferenceFileBrowse.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            browseForFile(pathToImportOrderPreferenceFile);
        }
    });
    eclipsePreferenceFilePathJSBrowse.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            browseForFile(pathToEclipsePreferenceFileJS);
        }
    });
    eclipsePreferenceFilePathCppBrowse.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            browseForFile(pathToEclipsePreferenceFileCpp);
        }
    });

    rootComponent.addAncestorListener(new AncestorListener() {
        public void ancestorAdded(AncestorEvent event) {
            // Called when component becomes visible, to ensure that the
            // popups
            // are visible when the form is shown for the first time.
            updateComponents();
        }

        public void ancestorRemoved(AncestorEvent event) {
        }

        public void ancestorMoved(AncestorEvent event) {
        }
    });

    pathToEclipsePreferenceFileJava.getDocument().addDocumentListener(new DocumentAdapter() {
        @Override
        protected void textChanged(DocumentEvent e) {
            setJavaFormatterProfileModel();
        }
    });

    pathToEclipsePreferenceFileJS.getDocument().addDocumentListener(new DocumentAdapter() {
        @Override
        protected void textChanged(DocumentEvent e) {
            setJavaScriptFormatterProfileModel();
        }
    });

    pathToEclipsePreferenceFileCpp.getDocument().addDocumentListener(new DocumentAdapter() {
        @Override
        protected void textChanged(DocumentEvent e) {
            setCppFormatterProfileModel();
        }
    });

    newProfile.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (isModified(displayedSettings)) {
                createConfirmation("Profile was modified, save changes to current profile?", "Yes", "No",
                        new Runnable() {
                            @Override
                            public void run() {
                                apply();
                                createProfile();
                            }
                        }, new Runnable() {
                            @Override
                            public void run() {
                                importFrom(displayedSettings);
                                createProfile();
                            }
                        }, 0).showInFocusCenter();
            } else {
                createProfile();
            }
        }

        private void createProfile() {
            Settings settings = GlobalSettings.getInstance().newSettings();
            refreshProfilesModel();
            profiles.setSelectedItem(settings);
        }
    });
    copyProfile.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (isModified(displayedSettings)) {
                ListPopup confirmation = createConfirmation(
                        "Profile was modified, save changes to current profile?", "Yes", "No", new Runnable() {
                            @Override
                            public void run() {
                                apply();
                                copyProfile();
                            }
                        }, new Runnable() {
                            @Override
                            public void run() {
                                importFrom(displayedSettings);
                                copyProfile();
                            }
                        }, 0);

                confirmation.showInFocusCenter();
            } else {
                copyProfile();
            }
        }

        private void copyProfile() {
            Settings settings = GlobalSettings.getInstance().copySettings(displayedSettings);
            refreshProfilesModel();
            profiles.setSelectedItem(settings);

        }
    });
    setJavaFormatterProfileModel();
    setJavaScriptFormatterProfileModel();
    setCppFormatterProfileModel();

    profilesModel = createProfilesModel();
    profiles.setModel(profilesModel);
    profiles.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // && isSameId()
            if (displayedSettings != null && getSelectedItem() != null && isModified(displayedSettings)) {
                showConfirmationDialogOnProfileChange();
            } else if (displayedSettings != null && getSelectedItem() != null) {
                importFromInternal(getSelectedItem());
            }
        }

    });

    profiles.setRenderer(new ListCellRendererWrapper() {
        @Override
        public void customize(JList jList, Object value, int i, boolean b, boolean b1) {
            if (value != null) {
                setText(((Settings) value).getName());
            }
        }
    });
    rename.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final JTextField content = new JTextField();
            content.setText(displayedSettings.getName());
            JBPopup balloon = PopupFactoryImpl.getInstance().createComponentPopupBuilder(content, content)
                    .createPopup();
            balloon.setMinimumSize(new Dimension(200, 20));
            balloon.addListener(new JBPopupListener() {
                @Override
                public void beforeShown(LightweightWindowEvent event) {
                }

                @Override
                public void onClosed(LightweightWindowEvent event) {
                    displayedSettings.setName(content.getText());
                }
            });
            balloon.showUnderneathOf(rename);
        }
    });
    delete.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int selectedIndex = profiles.getSelectedIndex();
            GlobalSettings.getInstance().delete(getSelectedItem(), getProject());
            profiles.setModel(profilesModel = createProfilesModel());
            int itemCount = profiles.getItemCount();
            if (selectedIndex < itemCount && selectedIndex >= 0) {
                Object itemAt = profiles.getItemAt(selectedIndex);
                importFromInternal((Settings) itemAt);
                profiles.setSelectedIndex(selectedIndex);
            }
            if (selectedIndex == itemCount && selectedIndex - 1 >= 0) {
                Object itemAt = profiles.getItemAt(selectedIndex - 1);
                importFromInternal((Settings) itemAt);
                profiles.setSelectedIndex(selectedIndex - 1);
            } else {
                Settings defaultSettings = GlobalSettings.getInstance().getDefaultSettings();
                importFromInternal(defaultSettings);
                profiles.setSelectedItem(defaultSettings);
            }

        }
    });
    DONATEButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            BareBonesBrowserLaunch.openURL(
                    "https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=75YN7U7H7D7XU&lc=CZ&item_name=Eclipse%20code%20formatter%20%2d%20IntelliJ%20plugin%20%2d%20Donation&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHostedGuest");
        }
    });
    helpButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            BareBonesBrowserLaunch
                    .openURL("http://code.google.com/p/eclipse-code-formatter-intellij-plugin/wiki/HowTo");
        }
    });
    ;
    homepage.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            BareBonesBrowserLaunch.openURL("http://plugins.intellij.net/plugin/?idea&id=6546");
        }
    });
}

From source file:edu.ku.brc.specify.tasks.ExpressSearchTask.java

/**
 * Performs the express search and returns the results to the ExpressSearchResultsPaneIFace.
 * If the control is null then it will use the string.
 *
 * @param searchTextArg the Text Control that contains the search string (can be null)
 * @param searchTextStr the Text Control that contains the search string (can be null)
 * @param tables ExpressResultsTableInfo hash
 * @param esrPane the pane that the results will be set into
 * @return true if results were found, false if not results
 *//*from   ww  w . j a va  2s.  c  om*/
public synchronized boolean doQuery(final JTextField searchTextArg, final String searchTextStr,
        final ExpressSearchResultsPaneIFace esrPane) {

    doingDebug = AppPreferences.getLocalPrefs().getBoolean("esdebug", false);
    searchWarningsResults = null;

    String searchTerm = (searchTextArg != null ? searchTerm = searchTextArg.getText() : searchTextStr);

    if (!ESTermParser.getInstance().parse(searchTerm, false)) {
        setUserInputToNotFound("BAD_SEARCH_TERMS", false);
        return false;
    }

    //boolean hasResults = true;
    if (StringUtils.isNotEmpty(searchTerm)) {
        SearchTableConfig context = SearchConfigService.getInstance().getSearchContext();
        if (context == null) {
            SearchConfig config = SearchConfigService.getInstance().getSearchConfig();

            if (config.getTables().size() > 0) {
                sqlHasResults = false;
                if (searchTextArg != null) {
                    searchTextArg.setEnabled(false);
                }
                if (searchBtn != null) {
                    searchBtn.setEnabled(false);
                }

                queryList.clear(); // Just in case
                queryCount = 0;
                queryCountDone = 0;

                int cnt = 0;
                for (SearchTableConfig table : config.getTables()) {
                    if (!table.getTableInfo().isHidden()) {
                        if (AppContextMgr.isSecurityOn()) {
                            if (table.getTableInfo().getPermissions().canView()) {
                                if (startSearchJPA(esrPane, table, searchTerm,
                                        ESTermParser.getInstance().getFields()) != null) {
                                    cnt++;
                                }
                            } else {
                                log.debug("Skipping [" + table.getTableInfo().getTitle() + "]");
                            }
                        } else {
                            if (startSearchJPA(esrPane, table, searchTerm,
                                    ESTermParser.getInstance().getFields()) != null) {
                                cnt++;
                            }
                        }
                    }
                }

                if (cnt == 0) {
                    setUserInputToNotFound("NO_FIELDS_TO_SEARCH", true);
                    searchText.setEnabled(true);
                    searchBtn.setEnabled(true);
                    return false;
                }

                // Check to see if any queries got started.
                if (queryList.size() == 0) {
                    completionUIHelper(null);
                } else {
                    return true;
                }

            } else {
                searchTextArg.getToolkit().beep();
            }

        } else {
            if (startSearchJPA(esrPane, context, searchTerm, ESTermParser.getInstance().getFields()) != null) {
                return true;
            }
            setUserInputToNotFound("NO_FIELDS_TO_SEARCH", true);
            return true; // if we return false then this error gets overwritten with a different error
        }
    } else {
        //System.err.println("SearchTableConfig service has not been loaded or is empty.");
        log.error("SearchTableConfig service has been loaded or is empty.");
    }
    return false;
}