Example usage for javax.swing JTextField addKeyListener

List of usage examples for javax.swing JTextField addKeyListener

Introduction

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

Prototype

public synchronized void addKeyListener(KeyListener l) 

Source Link

Document

Adds the specified key listener to receive key events from this component.

Usage

From source file:com.sec.ose.osi.ui.frm.main.identification.JComboProjectName.java

public JComboProjectName() {

    this.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
    this.setEditable(true);
    this.setPreferredSize(new Dimension(400, 27));
    this.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            long start = System.currentTimeMillis();
            actionOnProjectSelectedonProjectComboBox();
            long end = System.currentTimeMillis();
            log.debug(/*from   w  ww.  ja va2s.com*/
                    "[JComboProjectName.addActionListener()] Project Loding TIME : " + (end - start) / 1000.0);
        }
    });

    final JTextField editor = (JTextField) this.getEditor().getEditorComponent();
    editor.addKeyListener(new KeyAdapter() {

        public void keyReleased(KeyEvent e) {

            char ch = e.getKeyChar();
            int count = 0;
            String newProjectName = editor.getText();

            if (ch != KeyEvent.VK_ENTER && ch != KeyEvent.VK_BACK_SPACE
                    && (ch == KeyEvent.CHAR_UNDEFINED || Character.isISOControl(ch))) {
                return;
            }

            if (newProjectName.length() <= 0 && ch == KeyEvent.VK_BACK_SPACE) {
                count++;
                if (count >= 2) {
                    String projectName = IdentifyMediator.getInstance().getSelectedProjectName();
                    ((JTextField) JComboProjectName.this.getEditor().getEditorComponent()).setText(projectName);
                    count = 0;
                    return;
                }
            }
            if (JComboProjectName.this.getComponentCount() > 0) {
                JComboProjectName.this.removeAllItems();
            }

            JComboProjectName.this.addItem(newProjectName);
            try {
                Collection<OSIProjectInfo> ProjectsInfo = OSIProjectInfoMgr.getInstance().getAllProjects();

                String tmpProName = null;
                boolean bAnalysis = false;
                if (newProjectName.length() > 0) {
                    for (OSIProjectInfo projectInfo : ProjectsInfo) {
                        tmpProName = projectInfo.getProjectName();
                        bAnalysis = projectInfo.isAnalyzed();
                        if (tmpProName.toLowerCase().contains(newProjectName.toLowerCase()) && bAnalysis)
                            JComboProjectName.this.addItem(tmpProName);
                    }
                    if (JComboProjectName.this.getItemCount() <= 1) {
                        JComboProjectName.this.removeAllItems();
                        JOptionPane.showOptionDialog(null, "There is no project.", "Project Filter",
                                JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE, null, buttonOK, "OK");
                    }
                } else {
                    for (OSIProjectInfo projectInfo : ProjectsInfo) {
                        if (projectInfo.isManaged() == true && projectInfo.isAnalyzed()) {
                            JComboProjectName.this.addItem(projectInfo.getProjectName());
                        }
                    }
                    JComboProjectName.this.addItem(DIVIDER_LINE);
                    for (OSIProjectInfo projectInfo : ProjectsInfo) {
                        if (projectInfo.isManaged() == false && projectInfo.isAnalyzed()) {
                            JComboProjectName.this.addItem(projectInfo.getProjectName());
                        }
                    }
                    ((JTextField) JComboProjectName.this.getEditor().getEditorComponent()).setText("");
                }
            } catch (Exception e1) {
                log.warn(e1.getMessage());
            }

            JComboProjectName.this.hidePopup();
            if (newProjectName.length() > 0)
                JComboProjectName.this.showPopup();
        }
    });

}

From source file:de.wusel.partyplayer.gui.PartyPlayer.java

