Wednesday, May 8, 2013

JTextField Auto Completion






/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package text;


import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.event.*;

public class TextFileAutoComplete {

    public static void main(String[] args) throws Exception {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        JFrame frame = new JFrame();
        frame.setTitle("Auto Completion Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(200, 200, 500, 400);

        ArrayList items = new ArrayList();
        Locale[] locales = Locale.getAvailableLocales();
        for (int i = 0; i < locales.length; i++) {
            String item = locales[i].getDisplayName();
            items.add(item);
        }
        JTextField txtInput = new JTextField();
        setupAutoComplete(txtInput, items);
        txtInput.setColumns(30);
        frame.getContentPane().setLayout(new FlowLayout());
        frame.getContentPane().add(txtInput, BorderLayout.NORTH);
        frame.setVisible(true);
    }

    private static boolean isAdjusting(JComboBox cbInput) {
        if (cbInput.getClientProperty("is_adjusting") instanceof Boolean) {
            return (Boolean) cbInput.getClientProperty("is_adjusting");
        }
        return false;
    }

    private static void setAdjusting(JComboBox cbInput, boolean adjusting) {
        cbInput.putClientProperty("is_adjusting", adjusting);
    }

    public static void setupAutoComplete(final JTextField txtInput, final List items) {
        final DefaultComboBoxModel model = new DefaultComboBoxModel();
        final JComboBox cbInput = new JComboBox(model) {
            public Dimension getPreferredSize() {
                return new Dimension(super.getPreferredSize().width, 0);
            }
        };
        setAdjusting(cbInput, false);
        for (String item : items) {
            model.addElement(item);
        }
        cbInput.setSelectedItem(null);
        cbInput.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!isAdjusting(cbInput)) {
                    if (cbInput.getSelectedItem() != null) {
                        txtInput.setText(cbInput.getSelectedItem().toString());
                    }
                }
            }
        });

        txtInput.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                setAdjusting(cbInput, true);
                if (e.getKeyCode() == KeyEvent.VK_SPACE) {
                    if (cbInput.isPopupVisible()) {
                        e.setKeyCode(KeyEvent.VK_ENTER);
                    }
                }
                if (e.getKeyCode() == KeyEvent.VK_ENTER || e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN) {
                    e.setSource(cbInput);
                    cbInput.dispatchEvent(e);
                    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                        txtInput.setText(cbInput.getSelectedItem().toString());
                        cbInput.setPopupVisible(false);
                    }
                }
                if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                    cbInput.setPopupVisible(false);
                }
                setAdjusting(cbInput, false);
            }
        });
        txtInput.getDocument().addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {
                updateList();
            }

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

            public void changedUpdate(DocumentEvent e) {
                updateList();
            }

            private void updateList() {
                setAdjusting(cbInput, true);
                model.removeAllElements();
                String input = txtInput.getText();
                if (!input.isEmpty()) {
                    for (String item : items) {
                        if (item.toLowerCase().startsWith(input.toLowerCase())) {
                            model.addElement(item);
                        }
                    }
                }
                cbInput.setPopupVisible(model.getSize() > 0);
                setAdjusting(cbInput, false);
            }
        });
        txtInput.setLayout(new BorderLayout());
        txtInput.add(cbInput, BorderLayout.SOUTH);
    }
}

Monday, May 6, 2013

JTable with GradiantColorTableCellRenderer

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package text;


public class ResultViewTableJPanel extends javax.swing.JPanel {

    /**
     * Creates new form ResultViewTableJPanel
     */
    public ResultViewTableJPanel() {
        initComponents();
    }

