Example usage for javax.swing JScrollPane setPreferredSize

List of usage examples for javax.swing JScrollPane setPreferredSize

Introduction

In this page you can find the example usage for javax.swing JScrollPane setPreferredSize.

Prototype

@BeanProperty(preferred = true, description = "The preferred size of the component.")
public void setPreferredSize(Dimension preferredSize) 

Source Link

Document

Sets the preferred size of this component.

Usage

From source file:it.imtech.metadata.MetaUtility.java

/**
 * Metodo adibito alla creazione dinamica ricorsiva dell'interfaccia dei
 * metadati//from  w  w  w  .  ja v a  2s .com
 *
 * @param submetadatas Map contente i metadati e i sottolivelli di metadati
 * @param vocabularies Map contenente i dati contenuti nel file xml
 * vocabulary.xml
 * @param parent Jpanel nel quale devono venir inseriti i metadati
 * @param level Livello corrente
 */
public void create_metadata_view(Map<Object, Metadata> submetadatas, JPanel parent, int level,
        final String panelname) throws Exception {
    ResourceBundle bundle = ResourceBundle.getBundle(Globals.RESOURCES, Globals.CURRENT_LOCALE, Globals.loader);
    int lenght = submetadatas.size();
    int labelwidth = 220;
    int i = 0;
    JButton addcontribute = null;

    for (Map.Entry<Object, Metadata> kv : submetadatas.entrySet()) {
        ArrayList<Component> tabobjects = new ArrayList<Component>();

        if (kv.getValue().MID == 17 || kv.getValue().MID == 23 || kv.getValue().MID == 18
                || kv.getValue().MID == 137) {
            continue;
        }

        //Crea un jpanel nuovo e fa appen su parent
        JPanel innerPanel = new JPanel(new MigLayout("fillx, insets 1 1 1 1"));
        innerPanel.setName("pannello" + level + i);

        i++;
        String datatype = kv.getValue().datatype.toString();

        if (kv.getValue().MID == 45) {
            JPanel choice = new JPanel(new MigLayout());

            JComboBox combo = addClassificationChoice(choice, kv.getValue().sequence, panelname);

            JLabel labelc = new JLabel();
            labelc.setText(Utility.getBundleString("selectclassif", bundle));
            labelc.setPreferredSize(new Dimension(100, 20));

            choice.add(labelc);

            findLastClassification(panelname);
            if (last_classification != 0 && classificationRemoveButton == null) {
                logger.info("Removing last clasification");
                classificationRemoveButton = new JButton("-");

                classificationRemoveButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent event) {
                        BookImporter.getInstance().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                        removeClassificationToMetadata(panelname);
                        BookImporter.getInstance().refreshMetadataTab(false, panelname);
                        findLastClassification(panelname); //update last_classification
                        BookImporter.getInstance().setCursor(null);
                    }
                });
                if (Integer.parseInt(kv.getValue().sequence) == last_classification) {
                    choice.add(classificationRemoveButton, "wrap, width :50:");
                }
            }

            if (classificationAddButton == null) {
                logger.info("Adding a new classification");
                choice.add(combo, "width 100:600:600");

                classificationAddButton = new JButton("+");

                classificationAddButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent event) {
                        BookImporter.getInstance().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                        addClassificationToMetadata(panelname);
                        BookImporter.getInstance().refreshMetadataTab(false, panelname);
                        BookImporter.getInstance().setCursor(null);
                    }
                });

                choice.add(classificationAddButton, "width :50:");
            } else {
                //choice.add(combo, "wrap,width 100:700:700");
                choice.add(combo, "width 100:700:700");
                if (Integer.parseInt(kv.getValue().sequence) == last_classification) {
                    choice.add(classificationRemoveButton, "wrap, width :50");
                }
            }
            parent.add(choice, "wrap,width 100:700:700");
            classificationMID = kv.getValue().MID;

            innerPanel.setName(panelname + "---ImPannelloClassif---" + kv.getValue().sequence);
            try {

                addClassification(innerPanel, classificationMID, kv.getValue().sequence, panelname);
            } catch (Exception ex) {
                logger.error("Errore nell'aggiunta delle classificazioni");
            }
            parent.add(innerPanel, "wrap, growx");
            BookImporter.policy.addIndexedComponent(combo);

            continue;
        }

        if (datatype.equals("Node")) {
            JLabel label = new JLabel();
            label.setText(kv.getValue().description);
            label.setPreferredSize(new Dimension(100, 20));

            int size = 16 - (level * 2);
            Font myFont = new Font("MS Sans Serif", Font.PLAIN, size);
            label.setFont(myFont);

            if (Integer.toString(kv.getValue().MID).equals("11")) {
                JPanel temppanel = new JPanel(new MigLayout());

                //update last_contribute
                findLastContribute(panelname);

                if (last_contribute != 0 && removeContribute == null) {
                    logger.info("Removing last contribute");
                    removeContribute = new JButton("-");

                    removeContribute.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent event) {
                            BookImporter.getInstance()
                                    .setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                            removeContributorToMetadata(panelname);
                            BookImporter.getInstance().refreshMetadataTab(false, panelname);
                            BookImporter.getInstance().setCursor(null);
                        }
                    });

                    if (!kv.getValue().sequence.equals("")) {
                        if (Integer.parseInt(kv.getValue().sequence) == last_contribute) {
                            innerPanel.add(removeContribute, "width :50:");
                        }
                    }
                }

                if (addcontribute == null) {
                    logger.info("Adding a new contribute");
                    addcontribute = new JButton("+");

                    addcontribute.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent event) {
                            BookImporter.getInstance()
                                    .setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                            addContributorToMetadata(panelname);
                            BookImporter.getInstance().refreshMetadataTab(false, panelname);
                            BookImporter.getInstance().setCursor(null);
                        }
                    });

                    temppanel.add(label, " width :200:");
                    temppanel.add(addcontribute, "width :50:");
                    innerPanel.add(temppanel, "wrap, growx");
                } else {
                    temppanel.add(label, " width :200:");
                    findLastContribute(panelname);
                    if (!kv.getValue().sequence.equals("")) {
                        if (Integer.parseInt(kv.getValue().sequence) == last_contribute) {
                            temppanel.add(removeContribute, "width :50:");
                        }
                    }
                    innerPanel.add(temppanel, "wrap, growx");
                }
            } else if (Integer.toString(kv.getValue().MID).equals("115")) {
                logger.info("Devo gestire una provenience!");
            }
        } else {
            String title = "";

            if (kv.getValue().mandatory.equals("Y") || kv.getValue().MID == 14 || kv.getValue().MID == 15) {
                title = kv.getValue().description + " *";
            } else {
                title = kv.getValue().description;
            }

            innerPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), title,
                    TitledBorder.LEFT, TitledBorder.TOP));

            if (datatype.equals("Vocabulary")) {
                TreeMap<String, String> entryCombo = new TreeMap<String, String>();
                int index = 0;
                String selected = null;

                if (!Integer.toString(kv.getValue().MID).equals("8"))
                    entryCombo.put(Utility.getBundleString("comboselect", bundle),
                            Utility.getBundleString("comboselect", bundle));

                for (Map.Entry<String, TreeMap<String, VocEntry>> vc : vocabularies.entrySet()) {
                    String tempmid = Integer.toString(kv.getValue().MID);

                    if (Integer.toString(kv.getValue().MID_parent).equals("11")
                            || Integer.toString(kv.getValue().MID_parent).equals("13")) {
                        String[] testmid = tempmid.split("---");
                        tempmid = testmid[0];
                    }

                    if (vc.getKey().equals(tempmid)) {
                        TreeMap<String, VocEntry> iEntry = vc.getValue();

                        for (Map.Entry<String, VocEntry> ivc : iEntry.entrySet()) {
                            entryCombo.put(ivc.getValue().description, ivc.getValue().ID);
                            if (kv.getValue().value != null) {
                                if (kv.getValue().value.equals(ivc.getValue().ID)) {
                                    selected = ivc.getValue().ID;
                                }
                            }
                            index++;
                        }
                    }
                }

                final ComboMapImpl model = new ComboMapImpl();
                model.setVocabularyCombo(true);
                model.putAll(entryCombo);

                final JComboBox voc = new javax.swing.JComboBox(model);
                model.specialRenderCombo(voc);

                if (Integer.toString(kv.getValue().MID_parent).equals("11")
                        || Integer.toString(kv.getValue().MID_parent).equals("13")) {
                    voc.setName("MID_" + Integer.toString(kv.getValue().MID) + "---" + kv.getValue().sequence);
                } else {
                    voc.setName("MID_" + Integer.toString(kv.getValue().MID));
                }

                if (Integer.toString(kv.getValue().MID).equals("8") && selected == null)
                    selected = "44";

                selected = (selected == null) ? Utility.getBundleString("comboselect", bundle) : selected;

                for (int k = 0; k < voc.getItemCount(); k++) {
                    Map.Entry<String, String> el = (Map.Entry<String, String>) voc.getItemAt(k);
                    if (el.getValue().equals(selected))
                        voc.setSelectedIndex(k);
                }

                voc.setPreferredSize(new Dimension(150, 30));
                innerPanel.add(voc, "wrap, width :400:");
                tabobjects.add(voc);
            } else if (datatype.equals("CharacterString") || datatype.equals("GPS")) {
                final JTextArea textField = new javax.swing.JTextArea();

                if (Integer.toString(kv.getValue().MID_parent).equals("11")
                        || Integer.toString(kv.getValue().MID_parent).equals("13")) {
                    textField.setName(
                            "MID_" + Integer.toString(kv.getValue().MID) + "---" + kv.getValue().sequence);
                } else {
                    textField.setName("MID_" + Integer.toString(kv.getValue().MID));
                }

                textField.setPreferredSize(new Dimension(230, 0));
                textField.setText(kv.getValue().value);
                textField.setLineWrap(true);
                textField.setWrapStyleWord(true);

                innerPanel.add(textField, "wrap, width :300:");

                textField.addKeyListener(new KeyAdapter() {
                    @Override
                    public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode() == KeyEvent.VK_TAB) {
                            if (e.getModifiers() > 0) {
                                textField.transferFocusBackward();
                            } else {
                                textField.transferFocus();
                            }
                            e.consume();
                        }
                    }
                });

                tabobjects.add(textField);
            } else if (datatype.equals("LangString")) {
                JScrollPane inner_scroll = new javax.swing.JScrollPane();
                inner_scroll.setHorizontalScrollBarPolicy(
                        javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
                inner_scroll.setVerticalScrollBarPolicy(
                        javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
                inner_scroll.setPreferredSize(new Dimension(240, 80));
                inner_scroll.setName("langStringScroll");
                final JTextArea jTextArea1 = new javax.swing.JTextArea();
                jTextArea1.setName("MID_" + Integer.toString(kv.getValue().MID));
                jTextArea1.setText(kv.getValue().value);

                jTextArea1.setSize(new Dimension(350, 70));
                jTextArea1.setLineWrap(true);
                jTextArea1.setWrapStyleWord(true);

                inner_scroll.setViewportView(jTextArea1);
                innerPanel.add(inner_scroll, "width :300:");

                //Add combo language box
                JComboBox voc = getComboLangBox(kv.getValue().language);
                voc.setName("MID_" + Integer.toString(kv.getValue().MID) + "_lang");

                voc.setPreferredSize(new Dimension(200, 20));
                innerPanel.add(voc, "wrap, width :300:");

                jTextArea1.addKeyListener(new KeyAdapter() {
                    @Override
                    public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode() == KeyEvent.VK_TAB) {
                            if (e.getModifiers() > 0) {
                                jTextArea1.transferFocusBackward();
                            } else {
                                jTextArea1.transferFocus();
                            }
                            e.consume();
                        }
                    }
                });
                tabobjects.add(jTextArea1);
                tabobjects.add(voc);
            } else if (datatype.equals("Language")) {
                final JComboBox voc = getComboLangBox(kv.getValue().value);
                voc.setName("MID_" + Integer.toString(kv.getValue().MID));

                voc.setPreferredSize(new Dimension(150, 20));
                voc.setBounds(5, 5, 150, 20);
                innerPanel.add(voc, "wrap, width :500:");

                //BookImporter.policy.addIndexedComponent(voc);
                tabobjects.add(voc);

            } else if (datatype.equals("Boolean")) {
                int selected = 0;
                TreeMap bin = new TreeMap<String, String>();
                bin.put("yes", Utility.getBundleString("voc1", bundle));
                bin.put("no", Utility.getBundleString("voc2", bundle));

                if (kv.getValue().value == null) {
                    switch (kv.getValue().MID) {
                    case 35:
                        selected = 0;
                        break;
                    case 36:
                        selected = 1;
                        break;
                    }
                } else if (kv.getValue().value.equals("yes")) {
                    selected = 1;
                } else {
                    selected = 0;
                }

                final ComboMapImpl model = new ComboMapImpl();
                model.putAll(bin);

                final JComboBox voc = new javax.swing.JComboBox(model);
                model.specialRenderCombo(voc);

                voc.setName("MID_" + Integer.toString(kv.getValue().MID));
                voc.setSelectedIndex(selected);

                voc.setPreferredSize(new Dimension(150, 20));
                voc.setBounds(5, 5, 150, 20);
                innerPanel.add(voc, "wrap, width :300:");
                //BookImporter.policy.addIndexedComponent(voc);
                tabobjects.add(voc);
            } else if (datatype.equals("License")) {
                String selectedIndex = null;
                int vindex = 0;
                int defaultIndex = 0;

                TreeMap<String, String> entryCombo = new TreeMap<String, String>();

                for (Map.Entry<String, TreeMap<String, VocEntry>> vc : vocabularies.entrySet()) {
                    if (vc.getKey().equals(Integer.toString(kv.getValue().MID))) {
                        TreeMap<String, VocEntry> iEntry = vc.getValue();

                        for (Map.Entry<String, VocEntry> ivc : iEntry.entrySet()) {
                            entryCombo.put(ivc.getValue().description, ivc.getValue().ID);

                            if (ivc.getValue().ID.equals("1"))
                                defaultIndex = vindex;

                            if (kv.getValue().value != null) {
                                if (ivc.getValue().ID.equals(kv.getValue().value)) {
                                    selectedIndex = Integer.toString(vindex);
                                }
                            }
                            vindex++;
                        }
                    }
                }

                if (selectedIndex == null)
                    selectedIndex = Integer.toString(defaultIndex);

                ComboMapImpl model = new ComboMapImpl();
                model.putAll(entryCombo);
                model.setVocabularyCombo(true);

                JComboBox voc = new javax.swing.JComboBox(model);
                model.specialRenderCombo(voc);

                voc.setName("MID_" + Integer.toString(kv.getValue().MID));
                voc.setSelectedIndex(Integer.parseInt(selectedIndex));
                voc.setPreferredSize(new Dimension(150, 20));

                voc.setBounds(5, 5, 150, 20);
                innerPanel.add(voc, "wrap, width :500:");
                //BookImporter.policy.addIndexedComponent(voc);
                tabobjects.add(voc);
            } else if (datatype.equals("DateTime")) {
                //final JXDatePicker datePicker = new JXDatePicker();
                JDateChooser datePicker = new JDateChooser();
                datePicker.setName("MID_" + Integer.toString(kv.getValue().MID));

                JPanel test = new JPanel(new MigLayout());
                JLabel lbefore = new JLabel(Utility.getBundleString("beforechristlabel", bundle));
                JCheckBox beforechrist = new JCheckBox();
                beforechrist.setName("MID_" + Integer.toString(kv.getValue().MID) + "_check");

                if (kv.getValue().value != null) {
                    try {
                        if (kv.getValue().value.charAt(0) == '-') {
                            beforechrist.setSelected(true);
                        }

                        Date date1 = new Date();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        if (kv.getValue().value.charAt(0) == '-') {
                            date1 = sdf.parse(adjustDate(kv.getValue().value));
                        } else {
                            date1 = sdf.parse(kv.getValue().value);
                        }
                        datePicker.setDate(date1);
                    } catch (Exception e) {
                        //Console.WriteLine("ERROR import date:" + ex.Message);
                    }
                }

                test.add(datePicker, "width :200:");
                test.add(lbefore, "gapleft 30");
                test.add(beforechrist, "wrap");

                innerPanel.add(test, "wrap");
            }
        }

        //Recursive call
        create_metadata_view(kv.getValue().submetadatas, innerPanel, level + 1, panelname);

        if (kv.getValue().editable.equals("Y")
                || (datatype.equals("Node") && kv.getValue().hidden.equals("0"))) {
            parent.add(innerPanel, "wrap, growx");

            for (Component tabobject : tabobjects) {
                BookImporter.policy.addIndexedComponent(tabobject);
            }
        }
    }
}