private JComponent createMainComponent() {
    JPanel mainPanel = new JPanel(new MigLayout("fill", "[][50%][][50%]", "[] [] [] [] [grow]"));
    mainPanel.add(new JLabel(getText("layout.current.title")));
    mainPanel.add(new JSeparator(), "growx");
    mainPanel.add(new JLabel(getText("layout.next.title")));
    mainPanel.add(new JSeparator(), "growx, wrap");
    mainPanel.add(createPlayerPanel(), "grow, span 2");
    mainPanel.add(createPlayListPanel(), "grow, hmax 100, span 2, wrap");
    mainPanel.add(new JLabel(getText("layout.available.title")));
    mainPanel.add(new JSeparator(), "growx, span, wrap");
    final JTextField searchField = new JTextField();
    searchField.addKeyListener(new KeyAdapter() {

        @Override/*from  w w  w  .j a  v  a 2s  .  c o  m*/
        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                searchField.setText(null);
                table.setRowFilter(null);
            }
            try {
                table.setRowFilter(
                        RowFilter.regexFilter("(?i)" + Pattern.quote(searchField.getText()), 0, 1, 3));
            } catch (PatternSyntaxException ex) {
                table.setRowFilter(null);
                //do nothing
            }
        }
    });
    mainPanel.add(new JLabel(getText("layout.search.label")));
    mainPanel.add(searchField, "span, growx, wrap");
    mainPanel.add(createSongPanel(), "span, grow");
    return mainPanel;
}

From source file:com.emental.mindraider.ui.dialogs.OpenConceptByTagJDialog.java

public OpenConceptByTagJDialog(String dialogTitle, String selectionLabel, String buttonLabel,
        boolean showCancel) {
    super(dialogTitle);

    JPanel framePanel = new JPanel();
    framePanel.setBorder(new EmptyBorder(5, 10, 0, 10));
    framePanel.setLayout(new BorderLayout());

    // NORTH panel
    JPanel northPanel = new JPanel();
    northPanel.setLayout(new BorderLayout());
    northPanel.add(new JLabel(selectionLabel), BorderLayout.NORTH);

    final JTextField tagLabel = new JTextField(TEXTFIELD_WIDTH);

    // data//from w  w  w .  ja v  a  2  s  .  c  o  m
    tags = MindRaider.tagCustodian.getAllTags();
    ;
    if (tags == null) {
        tagLabel.setEnabled(false);
    }
    tagLabel.addKeyListener(new KeyListener() {
        public void keyPressed(KeyEvent keyEvent) {
            if (keyEvent.getKeyCode() == KeyEvent.VK_ENTER) {
                logger.debug("Openning selected tag...");
                openTagSearchDialog();
            }
        }

        public void keyReleased(KeyEvent keyEvent) {
            getListModel().clear();
            shownTags.clear();
            if (tagLabel.getText().length() > 0) {
                for (TagEntry tag : tags) {
                    if (tag.getTagLabel().toLowerCase().startsWith(tagLabel.getText().toLowerCase())) {
                        getListModel().addElement(tag.getTagLabel() + " (" + tag.getCardinality() + ")");
                        shownTags.add(tag);
                    }
                }
            } else {
                // show all tags
                for (TagEntry tag : tags) {
                    getListModel().addElement(tag.getTagLabel() + " (" + tag.getCardinality() + ")");
                    shownTags.add(tag);
                }
            }
        }

        public void keyTyped(KeyEvent keyEvent) {
        }
    });
    northPanel.add(tagLabel, BorderLayout.SOUTH);
    framePanel.add(northPanel, BorderLayout.NORTH);

    // CENTER panel
    JPanel centerPanel = new JPanel();
    centerPanel.setLayout(new BorderLayout());
    centerPanel.add(new JLabel(Messages.getString("OpenConceptByTagJDialog.matchingTags")), BorderLayout.NORTH);

    defaultListModel = new DefaultListModel();
    list = new JList(defaultListModel);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setSelectedIndex(0);
    // list.addListSelectionListener(this);
    list.setVisibleRowCount(15);
    JScrollPane listScrollPane = new JScrollPane(list);
    centerPanel.add(listScrollPane, BorderLayout.SOUTH);
    framePanel.add(centerPanel, BorderLayout.CENTER);

    JPanel southPanel = new JPanel();
    southPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
    JButton openButton = new JButton(buttonLabel);
    southPanel.add(openButton);
    openButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            openTagSearchDialog();
        }
    });

    if (showCancel) {
        JButton cancelButton = new JButton(Messages.getString("OpenNotebookJDialog.cancel"));
        southPanel.add(cancelButton);
        cancelButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                OpenConceptByTagJDialog.this.dispose();
            }
        });
    }

    framePanel.add(southPanel, BorderLayout.SOUTH);

    getContentPane().add(framePanel, BorderLayout.CENTER);

    // show
    pack();
    Gfx.centerAndShowWindow(this);
}

