Friday, April 28, 2017

[Solved] Sort JTable progrommatically and by clicking column header

A. Sort by clicking at column header

1. Set all column headers clickable for sorting

JTable table = new JTable();
table.setModel(new MyTableModel());

//This will allow sort by clicking column header
table.setAutoCreateRowSorter(true);

//To programmatically reverse the order of sorting of a column
table.getRowSorter().toggleSortOrder(<columnIndex>);

2. Set sorting by a particular column in the beggining
     
TableRowSorter<MyTableModel> sorter = new TableRowSorter<>(table.getModel());
table.setRowSorter(sorter);
//or
//table.setAutoCreateRowSorter(true);
//DefaultRowSorter sorter = (DefaultRowSorter)table.getRowSorter();

List<RowSorter.SortKey> sortKeys = new ArrayList<>();
sortKeys.add(new RowSorter.SortKey(<columnIndex>, SortOrder.ASCENDING));

sorter.setSortKeys(sortKeys);


B. Sort programmatically on values in one column


public class SortableVector<E> extends Vector<E> implements Comparable<E> {
      public SortableVector(List values) {
            super(vaules);
        }

      public int compareTo(Object obj) {
            SortableVector<E> r2 = (SortableVector<E>) obj;
            Object v1 = get(<columnIndex>);
            Object v2 = r2.get(<columnIndex>);

           if (v1 <= v2) {
                 return -1;
           }
           return 1;
      }
}

public class MyTableModel extends DefaultTableModel{
      public void sort() {
            Vector<SortableVector<Object>> data = getDataVector();
            Collections.sort(data);
        }
}

MyTableModel model = new MyTableModel();
model.addRow(new SortableVector<>(Arrays.asList(new String[] {"Apple", "East Street"})));
mode.addRow(new SortableVector<>(Arrays.asList(new String[] {"Orange", "Main Ave"})));
mode.addRow(new SortableVector<>(Arrays.asList(new String[] {"Mangle", "5th Street"})));

JTable table = new JTable();
table.setModel(model);

//When data is changed, call the sort() method.
if (table.getCellEditor() != null) {
      table.getCellEditor().stopCellEditing();
}
model.sort();
model.fireTableDataChanged();

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


[Solved] Set the row height and column width of JTable

import javax.swing.JTable;

public class TableTest {
      public static void main(String[] args) {
            JTable myTable = new JTable();

           //Set the height of  all rows
            myTable.setRowHeight(50);
           //myTable.setRowHeight(myTable.getRowHeight() + 10);

          //Set the height of one particular row.
          //Works only after calling the setModel method of JTable
          //Need to reset each time table data is modified
          //set the height of row 3 to 50
         MyTableModel model = new MyTableModel();
          myTable.setModel(model);
         myTable.setRowHeight(3, 50);
        //myTable.setRowHeight(3, myTable.getRowHeight(3) + 10);

        model.addTableModelListener(new TableModelListener() { 

             @Override 
            public void   tableChanged(final TableModelEvent e) { 
                  EventQueue.invokeLater(new Runnable() {  
                       @Override 
                       public void run() { 
                              myTable.setRowHeight(3, 50); 
                      } 
                }); 
             } 
         });

         //Set column width         
        TableColumnModel columnModel = myTable.getColumnModel();
         columnModel.getColumn(0).setPreferredWidth(200);
         columnModel.getColumn(1).setPreferredWidth(120);
         columnModel.getColumn(2).setPreferredWidth(150);
        columnModel.getColumn(3).setPreferredWidth(180);
    }
}

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

[Solved] JComboBox in JTable automatically displays a selected value other than the value in table model when clicked

A. The problem


The code below create a two column table that displays the name and department of employees. When the combo box with a list of department is clicked, it will spontaneously display a selected value other than the original value.

public class TableTest extends JFrame{
    private JTable table;
    private DefaultTableModel model;
    private JComboBox<String> comboBox;
    private DefaultComboBoxModel<String> deptData;
 