From source file:com.pironet.tda.TDA.java

/**
 * display selected category in upper right frame
 *//* w ww.j a v  a 2s .  c  o  m*/
private void displayCategory(Object nodeInfo) {
    final Category cat = ((Category) nodeInfo);
    topSplitPane.getLeftComponent().setPreferredSize(topSplitPane.getLeftComponent().getSize());
    boolean needDividerPos = false;
    Dimension size = null;
    if (topSplitPane.getRightComponent() != null) {
        size = topSplitPane.getRightComponent().getSize();
    } else {
        needDividerPos = true;
    }
    setThreadDisplay(true);
    final JScrollPane lastView = cat.getLastView();
    if (lastView == null) {
        JComponent catComp = cat.getCatComponent(this);
        if (cat.getName().startsWith("Monitors") || cat.getName().startsWith("Threads blocked by Monitors")) {
            catComp.addMouseListener(getMonitorsPopupMenu());
        } else {
            catComp.addMouseListener(getCatPopupMenu());
        }
        final ViewScrollPane dumpView = new ViewScrollPane(catComp, runningAsVisualVMPlugin);
        if (size != null) {
            dumpView.setPreferredSize(size);
        }

        topSplitPane.setRightComponent(dumpView);
        cat.setLastView(dumpView);
    } else {
        if (size != null) {
            lastView.setPreferredSize(size);
        } else {
            lastView.setMinimumSize(Const.EMPTY_DIMENSION);
            lastView.setPreferredSize(Const.EMPTY_DIMENSION);
        }
        topSplitPane.setRightComponent(lastView);

    }

    if (cat.getCurrentlySelectedUserObject() != null) {
        displayThreadInfo(cat.getCurrentlySelectedUserObject());
    } else {
        displayContent(null);
    }
    if (needDividerPos) {
        topSplitPane.setDividerLocation(PrefManager.get().getTopDividerPos());
    }
    if (cat.howManyFiltered() > 0) {
        statusBar.setInfoText("Filtered " + cat.howManyFiltered()
                + " elements in this category. Showing remaining " + cat.showing() + " elements.");
    } else {
        statusBar.setInfoText(AppInfo.getStatusBarInfo());
    }

    displayContent(cat.getInfo());
}

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//  w  w w  .jav a  2 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:ucar.unidata.idv.flythrough.Flythrough.java