From source file:com.intuit.tank.proxy.ProxyApp.java

private JPanel getTransactionTable() {
    JPanel frame = new JPanel(new BorderLayout());
    model = new TransactionTableModel();
    final JTable table = new TransactionTable(model);
    final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    table.setRowSorter(sorter);// ww w  .j av a2  s  . co m
    final JPopupMenu pm = new JPopupMenu();
    JMenuItem item = new JMenuItem("Delete Selected");
    item.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            int[] selectedRows = table.getSelectedRows();
            if (selectedRows.length != 0) {
                int response = JOptionPane.showConfirmDialog(ProxyApp.this,
                        "Are you sure you want to delete " + selectedRows.length + " Transactions?",
                        "Confirm Delete", JOptionPane.YES_NO_OPTION);
                if (response == JOptionPane.YES_OPTION) {
                    int[] correctedRows = new int[selectedRows.length];
                    for (int i = selectedRows.length; --i >= 0;) {
                        int row = selectedRows[i];
                        int index = (Integer) table.getValueAt(row, 0) - 1;
                        correctedRows[i] = index;
                    }
                    Arrays.sort(correctedRows);
                    for (int i = correctedRows.length; --i >= 0;) {
                        int row = correctedRows[i];
                        Transaction transaction = model.getTransactionForIndex(row);
                        if (transaction != null) {
                            model.removeTransaction(transaction, row);
                            isDirty = true;
                            saveAction.setEnabled(isDirty && !stopAction.isEnabled());
                        }
                    }
                }
            }
        }
    });
    pm.add(item);
    table.add(pm);

    table.addMouseListener(new MouseAdapter() {
        boolean pressed = false;

        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                Point p = e.getPoint();
                int row = table.rowAtPoint(p);
                int index = (Integer) table.getValueAt(row, 0) - 1;
                Transaction transaction = model.getTransactionForIndex(index);
                if (transaction != null) {
                    detailsTF.setText(transaction.toString());
                    detailsTF.setCaretPosition(0);
                    detailsDialog.setVisible(true);
                }
            }
        }

        /**
         * @{inheritDoc
         */
        @Override
        public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
                pressed = true;
                int[] selectedRows = table.getSelectedRows();
                if (selectedRows.length != 0) {
                    pm.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        }

        /**
         * @{inheritDoc
         */
        @Override
        public void mouseReleased(MouseEvent e) {
            if (!pressed && e.isPopupTrigger()) {
                int[] selectedRows = table.getSelectedRows();
                if (selectedRows.length != 0) {
                    pm.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        }

    });

    JScrollPane pane = new JScrollPane(table);
    frame.add(pane, BorderLayout.CENTER);
    JPanel panel = new JPanel(new BorderLayout());
    JLabel label = new JLabel("Filter: ");
    panel.add(label, BorderLayout.WEST);
    final JLabel countLabel = new JLabel(" Count: 0 ");
    panel.add(countLabel, BorderLayout.EAST);
    final JTextField filterText = new JTextField("");
    filterText.addKeyListener(new KeyAdapter() {
        public void keyTyped(KeyEvent e) {
            String text = filterText.getText();
            if (text.length() == 0) {
                sorter.setRowFilter(null);
            } else {
                try {
                    sorter.setRowFilter(RowFilter.regexFilter(text));
                    countLabel.setText(" Count: " + sorter.getViewRowCount() + " ");
                } catch (PatternSyntaxException pse) {
                    System.err.println("Bad regex pattern");
                }
            }
        }
    });
    panel.add(filterText, BorderLayout.CENTER);

    frame.add(panel, BorderLayout.NORTH);
    return frame;
}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopPickerField.java