    public TableTest(){
        model = new MyTableModel();
        model.addRow(new String[]{"John Smith", "Human Resource"});
        model.addRow(new String[]{"Jane Shaw", "Human Resource"});
        model.addRow(new String[]{"Dalene Young", "Sale"});
        table = new JTable();
        table.setRowHeight(table.getRowHeight()+10);
        table.setModel(model);
        table.getColumn("Department").setCellEditor(new MyCellEditor());
        table.getColumn("Department").setCellRenderer(new MyCellRenderer());
        deptData = new DefaultComboBoxModel<>();
        deptData.addElement("Production");
        deptData.addElement("Sale");
        deptData.addElement("Customer Support");
        deptData.addElement("Human Resource");
     
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
     
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(300, 200);
        setVisible(true);
    }
 
    public class MyTableModel extends DefaultTableModel {
        String[] cols = {"Name", "Department"};
     
        public MyTableModel() {
            super();
            setColumnIdentifiers(cols);
        }
     
        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return true;
        }
     
        @Override
        public Class<? extends Object> getColumnClass(int columnIndex) {
            if (columnIndex == 1){
                return JComboBox.class;
            }
            return String.class;
        }
    }
 
    private class MyCellEditor extends AbstractCellEditor implements TableCellEditor, ItemListener, PopupMenuListener{
        private int theRow = 0;
        private boolean served = false;
        private String theDept = "";
     
        @Override
        public String getCellEditorValue() {
            return theDept;
        }
     
        @Override
        public Component getTableCellEditorComponent(JTable t, Object v, boolean seleted, int row, int col){
            theRow = row;
            theDept = (String)table.getValueAt(row, 1);
            comboBox = new JComboBox<>(deptData);
            comboBox.addPopupMenuListener(this);
            comboBox.addItemListener(this);
            comboBox.setSelectedItem(theDept);
            served = false;
            return comboBox;
        }
     
        @Override
        public void itemStateChanged(ItemEvent e){
            if(e.getStateChange() == ItemEvent.DESELECTED){
                return;
            }

            if(served){
                return;
            }
            JComboBox<String> combo = (JComboBox<String>) e.getSource();
            String dep = (String) combo.getSelectedItem();
            if (table.getCellEditor() != null)
                table.getCellEditor().stopCellEditing();
            combo.setSelectedItem(dep);
            model.setValueAt(dep, theRow, 1);

            served = true;
        }
     
        @Override
        public void popupMenuCanceled(PopupMenuEvent e){
            System.out.println("popup canceled...");
            if (table.getCellEditor() != null)
                table.getCellEditor().stopCellEditing();
        }
   
        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            System.out.println("popup to be invisible...");
            if (table.getCellEditor() != null)
                table.getCellEditor().stopCellEditing();
//            model.fireTableDataChanged();
        }
     
        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            System.out.println("popup to be visible...");
        }
    }

    private class MyCellRenderer extends DefaultTableCellRenderer {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

            JComboBox<String> comp = new JComboBox<>(deptData);
            String v = (String) table.getValueAt(row, 1);
            comp.setSelectedItem(v);
            return comp;
        }
    }

    public static void main(String[] args){
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TableTest();
            }
        });
    }
}

Once the code is executed, it looks like this.



Then you click on the Department combo box, it automatically select Sale before you select anything. And even worse, it does not allow you to select any value.



B. The solution


For the code to work properly:
1. Add a mouse listener to the JTable. In the mouseReleased() method, set the current selected value in the editing JComboBox to the corresponding current value in the table model, so that it will display the correct value when clicked.

2. The getCellEditorValue() in the Cell Editor class must return the newly selected value identified in the Item Listener, so that the cell renderer can use it to render the cell.

3. Each time the table data is changed, call the stopCellEditing() of the Cell Editor and fireTableDataChanged() of the Table Model to let the change be notified to all listeners. 

4. Add an editingCombo field to determine when the ItemStateChanged() method to be executed.

The code below works properly. The modified codes are highlighted.