/**
 * _more_// ww w  .j a va2 s.c  o m
 *
 * @return _more_
 */
public JComponent doMakeDescriptionPanel() {
    JScrollPane htmlScrollPane = new JScrollPane(getHtmlView());
    htmlScrollPane.setPreferredSize(new Dimension(400, 300));
    return htmlScrollPane;
}

From source file:ucar.unidata.idv.flythrough.Flythrough.java

/**
 * _more_//from   www .  j a  v a 2s .  co  m
 *
 * @param pt _more_
 *
 * @return _more_
 */
private boolean showProperties(FlythroughPoint pt) {
    try {
        DateTime[] times = viewManager.getAnimationWidget().getTimes();
        JComboBox timeBox = null;
        JLabel timeLabel = GuiUtils.rLabel("Time:");
        Vector timesList = new Vector();
        timesList.add(0, new TwoFacedObject("None", null));
        if ((times != null) && (times.length > 0)) {
            timesList.addAll(Misc.toList(times));
        }
        if ((pt.getDateTime() != null) && !timesList.contains(pt.getDateTime())) {
            timesList.add(pt.getDateTime());
        }
        timeBox = new JComboBox(timesList);
        if (pt.getDateTime() != null) {
            timeBox.setSelectedItem(pt.getDateTime());
        }

        LatLonWidget llw = new LatLonWidget("Latitude: ", "Longitude: ", "Altitude: ", null) {
            protected String formatLatLonString(String latOrLon) {
                return latOrLon;
            }
        };

        EarthLocation el = pt.getEarthLocation();
        llw.setLatLon(el.getLatitude().getValue(CommonUnit.degree),
                el.getLongitude().getValue(CommonUnit.degree));
        llw.setAlt(getAlt(el));

        JTextArea textArea = new JTextArea("", 5, 100);
        if (pt.getDescription() != null) {
            textArea.setText(pt.getDescription());
        }
        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setPreferredSize(new Dimension(400, 300));
        JComponent contents = GuiUtils.formLayout(new Component[] { GuiUtils.rLabel("Location:"), llw,
                timeLabel, GuiUtils.left(timeBox), GuiUtils.rLabel("Description:"), scrollPane });
        if (!GuiUtils.showOkCancelDialog(frame, "Point Properties", contents, null)) {
            return false;
        }
        pt.setDescription(textArea.getText());
        pt.setEarthLocation(makePoint(llw.getLat(), llw.getLon(), llw.getAlt()));
        Object selectedDate = timeBox.getSelectedItem();
        if (selectedDate instanceof TwoFacedObject) {
            pt.setDateTime(null);
        } else {
            pt.setDateTime((DateTime) selectedDate);
        }

        return true;
    } catch (Exception exc) {
        logException("Showing point properties", exc);
        return false;
    }

}