    public void init() {
        for (int i = 0; i < resultTable.getColumnCount(); i++) {
            resultTable.getColumnModel().getColumn(i).setCellRenderer(new TableCellRenderer());
        }        
        resultTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                // Open popup
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    });
                }
            }
        });
    }

    public void searchResult(final BasicSearchInfoParam basicSearchInfoParam) {
        resultList.clear();
        bottomPanel.removeAll();
        bottomPanel.add(progressPanel, BorderLayout.CENTER);
        bottomPanel.validate();
        bottomPanel.repaint();

        SwingWorker sw = new SwingWorker() {
            @Override
            protected Object doInBackground() throws Exception {
                Thread.sleep(200);
                // Fill resultList with beans
                int start = 0;
                if (!resultList.isEmpty()) {
                    start = QuickSearch.getFrom() + 1;

                    int count = quickSearch.getScoreDocsArray().length;
                    if (quickSearch.getPage() > 1) {
                        previousButton.setEnabled(true);
                    } else {
                        previousButton.setEnabled(false);
                    }
                    if ((quickSearch.getTotalPages() - quickSearch.getPage()) > 0) {
                        nextButton.setEnabled(true);
                    } else {
                        nextButton.setEnabled(false);
                    }

                    resultCountLabel.setText("Showing results from " + start + " to " + (caseQuickSearch.getEnd())
                            + " of " + count + "");
                } else {
                    resultCountLabel.setText(" No results found.");
                }
                return true;
            }

            @Override
            protected void done() {
                super.done();
                try {
                    get();
                } catch (Exception e) {
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(IndLawExecutor.getSingleInstance(), "Exception : " + e.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
                } finally {
                    bottomPanel.removeAll();
                    bottomPanel.add(navigationPanel, BorderLayout.CENTER);
                    bottomPanel.validate();
                    bottomPanel.repaint();
                }
            }
        };
        Executors.newCachedThreadPool().submit(sw);
    }

    private void displayResult(final String action) {
        resultList.clear();
        bottomPanel.removeAll();
        bottomPanel.add(progressPanel, BorderLayout.CENTER);
        bottomPanel.validate();
        bottomPanel.repaint();

        SwingWorker sw = new SwingWorker() {
            @Override
            protected Object doInBackground() throws Exception {
                Thread.sleep(200);
                CaseQuickSearch caseQuickSearch = CaseQuickSearch.getInstance();
                caseQuickSearch.loadNavigationDocs(action, resultList);
                int start = 0;
                if (!resultList.isEmpty()) {
                    start = caseQuickSearch.getFrom() + 1;

                    int count = caseQuickSearch.getScoreDocsArray().length;
                    if (caseQuickSearch.getPage() > 1) {
                        previousButton.setEnabled(true);
                    } else {
                        previousButton.setEnabled(false);
                    }
                    if ((caseQuickSearch.getTotalPages() - caseQuickSearch.getPage()) > 0) {
                        nextButton.setEnabled(true);
                    } else {
                        nextButton.setEnabled(false);
                    }
                    resultCountLabel.setText("Showing results from " + start + " to " + (caseQuickSearch.getEnd())
                            + " of " + count + "");

                } else {
                    resultCountLabel.setText(" No results found.");
                }
                return true;
            }

            @Override
            protected void done() {
                super.done();
                try {
                    get();
                } catch (Exception e) {
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(IndLawExecutor.getSingleInstance(), "Exception : " + e.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
                } finally {
                    bottomPanel.removeAll();
                    bottomPanel.add(navigationPanel, BorderLayout.CENTER);
                    bottomPanel.validate();
                    bottomPanel.repaint();
                }
            }
        };
        Executors.newCachedThreadPool().submit(sw);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // //GEN-BEGIN:initComponents
    private void initComponents() {
        info.clearthought.layout.TableLayout _tableLayoutInstance;
        info.clearthought.layout.TableLayout _tableLayoutInstance1;
        info.clearthought.layout.TableLayout _tableLayoutInstance2;
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        resultList = org.jdesktop.observablecollections.ObservableCollections.observableList(new ArrayList());
        progressPanel = new javax.swing.JPanel();
        progressLabel = new javax.swing.JLabel();
        navigationPanel = new javax.swing.JPanel();
        verticalDividerLabel = new javax.swing.JLabel();
        resultCountLabel = new javax.swing.JLabel();
        previousButton = new javax.swing.JButton();
        nextButton = new javax.swing.JButton();
        resultBasePanel = new javax.swing.JPanel();
        resultScrollPane = new javax.swing.JScrollPane();
        resultTable = new javax.swing.JTable();
        hDividerLabel = new javax.swing.JLabel();
        bottomPanel = new javax.swing.JPanel();

        progressPanel.setOpaque(false);
        progressPanel.setLayout(new java.awt.BorderLayout());

        progressLabel.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
        progressLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        progressLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/icons/ajax-loader4_30x30.gif"))); // NOI18N
        progressLabel.setText("Processing...");
        progressPanel.add(progressLabel, java.awt.BorderLayout.CENTER);

        navigationPanel.setBackground(new java.awt.Color(192, 192, 192));
        _tableLayoutInstance2 = new info.clearthought.layout.TableLayout();
        _tableLayoutInstance2.setHGap(10);
        _tableLayoutInstance2.setVGap(0);
        _tableLayoutInstance2.setColumn(new double[]{1,info.clearthought.layout.TableLayout.PREFERRED,info.clearthought.layout.TableLayout.FILL,34,34,0});
        _tableLayoutInstance2.setRow(new double[]{info.clearthought.layout.TableLayout.FILL,28,info.clearthought.layout.TableLayout.FILL,7});
        navigationPanel.setLayout(_tableLayoutInstance2);

        verticalDividerLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/icons/hori-dividerLong.png"))); // NOI18N
        navigationPanel.add(verticalDividerLabel, new info.clearthought.layout.TableLayoutConstraints(0, 3, 5, 3, info.clearthought.layout.TableLayout.FULL, info.clearthought.layout.TableLayout.FULL));

        resultCountLabel.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        resultCountLabel.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        navigationPanel.add(resultCountLabel, new info.clearthought.layout.TableLayoutConstraints(1, 1, 1, 1, info.clearthought.layout.TableLayout.FULL, info.clearthought.layout.TableLayout.FULL));

        previousButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/icons/previous_small.png"))); // NOI18N
        previousButton.setToolTipText("Previous");
        previousButton.setContentAreaFilled(false);
        previousButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        previousButton.setEnabled(false);
        previousButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                previousButtonActionPerformed(evt);
            }
        });
        navigationPanel.add(previousButton, new info.clearthought.layout.TableLayoutConstraints(3, 1, 3, 1, info.clearthought.layout.TableLayout.FULL, info.clearthought.layout.TableLayout.FULL));

        nextButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/icons/next_small.png"))); // NOI18N
        nextButton.setToolTipText("Next");
        nextButton.setContentAreaFilled(false);
        nextButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        nextButton.setEnabled(false);
        nextButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextButtonActionPerformed(evt);
            }
        });
        navigationPanel.add(nextButton, new info.clearthought.layout.TableLayoutConstraints(4, 1, 4, 1, info.clearthought.layout.TableLayout.FULL, info.clearthought.layout.TableLayout.FULL));

        setOpaque(false);
        _tableLayoutInstance = new info.clearthought.layout.TableLayout();
        _tableLayoutInstance.setHGap(0);
        _tableLayoutInstance.setVGap(0);
        _tableLayoutInstance.setColumn(new double[]{info.clearthought.layout.TableLayout.FILL});
        _tableLayoutInstance.setRow(new double[]{info.clearthought.layout.TableLayout.FILL});
        setLayout(_tableLayoutInstance);

        resultBasePanel.setOpaque(false);
        _tableLayoutInstance1 = new info.clearthought.layout.TableLayout();
        _tableLayoutInstance1.setHGap(0);
        _tableLayoutInstance1.setVGap(0);
        _tableLayoutInstance1.setColumn(new double[]{info.clearthought.layout.TableLayout.FILL});
        _tableLayoutInstance1.setRow(new double[]{info.clearthought.layout.TableLayout.FILL,info.clearthought.layout.TableLayout.PREFERRED,50});
        resultBasePanel.setLayout(_tableLayoutInstance1);

        Border empty = new EmptyBorder(0,0,0,0);
        //resultScrollPane.setBorder(empty);
        resultScrollPane.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        resultScrollPane.getViewport().setOpaque(false);
        //resultScrollPane.getViewport().setBorder(null);
        resultScrollPane.setOpaque(false);

        //resultTable.setShowGrid(false);
        resultTable.setBorder(null);
        resultTable.setTableHeader(null);
        resultTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        resultTable.setOpaque(false);
        resultTable.setRowHeight(70);
        resultTable.setShowVerticalLines(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, resultList, resultTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${caseId}"));
        columnBinding.setColumnName("Case Id");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        resultScrollPane.setViewportView(resultTable);

        resultBasePanel.add(resultScrollPane, new info.clearthought.layout.TableLayoutConstraints(0, 0, 0, 0, info.clearthought.layout.TableLayout.FULL, info.clearthought.layout.TableLayout.FULL));

        hDividerLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/icons/hori-dividerLongR.png"))); // NOI18N
        resultBasePanel.add(hDividerLabel, new info.clearthought.layout.TableLayoutConstraints(0, 1, 0, 1, info.clearthought.layout.TableLayout.FULL, info.clearthought.layout.TableLayout.FULL));

        bottomPanel.setOpaque(false);
        bottomPanel.setLayout(new java.awt.BorderLayout());
        resultBasePanel.add(bottomPanel, new info.clearthought.layout.TableLayoutConstraints(0, 2, 0, 2, info.clearthought.layout.TableLayout.FULL, info.clearthought.layout.TableLayout.FULL));

        add(resultBasePanel, new info.clearthought.layout.TableLayoutConstraints(0, 0, 0, 0, info.clearthought.layout.TableLayout.FULL, info.clearthought.layout.TableLayout.FULL));

        bindingGroup.bind();
    }// //GEN-END:initComponents

    private void previousButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_previousButtonActionPerformed
        // TODO add your handling code here:
        displayResult("previous");
    }//GEN-LAST:event_previousButtonActionPerformed

    private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextButtonActionPerformed
        // TODO add your handling code here:
        displayResult("next");
    }//GEN-LAST:event_nextButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel bottomPanel;
    private javax.swing.JLabel hDividerLabel;
    private javax.swing.JPanel navigationPanel;
    private javax.swing.JButton nextButton;
    private javax.swing.JButton previousButton;
    private javax.swing.JLabel progressLabel;
    private javax.swing.JPanel progressPanel;
    private javax.swing.JPanel resultBasePanel;
    private javax.swing.JLabel resultCountLabel;
    private java.util.List resultList;
    private javax.swing.JScrollPane resultScrollPane;
    private javax.swing.JTable resultTable;
    private javax.swing.JLabel verticalDividerLabel;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    private class CaseTableCellRenderer extends GradientLabel implements TableCellRenderer {

        private Color normalColor = new Color(211, 211, 211);
        public CaseTableCellRenderer() {
            setVerticalAlignment(JLabel.TOP);
            setOpaque(false);
            setBgColor(normalColor);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            SearchDisplayBean bean = resultList.get(table.convertRowIndexToModel(row));
            setText("" + bean.getDisplayText());
            if (isSelected) {
                setBgColor(table.getSelectionBackground());
            }else{
                setBgColor(normalColor);
            }
            if ((bean.getPetitioner().length() > 50) || (bean.getRespondent().length() > 50)) {
                setToolTipText(bean.getToolTipText());
            } else {
                setToolTipText(null);
            }
            return this;
        }
    }
}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tr.indlaw.design.resultView;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.LinearGradientPaint;
import java.awt.Paint;
import javax.swing.JLabel;

