May 25, 2012

JTextBox Select all on Click

Following code will select all the content from the text box at click on it, if the textbox content is "<comment>".

Use focus listener - JTextArea does not have ActionListener like JTextField

public static JScrollPane getCommentBox() {

    final JTextArea txtComment = new JTextArea();
    txtComment.setText("<comments>");
    txtComment.setForeground(Color.GRAY);
    txtComment.setColumns(50);
    txtComment.setRows(3);

    FocusListener fl = new FocusListener() {
    
       @Override
       public void focusLost(FocusEvent arg0) {
          System.out.println("not typing....");
       }

       @Override
       public void focusGained(FocusEvent arg0) {
          if (txtComment.getText().equals(Constants.COMMENTS)) {
              txtComment.selectAll();
              txtComment.setForeground(Color.BLACK);
          }
       }
    };

    txtComment.addFocusListener(fl);
    JScrollPane jScrollPane1 = new JScrollPane();
    jScrollPane1.setViewportView(txtComment);

    return jScrollPane1;
}

Fixed size text area with scroll

JTextArea txtArea = new JTextArea();
txtArea.setColumns(50);
txtArea.setRows(2);
JScrollPane jScrollPane1 = new JScrollPane();
jScrollPane1.setViewportView(txtArea);

May 15, 2012

ArrayList and Array Conversions

ArrayList to Array Conversion :
List<T> list = new ArrayList<T>();
T[] array = list.toArray(new T[list.size()]);

Array to ArrayList Conversion : 
String[] array = {"a", "b", "c"};
List list = Arrays.asList(array);

Here the list is immutable. So if you want to be able to modify this list, create the list as below :
List list = new ArrayList(Arrays.asList(array));