From source file:ucar.unidata.idv.flythrough.Flythrough.java

/**
 * _more_//w  w  w. j  a  va 2 s  .c om
 *
 * @return _more_
 */
public JComponent doMakePointsPanel() {

    pointTableModel = new FlythroughTableModel(this);
    pointTable = new JTable(pointTableModel);
    pointTable.setToolTipText("Double click: view; Control-P: Show point properties; Delete: delete point");

    pointTable.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
            if ((e.getKeyCode() == KeyEvent.VK_P) && e.isControlDown()) {
                List<FlythroughPoint> newPoints = new ArrayList<FlythroughPoint>();
                int[] rows = pointTable.getSelectedRows();
                List<FlythroughPoint> oldPoints = pointsToUse;
                for (int j = 0; j < rows.length; j++) {
                    FlythroughPoint pt = oldPoints.get(rows[j]);
                    if (!showProperties(pt)) {
                        break;
                    }
                    pointTable.repaint();
                }
            }

            if (GuiUtils.isDeleteEvent(e)) {
                List<FlythroughPoint> newPoints = new ArrayList<FlythroughPoint>();
                int[] rows = pointTable.getSelectedRows();
                List<FlythroughPoint> oldPoints = pointsToUse;
                for (int i = 0; i < oldPoints.size(); i++) {
                    boolean good = true;
                    for (int j = 0; j < rows.length; j++) {
                        if (i == rows[j]) {
                            good = false;
                            break;
                        }
                    }
                    if (good) {
                        newPoints.add(oldPoints.get(i));
                    }
                }
                flythrough(newPoints);
            }
        }
    });

    pointTable.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            final int row = pointTable.rowAtPoint(e.getPoint());
            if ((row < 0) || (row >= pointsToUse.size())) {
                return;
            }
            if (e.getClickCount() > 1) {
                animation.setCurrent(row);
            }
        }
    });

    JScrollPane scrollPane = new JScrollPane(pointTable);
    scrollPane.setPreferredSize(new Dimension(400, 300));
    return scrollPane;

}

From source file:eu.crisis_economics.abm.dashboard.Page_Parameters.java

