Code tips

Replacing a system class
1- Extract the .class file from the system archive. Ex.: rt.jar
2- Decompile the class
3- Include the decompiled class into your project
4- After deploying the project to a jar file, ex. proj.jar, use:
   java -Xbootclasspath/p:proj.jar -jar proj.jar

 

Lookup a static member value on a private class

private static String paramTypeToString(int type) throws Exception {
  Class c = Types.class;
  Constructor[] co = c.getDeclaredConstructors();
  for(int i=0; i<co.length; i++) {
    co[i].setAccessible(true);
  }
  Types o = (Types) co[0].newInstance();
  String result = null;
  Field[] af = c.getDeclaredFields();
  for (int i = 0; i < af.length; i++) {
    Field f = af[i];
    int v = f.getInt(o);
    if(type==v) {
      result = f.getName();
      break;
    }
  }
  return result;
}

 

Repaint and Validate
- after adding a component to a container call validate() on container:
    private JPanel panelTesters = new JPanel()
    PanelTester panel = new PanelTester(idChannel);
    panelTesters.add(panel);
    //use active rendering
    paint(getGraphics());
    //or
    panelTesters.validate();
    
  public void setChannelValue(int v, int perc) {
    synchronized (this) {
      this.value = v;
      borderValue.setTitle("Position " + StringUt.format(v, false, 3) +
                           StringUt.format(perc, false, 3) + "%");
      progPerc.setValue(perc);
      invalidate();
      repaint();
    }
  }

 

Get image height
Image image = getImage(applet);
ImageIcon icon = new ImageIcon(image);
height = icon.getIconHeight();

 

A caption for a GUI component

#With an empty border
component.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(),  "Resolution"));

#With a default line border
component.setBorder(BorderFactory.createTitledBorder("Area Color"));