@Override
public void addFieldListener(final FieldListener listener) {
    final JTextField field = (JTextField) impl.getEditor();
    field.addFocusListener(new FocusAdapter() {

        @Override/*from   www.  j  a v a2 s.c o m*/
        public void focusLost(FocusEvent e) {
            fireFieldListener(listener, field.getText());
        }
    });

    field.addKeyListener(new KeyAdapter() {
        protected static final int ENTER_CODE = 10;

        @Override
        public void keyPressed(KeyEvent e) {
            if (ENTER_CODE == e.getKeyCode()) {
                fireFieldListener(listener, field.getText());
            }
        }
    });
}

From source file:com.sec.ose.osi.ui.frm.main.manage.dialog.JDlgProjectCreate.java

/**
 * This method initializes jComboBoxClonedFrom   
 *    //from   w  ww .j  a  v  a  2  s  . co  m
 * @return javax.swing.JComboBox   
 */
private JComboBox<String> getJComboBoxClonedFrom() {
    if (jComboBoxClonedFrom == null) {
        jComboBoxClonedFrom = new JComboBox<String>();
        jComboBoxClonedFrom.setRenderer(new ComboToopTip());
        jComboBoxClonedFrom.setEditable(true);
        jComboBoxClonedFrom.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                log.debug("jComboBoxClonedFrom.actionPerformed()");
                eventHandler.handleEvent(EventHandler.COMBO_CLONED_FROM);
            }
        });
        refresh(jComboBoxClonedFrom);

        final JTextField editor;
        editor = (JTextField) jComboBoxClonedFrom.getEditor().getEditorComponent();
        editor.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                char ch = e.getKeyChar();

                if (ch != KeyEvent.VK_ENTER && ch != KeyEvent.VK_BACK_SPACE
                        && (ch == KeyEvent.CHAR_UNDEFINED || Character.isISOControl(ch)))
                    return;
                if (ch == KeyEvent.VK_ENTER) {
                    jComboBoxClonedFrom.hidePopup();
                    return;
                }

                String str = editor.getText();

                if (jComboBoxClonedFrom.getComponentCount() > 0) {
                    jComboBoxClonedFrom.removeAllItems();
                }

                jComboBoxClonedFrom.addItem(str);
                try {
                    String tmpProjectName = null;
                    if (str.length() > 0) {
                        for (int i = 0; i < names.size(); i++) {
                            tmpProjectName = names.get(i);
                            if (tmpProjectName.toLowerCase().startsWith(str.toLowerCase()))
                                jComboBoxClonedFrom.addItem(tmpProjectName);
                        }
                    } else {
                        for (int i = 0; i < names.size(); i++) {
                            jComboBoxClonedFrom.addItem(names.get(i));
                        }
                    }
                } catch (Exception e1) {
                    log.warn(e1.getMessage());
                }

                jComboBoxClonedFrom.hidePopup();
                if (str.length() > 0)
                    jComboBoxClonedFrom.showPopup();
            }
        });

        editor.addFocusListener(new FocusAdapter() {
            public void focusGained(FocusEvent e) {
                if (editor.getText().length() > 0)
                    jComboBoxClonedFrom.showPopup();
            }

            public void focusLost(FocusEvent e) {
                jComboBoxClonedFrom.hidePopup();
            }
        });
    }
    return jComboBoxClonedFrom;
}