@SuppressWarnings("serial")
private JPanel createParamsweepGUI() {

    // left/*ww w .j  ava  2  s  . c o  m*/
    parameterList = new JList();
    parameterList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    new ListAction(parameterList, new AbstractAction() {
        public void actionPerformed(final ActionEvent event) {
            final AvailableParameter selectedParameter = (AvailableParameter) parameterList.getSelectedValue();
            addParameterToTree(new AvailableParameter[] { selectedParameter }, parameterTreeBranches.get(0));
            enableDisableParameterCombinationButtons();
        }
    });
    parameterList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (!parameterList.isSelectionEmpty()) {
                boolean success = true;
                if (editedNode != null)
                    success = modify();

                if (success) {
                    cancelAllSelectionBut(parameterList);
                    resetSettings();
                    updateDescriptionField(parameterList.getSelectedValues());
                    enableDisableParameterCombinationButtons();
                } else
                    parameterList.clearSelection();
            }
        }
    });

    final JScrollPane parameterListPane = new JScrollPane(parameterList);
    parameterListPane.setBorder(BorderFactory.createTitledBorder("")); // for rounded border
    parameterListPane.setPreferredSize(new Dimension(300, 300));

    final JPanel parametersPanel = FormsUtils.build("p ' p:g", "[DialogBorder]00||" + "12||" + "34||" +
    //                                          "56||" + 
            "55||" + "66 f:p:g", new FormsUtils.Separator("<html><b>General parameters</b></html>"),
            NUMBER_OF_TURNS_LABEL_TEXT, numberOfTurnsFieldPSW, NUMBER_OF_TIMESTEPS_TO_IGNORE_LABEL_TEXT,
            numberTimestepsIgnoredPSW,
            //                                          UPDATE_CHARTS_LABEL_TEXT,onLineChartsCheckBoxPSW,
            new FormsUtils.Separator("<html><b>Model parameters</b></html>"), parameterListPane).getPanel();

    combinationsPanel = new JPanel(new GridLayout(0, 1, 5, 5));
    combinationsScrPane = new JScrollPane(combinationsPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    combinationsScrPane.setBorder(null);
    combinationsScrPane.setPreferredSize(new Dimension(550, 500));

    parameterDescriptionLabel = new JXLabel();
    parameterDescriptionLabel.setLineWrap(true);
    parameterDescriptionLabel.setVerticalAlignment(SwingConstants.TOP);
    final JScrollPane descriptionScrollPane = new JScrollPane(parameterDescriptionLabel);
    descriptionScrollPane.setBorder(BorderFactory.createTitledBorder(null, "Description", TitledBorder.LEADING,
            TitledBorder.BELOW_TOP));
    descriptionScrollPane.setPreferredSize(
            new Dimension(PARAMETER_DESCRIPTION_LABEL_WIDTH, PARAMETER_DESCRIPTION_LABEL_HEIGHT));
    descriptionScrollPane.setViewportBorder(null);

    final JButton addNewBoxButton = new JButton("Add new combination");
    addNewBoxButton.setActionCommand(ACTIONCOMMAND_ADD_BOX);

    final JPanel left = FormsUtils.build("p ~ f:p:g ~ p", "011 f:p:g ||" + "0_2 p", parametersPanel,
            combinationsScrPane, addNewBoxButton).getPanel();
    left.setBorder(BorderFactory.createTitledBorder(null, "Specify parameter combinations",
            TitledBorder.LEADING, TitledBorder.BELOW_TOP));
    Style.registerCssClasses(left, Dashboard.CSS_CLASS_COMMON_PANEL);

    final JPanel leftAndDesc = new JPanel(new BorderLayout());
    leftAndDesc.add(left, BorderLayout.CENTER);
    leftAndDesc.add(descriptionScrollPane, BorderLayout.SOUTH);
    Style.registerCssClasses(leftAndDesc, Dashboard.CSS_CLASS_COMMON_PANEL);

    // right
    editedParameterText = new JLabel(ORIGINAL_TEXT);
    editedParameterText.setPreferredSize(new Dimension(280, 40));
    constDef = new JRadioButton("Constant");
    listDef = new JRadioButton("List");
    incrDef = new JRadioButton("Increment");

    final JPanel rightTop = FormsUtils.build("p:g", "[DialogBorder]0||" + "1||" + "2||" + "3",
            editedParameterText, constDef, listDef, incrDef).getPanel();

    Style.registerCssClasses(rightTop, Dashboard.CSS_CLASS_COMMON_PANEL);

    constDefField = new JTextField();
    final JPanel constDefPanel = FormsUtils
            .build("p ~ p:g", "[DialogBorder]01 p", "Constant value: ", CellConstraints.TOP, constDefField)
            .getPanel();

    listDefArea = new JTextArea();
    final JScrollPane listDefScr = new JScrollPane(listDefArea,
            ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    final JPanel listDefPanel = FormsUtils.build("p ~ p:g", "[DialogBorder]01|" + "_1 f:p:g||" + "_2 p",
            "Value list: ", listDefScr, "(Separate values with spaces!)").getPanel();

    incrStartValueField = new JTextField();
    incrEndValueField = new JTextField();
    incrStepField = new JTextField();

    final JPanel incrDefPanel = FormsUtils.build("p ~ p:g", "[DialogBorder]01||" + "23||" + "45",
            "Start value: ", incrStartValueField, "End value: ", incrEndValueField, "Step: ", incrStepField)
            .getPanel();

    enumDefBox = new JComboBox(new DefaultComboBoxModel());
    final JPanel enumDefPanel = FormsUtils
            .build("p ~ p:g", "[DialogBorder]01 p", "Constant value:", CellConstraints.TOP, enumDefBox)
            .getPanel();

    submodelTypeBox = new JComboBox();
    final JPanel submodelTypePanel = FormsUtils
            .build("p ~ p:g", "[DialogBorder]01", "Constant value:", CellConstraints.TOP, submodelTypeBox)
            .getPanel();

    fileTextField = new JTextField();
    fileTextField.addKeyListener(new KeyAdapter() {
        public void keyTyped(final KeyEvent e) {
            final char character = e.getKeyChar();
            final File file = new File(Character.isISOControl(character) ? fileTextField.getText()
                    : fileTextField.getText() + character);
            fileTextField.setToolTipText(file.getAbsolutePath());
        }
    });
    fileBrowseButton = new JButton(BROWSE_BUTTON_TEXT);
    fileBrowseButton.setActionCommand(ACTIONCOMMAND_BROWSE);
    final JPanel fileDefPanel = FormsUtils
            .build("p ~ p:g ~p", "[DialogBorder]012", "File:", fileTextField, fileBrowseButton).getPanel();

    constDefPanel.setName("CONST");
    listDefPanel.setName("LIST");
    incrDefPanel.setName("INCREMENT");
    enumDefPanel.setName("ENUM");
    submodelTypePanel.setName("SUBMODEL");
    fileDefPanel.setName("FILE");

    Style.registerCssClasses(constDefPanel, Dashboard.CSS_CLASS_COMMON_PANEL);
    Style.registerCssClasses(listDefPanel, Dashboard.CSS_CLASS_COMMON_PANEL);
    Style.registerCssClasses(incrDefPanel, Dashboard.CSS_CLASS_COMMON_PANEL);
    Style.registerCssClasses(enumDefPanel, Dashboard.CSS_CLASS_COMMON_PANEL);
    Style.registerCssClasses(submodelTypePanel, Dashboard.CSS_CLASS_COMMON_PANEL);
    Style.registerCssClasses(fileDefPanel, Dashboard.CSS_CLASS_COMMON_PANEL);

    rightMiddle = new JPanel(new CardLayout());
    Style.registerCssClasses(rightMiddle, Dashboard.CSS_CLASS_COMMON_PANEL);
    rightMiddle.add(constDefPanel, constDefPanel.getName());
    rightMiddle.add(listDefPanel, listDefPanel.getName());
    rightMiddle.add(incrDefPanel, incrDefPanel.getName());
    rightMiddle.add(enumDefPanel, enumDefPanel.getName());
    rightMiddle.add(submodelTypePanel, submodelTypePanel.getName());
    rightMiddle.add(fileDefPanel, fileDefPanel.getName());

    modifyButton = new JButton("Modify");
    cancelButton = new JButton("Cancel");

    final JPanel rightBottom = FormsUtils
            .build("p:g p ~ p ~ p:g", "[DialogBorder]_01_ p", modifyButton, cancelButton).getPanel();

    Style.registerCssClasses(rightBottom, Dashboard.CSS_CLASS_COMMON_PANEL);

    final JPanel right = new JPanel(new BorderLayout());
    right.add(rightTop, BorderLayout.NORTH);
    right.add(rightMiddle, BorderLayout.CENTER);
    right.add(rightBottom, BorderLayout.SOUTH);
    right.setBorder(BorderFactory.createTitledBorder(null, "Parameter settings", TitledBorder.LEADING,
            TitledBorder.BELOW_TOP));

    Style.registerCssClasses(right, Dashboard.CSS_CLASS_COMMON_PANEL);

    // the whole paramsweep panel

    final JPanel content = FormsUtils.build("p:g p", "01 f:p:g", leftAndDesc, right).getPanel();
    Style.registerCssClasses(content, Dashboard.CSS_CLASS_COMMON_PANEL);

    sweepPanel = new JPanel();
    Style.registerCssClasses(sweepPanel, Dashboard.CSS_CLASS_COMMON_PANEL);
    sweepPanel.setLayout(new BorderLayout());
    final JScrollPane sp = new JScrollPane(content);
    sp.setBorder(null);
    sp.setViewportBorder(null);
    sweepPanel.add(sp, BorderLayout.CENTER);

    GUIUtils.createButtonGroup(constDef, listDef, incrDef);
    constDef.setSelected(true);
    constDef.setActionCommand("CONST");
    listDef.setActionCommand("LIST");
    incrDef.setActionCommand("INCREMENT");

    constDefField.setActionCommand("CONST_FIELD");
    incrStartValueField.setActionCommand("START_FIELD");
    incrEndValueField.setActionCommand("END_FIELD");
    incrStepField.setActionCommand("STEP_FIELD");

    modifyButton.setActionCommand("EDIT");
    cancelButton.setActionCommand("CANCEL");

    listDefArea.setLineWrap(true);
    listDefArea.setWrapStyleWord(true);
    listDefScr.setPreferredSize(new Dimension(100, 200));

    GUIUtils.addActionListener(this, modifyButton, cancelButton, constDef, listDef, incrDef, constDefField,
            incrStartValueField, incrEndValueField, incrStepField, addNewBoxButton, submodelTypeBox,
            fileBrowseButton);

    return sweepPanel;
}

From source file:edu.ku.brc.specify.tasks.subpane.qb.QueryBldrPane.java

/**
 * create the query builder UI.//from  w w  w.j  a v  a2s .co m
 */
protected void createUI() {
    removeAll();

    JMenuItem saveItem = new JMenuItem(UIRegistry.getResourceString("QB_SAVE"));
    Action saveActionListener = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            if (saveQuery(false)) {
                try {
                    String selId = null;
                    if (selectedQFP != null && selectedQFP.getQueryField() != null) {
                        selId = selectedQFP.getQueryField().getStringId();
                    }
                    final String selectedFldId = selId;
                    setupUI(true);
                    SwingUtilities.invokeLater(new Runnable() {

                        /* (non-Javadoc)
                         * @see java.lang.Runnable#run()
                         */
                        @Override
                        public void run() {
                            if (selectedFldId != null) {
                                for (QueryFieldPanel qfp : queryFieldItems) {
                                    if (qfp.getQueryField() != null
                                            && selectedFldId.equals(qfp.getQueryField().getStringId())) {
                                        selectQFP(qfp);
                                        return;
                                    }
                                }
                                selectQFP(queryFieldItems.get(0));
                            }
                        }

                    });
                } catch (Exception ex) {

                }
                setSaveBtnEnabled(false);
            }
        }
    };
    saveItem.addActionListener(saveActionListener);

    JMenuItem saveAsItem = new JMenuItem(UIRegistry.getResourceString("QB_SAVE_AS"));
    Action saveAsActionListener = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            if (saveQuery(true)) {
                setSaveBtnEnabled(false);
            }
        }
    };
    saveAsItem.addActionListener(saveAsActionListener);
    JComponent[] itemSample = { saveItem, saveAsItem };
    saveBtn = new DropDownButton(UIRegistry.getResourceString("QB_SAVE"), null, 1,
            java.util.Arrays.asList(itemSample));
    saveBtn.addActionListener(saveActionListener);
    String ACTION_KEY = "SAVE";
    KeyStroke ctrlS = KeyStroke.getKeyStroke(KeyEvent.VK_S,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
    InputMap inputMap = saveBtn.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    inputMap.put(ctrlS, ACTION_KEY);
    ActionMap actionMap = saveBtn.getActionMap();
    actionMap.put(ACTION_KEY, saveActionListener);
    ACTION_KEY = "SAVE_AS";
    KeyStroke ctrlA = KeyStroke.getKeyStroke(KeyEvent.VK_A,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
    inputMap.put(ctrlA, ACTION_KEY);
    actionMap.put(ACTION_KEY, saveAsActionListener);
    saveBtn.setActionMap(actionMap);

    UIHelper.setControlSize(saveBtn);
    //saveBtn.setOverrideBorder(true, BasicBorders.getButtonBorder());

    listBoxPanel = new JPanel(new HorzLayoutManager(2, 2));

    Vector<TableQRI> list = new Vector<TableQRI>();
    for (int k = 0; k < tableTree.getKids(); k++) {
        list.add(tableTree.getKid(k).getTableQRI());
    }

    Collections.sort(list);
    DefaultListModel model = new DefaultListModel();
    for (TableQRI qri : list) {
        model.addElement(qri);
    }

    tableList = new JList(model);
    QryListRenderer qr = new QryListRenderer(IconManager.IconSize.Std16);
    qr.setDisplayKidIndicator(false);
    tableList.setCellRenderer(qr);

    JScrollPane spt = new JScrollPane(tableList, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    Dimension pSize = spt.getPreferredSize();
    pSize.height = 200;
    spt.setPreferredSize(pSize);

    JPanel topPanel = new JPanel(new BorderLayout());

    scrollPane = new JScrollPane(listBoxPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

    tableList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                int inx = tableList.getSelectedIndex();
                if (inx > -1) {
                    fillNextList(tableList);
                } else {
                    listBoxPanel.removeAll();
                }
            }
        }
    });

    addBtn = new JButton(IconManager.getImage("PlusSign", IconManager.IconSize.Std16));
    addBtn.setEnabled(false);
    addBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            BaseQRI qri = (BaseQRI) listBoxList.get(currentInx).getSelectedValue();
            if (qri.isInUse) {
                return;
            }

            try {
                FieldQRI fieldQRI = buildFieldQRI(qri);
                if (fieldQRI == null) {
                    throw new Exception("null FieldQRI");
                }
                SpQueryField qf = new SpQueryField();
                qf.initialize();
                qf.setFieldName(fieldQRI.getFieldName());
                qf.setStringId(fieldQRI.getStringId());
                query.addReference(qf, "fields");

                if (!isExportMapping) {
                    addQueryFieldItem(fieldQRI, qf, false);
                } else {
                    addNewMapping(fieldQRI, qf, null, false);
                }
            } catch (Exception ex) {
                log.error(ex);
                UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(QueryBldrPane.class, ex);
                return;
            }
        }
    });

    contextPanel = new JPanel(new BorderLayout());
    contextPanel.add(createLabel("Search Context", SwingConstants.CENTER), BorderLayout.NORTH); // I18N
    contextPanel.add(spt, BorderLayout.CENTER);
    contextPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10));

    JPanel schemaPanel = new JPanel(new BorderLayout());
    schemaPanel.add(scrollPane, BorderLayout.CENTER);

    topPanel.add(contextPanel, BorderLayout.WEST);
    topPanel.add(schemaPanel, BorderLayout.CENTER);
    add(topPanel, BorderLayout.NORTH);

    queryFieldsPanel = new JPanel();
    queryFieldsPanel.setLayout(new NavBoxLayoutManager(0, 2));
    queryFieldsScroll = new JScrollPane(queryFieldsPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    queryFieldsScroll.setBorder(null);
    add(queryFieldsScroll);

    //if (!isExportMapping)
    //{
    final JPanel mover = buildMoverPanel(false);
    add(mover, BorderLayout.EAST);
    // }

    String searchLbl = schemaMapping == null ? getResourceString("QB_SEARCH")
            : getResourceString("QB_EXPORT_PREVIEW");
    searchBtn = createButton(searchLbl);
    searchBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            //               int m = ae.getModifiers();
            //               boolean ors = (m & ActionEvent.ALT_MASK) > 0 && (m & ActionEvent.CTRL_MASK) > 0 && (m & ActionEvent.SHIFT_MASK) > 0;
            //               if (ors)
            //               {
            //                  System.out.println("Disjunctional conjoinment desire gesture detected");
            //               }
            //               doSearch(ors);
            doSearch(false);
        }
    });
    distinctChk = createCheckBox(UIRegistry.getResourceString("QB_DISTINCT"));
    distinctChk.setVisible(schemaMapping == null);
    if (schemaMapping == null) {
        distinctChk.setSelected(false);
        distinctChk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                new SwingWorker() {

                    /* (non-Javadoc)
                     * @see edu.ku.brc.helpers.SwingWorker#construct()
                     */
                    @Override
                    public Object construct() {
                        if (distinctChk.isSelected()) {
                            UsageTracker.incrUsageCount("QB.DistinctOn");
                        } else {
                            UsageTracker.incrUsageCount("QB.DistinctOff");
                        }
                        if ((isTreeLevelSelected() || isAggFieldSelected()) && countOnly
                                && distinctChk.isSelected()) {
                            countOnlyChk.setSelected(false);
                            countOnly = false;
                        }
                        query.setCountOnly(countOnly);
                        query.setSelectDistinct(distinctChk.isSelected());
                        setSaveBtnEnabled(thereAreItems());
                        return null;
                    }
                }.start();
            }
        });
    }
    countOnlyChk = createCheckBox(UIRegistry.getResourceString("QB_COUNT_ONLY"));
    countOnlyChk.setSelected(false);
    countOnlyChk.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            new SwingWorker() {

                /* (non-Javadoc)
                 * @see edu.ku.brc.helpers.SwingWorker#construct()
                 */
                @Override
                public Object construct() {
                    //Don't allow change while query is running.
                    if (runningResults.get() == null) {
                        countOnly = !countOnly;
                        if (countOnly) {
                            UsageTracker.incrUsageCount("QB.CountOnlyOn");
                        } else {
                            UsageTracker.incrUsageCount("QB.CountOnlyOff");
                        }
                        if ((isTreeLevelSelected() || isAggFieldSelected()) && countOnly
                                && (distinctChk.isSelected() || searchSynonymyChk.isSelected())) {
                            distinctChk.setSelected(false);
                            searchSynonymyChk.setSelected(false);
                        }
                    } else {
                        //This might be awkward and/or klunky...
                        countOnlyChk.setSelected(countOnly);
                    }
                    query.setCountOnly(countOnly);
                    query.setSelectDistinct(distinctChk.isSelected());
                    setSaveBtnEnabled(thereAreItems());
                    return null;
                }
            }.start();
        }
    });

    searchSynonymyChk = createCheckBox(UIRegistry.getResourceString("QB_SRCH_SYNONYMS"));
    searchSynonymyChk.setSelected(searchSynonymy);
    searchSynonymyChk.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            new SwingWorker() {

                /* (non-Javadoc)
                 * @see edu.ku.brc.helpers.SwingWorker#construct()
                 */
                @Override
                public Object construct() {
                    searchSynonymy = !searchSynonymy;
                    if (!searchSynonymy) {
                        UsageTracker.incrUsageCount("QB.SearchSynonymyOff");
                    } else {
                        UsageTracker.incrUsageCount("QB.SearchSynonymyOn");
                    }
                    if (isTreeLevelSelected() && countOnly && searchSynonymyChk.isSelected()) {
                        countOnlyChk.setSelected(false);
                        countOnly = false;
                    }
                    query.setSearchSynonymy(searchSynonymy);
                    setSaveBtnEnabled(thereAreItems());
                    return null;
                }
            }.start();
        }
    });

    smushedChk = createCheckBox(UIRegistry.getResourceString("QB_SMUSH_RESULTS"));
    smushedChk.setVisible(isSmushableContext());
    if (isSmushableContext()) {
        smushedChk.setSelected(smushed);
        smushedChk.setToolTipText(
                String.format(UIRegistry.getResourceString("QB_SMUSH_RESULTS_HINT"), getCatalogNumberTitle()));
        smushedChk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                new SwingWorker() {

                    /*
                     * (non-Javadoc)
                     * 
                     * @see edu.ku.brc.helpers.SwingWorker#construct()
                     */
                    @Override
                    public Object construct() {
                        smushed = !smushed;
                        if (!smushed) {
                            UsageTracker.incrUsageCount("QB.SmushedOff");
                        } else {
                            UsageTracker.incrUsageCount("QB.SmushedOn");
                        }
                        query.setSmushed(smushed);
                        setSaveBtnEnabled(thereAreItems());
                        return null;
                    }
                }.start();
            }
        });
    }

    PanelBuilder outer = new PanelBuilder(
            new FormLayout("p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 6dlu, p", "p"));

    CellConstraints cc = new CellConstraints();
    outer.add(smushedChk, cc.xy(1, 1));
    outer.add(searchSynonymyChk, cc.xy(3, 1));
    outer.add(distinctChk, cc.xy(5, 1));
    outer.add(countOnlyChk, cc.xy(7, 1));
    outer.add(searchBtn, cc.xy(9, 1));
    outer.add(saveBtn, cc.xy(11, 1));

    JPanel bottom = new JPanel(new BorderLayout());
    bottom.add(outer.getPanel(), BorderLayout.EAST);

    JButton helpBtn = UIHelper.createHelpIconButton(getHelpBtnContext());
    bottom.add(helpBtn, BorderLayout.WEST);
    add(bottom, BorderLayout.SOUTH);

    setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
}