public class TableTest extends JFrame{
    private JTable table;
    private DefaultTableModel model;
    private JComboBox<String> comboBox;
    private DefaultComboBoxModel<String> deptData;
    private boolean editingCombo = false;
    
    public TableTest(){
        deptData = new DefaultComboBoxModel<>();
        deptData.addElement("Production");
        deptData.addElement("Sale");
        deptData.addElement("Customer Support");
        deptData.addElement("Human Resource");
        
        model = new MyTableModel();
        model.addRow(new String[]{"John Smith", "Human Resource"});
        model.addRow(new String[]{"Jane Shaw", "Human Resource"});
        model.addRow(new String[]{"Dalene Young", "Sale"});
        
        table = new JTable();
        table.setRowHeight(table.getRowHeight()+10);
        table.setModel(model);
        table.getColumn("Department").setCellEditor(new MyCellEditor());
        table.getColumn("Department").setCellRenderer(new MyCellRenderer());

        table.addMouseListener(new MyMouseListener());
        
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
        
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(300, 200);
        setVisible(true);
    }
    
    public class MyTableModel extends DefaultTableModel {
        String[] cols = {"Name", "Department"};
        
        public MyTableModel() {
            super();
            setColumnIdentifiers(cols);
        }
        
        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return true;
        }
        
        @Override
        public Class<? extends Object> getColumnClass(int columnIndex) {
            if (columnIndex == 1){
                return JComboBox.class;
            }
            return String.class;
        }
    }
    
    private class MyCellEditor extends AbstractCellEditor implements TableCellEditor, ItemListener,PopupMenuListener{
        private int theRow = 0;
        private boolean served = false;
        private String theDept = "";
        
        @Override
        public String getCellEditorValue() {
            return theDept;
        }
        
        @Override
        public Component getTableCellEditorComponent(JTable t, Object v, boolean seleted, int row, int col){
            theRow = row;
            theDept = (String)table.getValueAt(row, 1);
            comboBox = new JComboBox<>(deptData);
            comboBox.setSelectedItem(theDept);
            comboBox.addPopupMenuListener(this);
            comboBox.addItemListener(this);
            
            served = false;
            return comboBox;
        }
        
        @Override
        public void itemStateChanged(ItemEvent e){
            if(e.getStateChange() == ItemEvent.DESELECTED){
                return;
            }
            if (!editingCombo){
                return;
            }
            if(served){
                return;
            }
            JComboBox<String> combo = (JComboBox<String>) e.getSource();
            String dep = (String) combo.getSelectedItem();
            theDept = dep;
            System.out.println("ItemListener: selected="+dep+", row="+theRow);
            table.setValueAt(dep, theRow, 1);
            System.out.println("       ItemListener:"+table.getValueAt(theRow, 1));
            
            
            if (table.getCellEditor() != null)
                table.getCellEditor().stopCellEditing();
            System.out.println("       ItemListener0:"+table.getValueAt(theRow, 1));
            model.fireTableDataChanged();
            System.out.println("       ItemListener1:"+table.getValueAt(theRow, 1));
            served = true;
            editingCombo = false;
            System.out.println("       ItemListener2:"+table.getValueAt(theRow, 1));
        }
        
        @Override
        public void popupMenuCanceled(PopupMenuEvent e){
            System.out.println("popup canceled...");
            if (table.getCellEditor() != null)
                table.getCellEditor().stopCellEditing();
        }
     
        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            System.out.println("popup to be invisible..."+table.getValueAt(theRow, 1));
            if (table.getCellEditor() != null)
                table.getCellEditor().stopCellEditing();
            model.fireTableDataChanged();
            System.out.println("      popup to be invisible:"+table.getValueAt(theRow, 1));
            editingCombo = false;
        }
        
        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            System.out.println("popup to be visible...");
        }
    }

    private class MyCellRenderer extends DefaultTableCellRenderer {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            System.out.println ("Render: value="+value+":"+table.getValueAt(row, 1)+", row="+row);
            JComboBox<String> comp = new JComboBox<>(deptData);
            String v = (String) table.getValueAt(row, 1);
            comp.setSelectedItem(v);
            
            return comp;
        }
    }
    
    private class MyMouseListener extends MouseAdapter {
        @Override
        public void mouseReleased(MouseEvent e) {
            int row = table.rowAtPoint(e.getPoint());
            int col = table.columnAtPoint(e.getPoint());
            if (row < 0 || row >= table.getRowCount()
                    || col < 0 || col >= table.getColumnCount()) {
                return;
            }
            if (col == 1) {
                System.out.println("mouse released: row=" + row + ", col=" + col);
                comboBox.setSelectedItem(table.getValueAt(row, 1));
                editingCombo = true;
            }
        }
    }

    public static void main(String[] args){
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TableTest();
            }
        });
    }
}