From source file:com.aw.swing.mvp.cmp.RowSelectorMediator.java

public RowSelectorMediator(JTextField textField, JTable table, int columnIndex) {
    this.textField = textField;
    this.table = table;
    this.columnIndex = columnIndex;

    documentListener = new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
            textFieldChanged(e);//from  w w  w .  j a  v  a 2 s  .  c o  m
        }

        public void insertUpdate(DocumentEvent e) {
            textFieldChanged(e);
        }

        public void removeUpdate(DocumentEvent e) {
            textFieldChanged(e);
        }
    };

    textField.getDocument().addDocumentListener(documentListener);

    //Add the keylistener to process the Up, Down, PgUp and PgDn keys events
    textField.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
            textFieldKeyPressed(e);
        }

        public void keyReleased(KeyEvent e) {
        }
    });
}

From source file:net.lldp.checksims.ui.results.ScrollViewer.java

/**
 * Create a scroll viewer from a sortable Matrix Viewer
 * @param results the sortableMatrix to view
 * @param toRevalidate frame to revalidate sometimes
 *//*from   w w w.  j  ava  2  s  .co  m*/
public ScrollViewer(SimilarityMatrix exportMatrix, SortableMatrixViewer results, JFrame toRevalidate) {
    resultsView = new JScrollPane(results);
    setBackground(Color.black);
    resultsView.addComponentListener(new ComponentListener() {

        @Override
        public void componentHidden(ComponentEvent arg0) {
        }

        @Override
        public void componentMoved(ComponentEvent arg0) {
        }

        @Override
        public void componentResized(ComponentEvent ce) {
            Dimension size = ce.getComponent().getSize();
            results.padToSize(size);
        }

        @Override
        public void componentShown(ComponentEvent arg0) {
        }
    });

    resultsView.getViewport().addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            Rectangle r = resultsView.getViewport().getViewRect();
            results.setViewAt(r);
        }
    });

    resultsView.setBackground(Color.black);
    sidebar = new JPanel();

    setPreferredSize(new Dimension(900, 631));
    setMinimumSize(new Dimension(900, 631));
    sidebar.setPreferredSize(new Dimension(200, 631));
    sidebar.setMaximumSize(new Dimension(200, 3000));
    resultsView.setMinimumSize(new Dimension(700, 631));
    resultsView.setPreferredSize(new Dimension(700, 631));

    sidebar.setBackground(Color.GRAY);

    setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));

    this.add(sidebar);
    this.add(resultsView);

    resultsView.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    resultsView.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    resultsView.getVerticalScrollBar().setUnitIncrement(16);
    resultsView.getHorizontalScrollBar().setUnitIncrement(16);

    Integer[] presetThresholds = { 80, 60, 40, 20, 0 };
    JComboBox<Integer> threshHold = new JComboBox<Integer>(presetThresholds);
    threshHold.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent event) {
            if (event.getStateChange() == ItemEvent.SELECTED) {
                Integer item = (Integer) event.getItem();
                results.updateThreshold(item / 100.0);
                toRevalidate.revalidate();
                toRevalidate.repaint();
            }
        }
    });
    threshHold.setSelectedIndex(0);
    results.updateThreshold((Integer) threshHold.getSelectedItem() / 100.0);

    JTextField student1 = new JTextField(15);
    JTextField student2 = new JTextField(15);

    KeyListener search = new KeyListener() {

        @Override
        public void keyPressed(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
            results.highlightMatching(student1.getText(), student2.getText());
            toRevalidate.revalidate();
            toRevalidate.repaint();
        }

        @Override
        public void keyTyped(KeyEvent e) {
        }
    };

    student1.addKeyListener(search);
    student2.addKeyListener(search);

    Collection<MatrixPrinter> printerNameSet = MatrixPrinterRegistry.getInstance()
            .getSupportedImplementations();
    JComboBox<MatrixPrinter> exportAs = new JComboBox<>(new Vector<>(printerNameSet));
    JButton exportAsSave = new JButton("Save");

    JFileChooser fc = new JFileChooser();

    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setCurrentDirectory(new java.io.File("."));
    fc.setDialogTitle("Save results");

    exportAsSave.addActionListener(ae -> {
        MatrixPrinter method = (MatrixPrinter) exportAs.getSelectedItem();

        int err = fc.showDialog(toRevalidate, "Save");
        if (err == JFileChooser.APPROVE_OPTION) {
            try {
                FileUtils.writeStringToFile(fc.getSelectedFile(), method.printMatrix(exportMatrix));
            } catch (InternalAlgorithmError | IOException e1) {
                // TODO log / show error
            }
        }
    });

    JPanel thresholdLabel = new JPanel();
    JPanel studentSearchLabel = new JPanel();
    JPanel fileOutputLabel = new JPanel();

    thresholdLabel.setBorder(BorderFactory.createTitledBorder("Matching Threshold"));
    studentSearchLabel.setBorder(BorderFactory.createTitledBorder("Student Search"));
    fileOutputLabel.setBorder(BorderFactory.createTitledBorder("Save Results"));

    thresholdLabel.add(threshHold);
    studentSearchLabel.add(student1);
    studentSearchLabel.add(student2);
    fileOutputLabel.add(exportAs);
    fileOutputLabel.add(exportAsSave);

    studentSearchLabel.setPreferredSize(new Dimension(200, 100));
    studentSearchLabel.setMinimumSize(new Dimension(200, 100));
    thresholdLabel.setPreferredSize(new Dimension(200, 100));
    thresholdLabel.setMinimumSize(new Dimension(200, 100));
    fileOutputLabel.setPreferredSize(new Dimension(200, 100));
    fileOutputLabel.setMinimumSize(new Dimension(200, 100));

    sidebar.setMaximumSize(new Dimension(200, 4000));

    sidebar.add(thresholdLabel);
    sidebar.add(studentSearchLabel);
    sidebar.add(fileOutputLabel);
}

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 av  a2 s . c o  m
 */
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:kenh.xscript.elements.Debug.java