From source file:interfaces.InterfazPrincipal.java

private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
    String nombreCliente = nombreClienteReporteCliente.getText();
    String identificacion = identificacionClienteCliente.getText();
    try {/*from ww  w. ja  v a2 s.  c  o  m*/
        //08-11-2014 listar clientes por nombre
        ControladorCliente controladorCliente = new ControladorCliente();
        ArrayList<Cliente> listaClientes = new ArrayList<Cliente>();

        if (nombreCliente.equals("") && identificacion.equals("")) {
            listaClientes = controladorCliente.obtenerClientes();
        } else {
            int identificacionNumerico = 0;
            if (!identificacion.equals("")) {
                identificacionNumerico = Integer.parseInt(identificacion);
            }
            listaClientes = controladorCliente.obtenerClientes(nombreCliente, identificacionNumerico);
        }

        //08-11-2014 Crear dialogo de bsqueda
        final JDialog dialogoEditar = new JDialog(this);

        dialogoEditar.setTitle("Buscar clientes");
        dialogoEditar.setSize(300, 300);
        dialogoEditar.setResizable(false);

        JPanel panelDialogo = new JPanel();

        panelDialogo.setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;

        JLabel ediitarTextoPrincipalDialogo = new JLabel("Buscar cliente");
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 2;
        c.insets = new Insets(10, 60, 10, 10);
        Font textoGrande = new Font("Arial", 1, 16);
        ediitarTextoPrincipalDialogo.setFont(textoGrande);
        panelDialogo.add(ediitarTextoPrincipalDialogo, c);

        c.gridx = 0;
        c.gridy = 1;
        c.gridwidth = 2;
        c.insets = new Insets(10, 10, 10, 10);
        final JTable tablaDialogo = new JTable();
        DefaultTableModel modeloTabla = new DefaultTableModel() {

            @Override
            public boolean isCellEditable(int row, int column) {
                //all cells false
                return false;
            }
        };
        ;

        modeloTabla.addColumn("Identificacin");
        modeloTabla.addColumn("Nombre");

        //LLenar tabla
        for (int i = 0; i < listaClientes.size(); i++) {
            Object[] data = { "1", "2" };
            data[0] = listaClientes.get(i).getCliente_id();
            data[1] = listaClientes.get(i).getNombre();
            modeloTabla.addRow(data);
        }

        tablaDialogo.setModel(modeloTabla);
        tablaDialogo.getColumn("Identificacin").setMinWidth(110);
        tablaDialogo.getColumn("Nombre").setMinWidth(110);
        tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scroll = new JScrollPane(tablaDialogo);
        scroll.setPreferredSize(new Dimension(220, 150));

        panelDialogo.add(scroll, c);

        c.insets = new Insets(0, 0, 0, 10);
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 1;
        JButton botonGuardarClienteDialogo = new JButton("Elegir");
        panelDialogo.add(botonGuardarClienteDialogo, c);

        c.gridx = 1;
        c.gridy = 2;
        c.gridwidth = 1;
        JButton botonCerrarClienteDialogo = new JButton("Cancelar");
        panelDialogo.add(botonCerrarClienteDialogo, c);

        dialogoEditar.add(panelDialogo);
        dialogoEditar.setVisible(true);

        botonCerrarClienteDialogo.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                dialogoEditar.dispose();
            }
        });

        botonGuardarClienteDialogo.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                int row = tablaDialogo.getSelectedRow();
                if (row == -1) {
                    JOptionPane.showMessageDialog(dialogoEditar, "Por favor seleccione una fila");

                } else {
                    Object identificacionCliente = tablaDialogo.getValueAt(row, 0);
                    jTextFieldIdentificacionClienteReporte.setText(String.valueOf(identificacionCliente));
                    botonGenerarReporteCliente.setEnabled(true);
                    dialogoEditar.dispose();

                }

            }
        }); // TODO add your handling code here:     
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "El valor de la identificacin de ser numrico");

    }

}