---------------------------------------------------------------------------------------------------

                        



If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.



Tuesday, April 18, 2017

Java: add, insert, remove, delete an element in array []

Since the size of an array is fixed after it is created, without help from other tools it is impossible to directly insert or delete it's element.

Probably the most convenient way is to do this using the org.apache.commons.lang.ArrayUtils.

import org.apache.commons.lang.ArrayUtils;

public class EditArray {
    private static void print(Object[] array){
        for (Object s : array){
            System.out.print(s + " ");
        }
        System.out.println();
    }
    public static void main(String[] args) {
        Object[] array = {"Test", "to", "see", "if", "it", "works"};
        print(array);
        array = ArrayUtils.add(array, 6, "!");
        print(array);
        array = ArrayUtils.remove(array, 3);
        print(array);
        array = ArrayUtils.removeElement(array, "to");
        print(array);
   }
}

---------------------------------------------------------------------------------------------------

                        



If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


Saturday, April 15, 2017

ORA-01775: looping chain of synonyms / SP2-0749: Cannot resolve circular path of synonym

The following operations may result in these errors.

SQL> create table fruit (Name varchar2(10), Price float);
SQL> create public synonym fruit for fruit;

SQL> drop table fruit;
SQL> create table fruit (Name varchar2(10), Price float);

SQL> select count(*) from fruit;
ORA-01775: looping chain of synonyms

SQL> desc fruit
SP2-0749: Cannot resolve circular path of synonym "fuit"

To fix this problem:

SQL> drop public synonym fruit;

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.

Monday, April 10, 2017

java and SQL: Check if a binary number contains certain value

Below are some examples of binary numbers

Decimal format                   Binary format
2                                        00000010
16                                      00010000
18                                      00010010


In Java the operation to test if a binary number contains certain value is "&". For example,

             if ((theNumber & 4) == 4) {
                     . . . . . .
             }

             System.out.println((16 & 2) == 2);  The output is false;
             System.out.println((18 & 2) == 2); The output is true;

In SQL the operation to test if a binary number contains certain value is "bitand". For example,

             select * from Fruit where (bitand (criteria, 8) = 8);
---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, April 6, 2017

LibreOffice: set / define / edit spread sheet print range, gridline, and paper orientation

A. Set the print range

  1. Move your cursor to the top-left most cell of the area you want to print, press the left button on the mouse, then drag the mouse to highlight the area to print.
  2. Click the Format in the top menu, select Print Ranges, then select Define.


B. Add cells to an existing print range

  1. Highlight the cells you want to add to the existing print area.
  2. Click the Format in the top menu, select Print Ranges, then select Add.


C. Edit a print area

  1. Click View in the top menu, select Page Break.
  2. Drag the edge of the area to expand or reduce the print area.
  3. To exit, click View in the top menu and select Normal.


D. Clear a print range

  1. Click the Format in the top menu, select Print Ranges, then select Clear.


E. Print gridlines

  1. Click Format in the top menu and select Page.
  2. Select the Sheet tab in the pop-up window.
  3. Check Grid under Print.


F. Set print orientation: Portrait or Landscape

  1. Click Format in the top menu and select Page.
  2. Select the Page tab in the pop-up window.
  3. Check Portrait or Landscape under Paper Format.

---------------------------------------------------------------------------------------------------

                        


If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.