private void initial(Container c) {
    c.setLayout(new BorderLayout());

    // Add variable list

    DefaultListModel<String> model = new DefaultListModel();

    if (this.getEnvironment() != null) {
        java.util.Set<String> keys = this.getEnvironment().getVariables().keySet();
        for (String key : keys) {
            model.addElement(key);/*from  w  ww .  ja  va 2 s .com*/
        }
    } else {
        for (int i = 1; i < 10; i++) {
            model.addElement("Variable " + i);
        }
        model.addElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    }

    JList list = new JList(model);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane listPane = new JScrollPane();
    listPane.setViewportView(list);
    listPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

    c.add(listPane, BorderLayout.EAST);

    list.setPreferredSize(new Dimension(150, list.getPreferredSize().height));

    // 

    JTextField quote = new JTextField();
    quote.requestFocus();

    //JButton button = new JButton(">>");

    JPanel quotePanel = new JPanel();
    quotePanel.setLayout(new BorderLayout());
    quotePanel.add(quote, BorderLayout.CENTER);
    //quotePanel.add(button, BorderLayout.EAST);

    JTextArea result = new JTextArea();
    result.setEditable(false);

    JScrollPane resultPane = new JScrollPane();
    resultPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    resultPane.setViewportView(result);

    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.add(quotePanel, BorderLayout.NORTH);
    panel.add(resultPane, BorderLayout.CENTER);

    c.add(panel, BorderLayout.CENTER);

    list.addListSelectionListener(this);
    //button.addActionListener(this);
    quote.addKeyListener(this);

    this.result = result;
}