From source file:interfaces.InterfazPrincipal.java

private void botonAgregarProductoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAgregarProductoActionPerformed
    String nombre = jTextField_Factura_Producto_Nombre.getText();
    String descripcion = jTextField_Factura_Producto_Descripcion.getText();
    ControladorProducto controladorPro = new ControladorProducto();
    String restriccion = "";

    boolean encounter = true;

    if (!nombre.equals("")) {
        if (encounter) {
            encounter = false;//from   ww w .j  a  v  a  2  s.  co m
            restriccion = " where ";
        } else {
            restriccion += " OR ";
        }

        restriccion += " nombre like '%" + nombre + "%'";
    }

    if (!descripcion.equals("")) {
        if (encounter) {
            encounter = false;
            restriccion = " where ";
        } else {
            restriccion += " OR ";
        }

        restriccion += " descripcion like '%" + descripcion + "%'";
    }

    ArrayList<Productos> listaDeProductos = controladorPro.getProducto(restriccion);

    final JDialog dialogoEditar = new JDialog(this);
    dialogoEditar.setTitle("Buscar clientes");
    dialogoEditar.setSize(600, 310);
    dialogoEditar.setResizable(false);

    JPanel panelDialogo = new JPanel();

    panelDialogo.setLayout(new GridBagLayout());

    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;

    JLabel editarTextoPrincipalDialogo = new JLabel("Buscar Producto");
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 6;
    c.insets = new Insets(15, 200, 40, 0);
    c.ipadx = 100;
    Font textoGrande = new Font("Arial", 1, 18);
    editarTextoPrincipalDialogo.setFont(textoGrande);
    panelDialogo.add(editarTextoPrincipalDialogo, c);

    final JTable table = new JTable();
    DefaultTableModel modeloTabla = new DefaultTableModel() {

        @Override
        public boolean isCellEditable(int row, int column) {
            //all cells false
            return false;
        }
    };
    ;

    modeloTabla.addColumn("Numero");
    modeloTabla.addColumn("Identificacin");
    modeloTabla.addColumn("Nombre");
    modeloTabla.addColumn("Descripcion");
    modeloTabla.addColumn("Unidades Disponibles");
    modeloTabla.addColumn("Precio");

    //LLenar tabla
    for (int i = 0; i < listaDeProductos.size(); i++) {
        Object[] data = { "1", "2", "3", "4", "5", "6" };
        data[0] = (i + 1);
        data[1] = listaDeProductos.get(i).getProductoId();
        data[2] = listaDeProductos.get(i).getNombre();
        data[3] = listaDeProductos.get(i).getDescripcion();
        data[4] = listaDeProductos.get(i).getUnidadesDisponibles();
        data[5] = listaDeProductos.get(i).getPrecio();

        modeloTabla.addRow(data);
    }

    table.setModel(modeloTabla);
    table.getColumn("Numero").setMinWidth(50);
    table.getColumn("Identificacin").setMinWidth(50);
    table.getColumn("Nombre").setMinWidth(110);
    table.getColumn("Descripcion").setMinWidth(110);
    table.getColumn("Unidades Disponibles").setMinWidth(40);
    table.getColumn("Precio").setMinWidth(110);

    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scroll = new JScrollPane(table);
    scroll.setPreferredSize(new Dimension(320, 150));

    //final JTable table = new JTable(row, col);       
    table.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            //jTextField_Factura_Cliente_Id.setText(table.getValueAt(table.getSelectedRow(), 1).toString());
            //System.out.println(table.getValueAt(table.getSelectedRow(), 3).toString());
            DefaultTableModel modelo = (DefaultTableModel) TablaDeFacturaProducto.getModel();

            Object[] fila = new Object[7];

            fila[0] = table.getValueAt(table.getSelectedRow(), 0).toString();
            fila[1] = table.getValueAt(table.getSelectedRow(), 1).toString();
            fila[2] = table.getValueAt(table.getSelectedRow(), 2).toString();
            fila[3] = table.getValueAt(table.getSelectedRow(), 3).toString();
            //fila[4] = table.getValueAt(table.getSelectedRow(), 4).toString();
            fila[4] = (String) JOptionPane.showInputDialog("Ingrese el nmero de unidades que va a vender");
            fila[5] = table.getValueAt(table.getSelectedRow(), 5).toString();

            Double valorProducto = Double.parseDouble((String) fila[5]);
            String valorActualProducto = String.valueOf(Double.parseDouble(valorActualFactura.getText())
                    + Double.parseDouble((String) fila[4]) * valorProducto);
            valorActualFactura.setText(valorActualProducto);
            fila[6] = Double.parseDouble((String) fila[4]) * valorProducto;
            modelo.addRow(fila);
            //modelo.getColumnName(4).
            /*TablaDeFacturaProducto.setModel(modelo);
             TablaDeFacturaProducto.getColumnClass(4). ;*/
            dialogoEditar.dispose();
        }
    });

    c.insets = new Insets(0, 5, 10, 0);
    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 1;
    c.ipadx = 200;

    panelDialogo.add(scroll, c);

    //panelDialogo.add(table, c);
    dialogoEditar.add(panelDialogo);
    dialogoEditar.setVisible(true);

}