public class GradientLabel extends JLabel {

    /**
     * Creates new form GradientLabel
     */
    public GradientLabel() {
        initComponents();
    }

    public void setBgColor(Color bgColor) {
        start = bgColor;
        repaint();
    }
    
    @Override
    public void paint(Graphics g) {
        int width = getWidth();
        int height = getHeight();
        
        colors[0] = start;
        colors[1] = start.brighter();
        colors[2] = start;
        // Create the gradient paint
        //GradientPaint paint = new GradientPaint(0, 0, start, width, height, end, true);

        LinearGradientPaint paint = new LinearGradientPaint(0, 0, 0, getHeight(), dist, colors);

        // we need to cast to Graphics2D for this operation
        Graphics2D g2d = (Graphics2D) g;

        // save the old paint
        Paint oldPaint = g2d.getPaint();

        // set the paint to use for this operation
        g2d.setPaint(paint);

        // fill the background using the paint
        g2d.fillRect(0, 0, width, height);

        // restore the original paint
        g2d.setPaint(oldPaint);

        super.paint(g);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // //GEN-BEGIN:initComponents
    private void initComponents() {

        setOpaque(true);
    }// //GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
    private Color start;
    float[] dist = {0.0f, 0.5f, 1.0f};
    private Color[] colors = new Color[3];
}