Thursday, September 16, 2010

The difference between .equal and ==

The '.equal' method does deep comparison of the objects. 'equal' method compares what an object points to rather than pointer itself. The operation of the equal method and '==' operator has some strange effects when use to compare Strings.

String s = "Hello";
String s2 = "Hello";
if (s==s2){
System.out.println("Equal");
}

The creation of two strings without the use of the new keyword will create pointers to the same String in the Java String pool.

String t = new String("Hello");
string u = new String("Hello");
if (t==u){
System.out.println("Equal with new operator");
}

So now t and u are two separate strings. == operator only compares the address of the object not
the value.Now t and u have different addresses.

Tuesday, September 14, 2010

Add image to jList

rendering images in JList cells

        ArrayList list = new ArrayList();
        list.add("kasun");
        list.add("laknath");
        list.add("peter");


Icon pingImage = new ImageIcon("images/server.png");
jList1.setCellRenderer(new ImageListCellRenderer()); // need imageListCellRenderer class


ArrayList l2 =new ArrayList();

        String name;
        for (int i = 0; i < list.size(); i++) {
        name = list.get(i).toString();
        JLabel pingLabel= new JLabel(name, pingImage, JLabel.LEFT);
        JPanel pingPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        pingPanel.add(pingLabel);
        l2.add(pingPanel);
        }
        Object[] panels = l2.toArray();
        jList1.setListData(panels);


class ImageListCellRenderer implements ListCellRenderer{

   public Component getListCellRendererComponent(JList jlist, Object value, int cellIndex,
                                                boolean isSelected,
                                                boolean cellHasFocus)
  {
    if (value instanceof JPanel)
    {
      Component component = (Component) value;
      component.setForeground (Color.BLUE);
      component.setBackground(Color.WHITE);
      //component.setBackground (isSelected ? UIManager.getColor("Table.focusCellForeground") : Color.white);
      return component;
    }
    else
    {
      return new JLabel("???");
    }
  }

http://www.devdaily.com/java/jlist-image-jlabel-renderer

Tuesday, August 3, 2010

Display XML in Swing/applet

Display XML with syntax color highlight


download rsyntaxtextarea.jar




RSyntaxTextArea rsyntaxtextarea = new RSyntaxTextArea();
rsyntaxtextarea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_XML);


String contents = read xml using text file reader

rsyntaxtextarea.setText(contents);
JFrame frame = new JFrame("Inserting rows in the table!");
JPanel panel = new JPanel();

panel.add(rsyntaxtextarea);
frame.add(panel);
frame.setSize(800, 800);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);