1 19 20 package de.gulden.util; 21 22 import java.awt.*; 23 import java.net.MalformedURLException ; 24 import java.net.URL ; 25 import java.util.*; 26 import java.util.Collection ; 27 import java.util.List ; 28 import java.util.Map ; 29 import javax.swing.text.Document ; 30 31 37 public class Toolbox { 38 39 43 46 public static final int NORTH = 1; 47 48 51 public static final int EAST = 2; 52 53 56 public static final int SOUTH = 4; 57 58 61 public static final int WEST = 8; 62 63 66 public static final int NORTH_EAST = 3; 67 68 71 public static final int SOUTH_EAST = 6; 72 73 76 public static final int SOUTH_WEST = 12; 77 78 81 public static final int NORTH_WEST = 9; 82 83 86 public static final int CENTER = 0; 87 88 91 public static final String NL = System.getProperty("line.separator"); 92 93 96 private static final Object [][] primitiveTypeWrappers = {{"boolean","byte","short","int","long","float","double","char"},{java.lang.Boolean .class,java.lang.Byte .class,java.lang.Short .class,java.lang.Integer .class,java.lang.Long .class,java.lang.Float .class,java.lang.Double .class,java.lang.Character .class}}; 97 98 99 103 106 public static Class getPrimitiveTypeWrapperClass(String typename) throws ClassNotFoundException { 107 int i=getPrimitiveTypeIndex(typename); 108 if (i!=-1) { 109 return (Class )primitiveTypeWrappers[1][i]; 110 } else { 111 throw new ClassNotFoundException ("'"+typename+"' is not a primitive type"); 112 } 113 } 114 115 118 public static Class getPrimitiveTypeClass(String typename) throws ClassNotFoundException { 119 Class wrapper=getPrimitiveTypeWrapperClass(typename); 120 try { 121 java.lang.reflect.Field field=wrapper.getField("TYPE"); Class primitiveClass=(Class )field.get(null); 123 return primitiveClass; 124 } catch (Exception e) { 125 throw new ClassNotFoundException ("wrapper for '"+typename+"' has no TYPE field"); 126 } 127 } 128 129 public static boolean isPrimitiveType(String typename) { 130 return (getPrimitiveTypeIndex(typename)!=-1); 131 } 132 133 136 public static Color parseColor(String s) { 137 if ((s.length()==7)&&(s.startsWith("#"))) { 138 String rStr=s.substring(1,3); 139 String gStr=s.substring(3,5); 140 String bStr=s.substring(5,7); 141 int r=decimal(rStr); 142 int g=decimal(gStr); 143 int b=decimal(bStr); 144 return new Color(r,g,b); 145 } else { 146 try { 148 java.lang.reflect.Field field=Color.class.getField(s); 149 return (Color)field.get(null); 150 } catch (Exception e) { 151 return null; } 153 } 154 } 155 156 public static String toString(Color color) { 157 return "#"+hex(color.getRed(),2)+hex(color.getGreen(),2)+hex(color.getBlue(),2); 158 } 159 160 public static String hex(int i) { 161 return Integer.toHexString(i); 162 } 163 164 public static String hex(int i, int minLength) { 165 String s=hex(i); 166 int lendiff=minLength-s.length(); 167 return s+repeat('0',lendiff); } 169 170 public static int decimal(String hex) { 171 return Integer.valueOf(hex,16).intValue(); 172 } 173 174 public static String repeat(String s, int count) { 175 StringBuffer sb=new StringBuffer (); 176 for (int i=0;i<count;i++) { 177 sb.append(s); 178 } 179 return sb.toString(); 180 } 181 182 public static String repeat(char c, int count) { 183 StringBuffer sb=new StringBuffer (); 184 for (int i=0;i<count;i++) { 185 sb.append(c); 186 } 187 return sb.toString(); 188 } 189 190 public static String noNull(String s) { 191 if (s!=null) { 192 return s; 193 } else { 194 return ""; 195 } 196 } 197 198 public static String unqualify(String s) { 199 int pos=s.lastIndexOf('.'); 200 if (pos!=-1) { 201 return s.substring(pos+1); 202 } else { 203 return s; 204 } 205 } 206 207 public static String padRight(String s, String fill, int len) { 208 return s+repeat(fill,len-s.length()); 209 } 210 211 public static String padLeft(String s, String fill, int len) { 212 return repeat(fill,len-s.length())+s; 213 } 214 215 218 public static boolean parseBoolean(String s) { 219 return s.equalsIgnoreCase("yes")||s.equalsIgnoreCase("y")||s.equalsIgnoreCase("on")||s.equalsIgnoreCase("true"); 220 } 221 222 public static String capitalize(String s) { 223 if (s.length()>0) { 224 return s.substring(0,1).toUpperCase()+s.substring(1); 225 } else { 226 return ""; 227 } 228 } 229 230 public static String unqualifyJavaName(String name) { 231 int lastDotPos=name.lastIndexOf('.'); 232 if (lastDotPos!=-1) { 233 return name.substring(lastDotPos+1); 234 } else { 235 return name; 236 } 237 } 238 239 242 public static boolean arrayContains(Object [] array, Object object) { 243 for (int i=0;i<array.length;i++) { 244 if (object.equals(array[i])) { 245 return true; 246 } 247 } 248 return false; 249 } 250 251 255 public static boolean empty(String s) { 256 return isEmpty(s); 257 } 258 259 public static boolean isEmpty(String s) { 260 return (s==null)||(s.trim().length()==0); 261 } 262 263 269 public static String emptyNull(String s) { 270 if (s==null||s.length()==0) { 271 return null; 272 } else { 273 return s; 274 } 275 } 276 277 public static void centerOnScreen(Component component) { 278 Dimension screen=component.getToolkit().getScreenSize(); 279 Dimension comp=component.getSize(); 280 Point newLocation=new Point((screen.width-comp.width)/2,(screen.height-comp.height)/2); 281 component.setLocation(newLocation); 282 } 283 284 public static void centerComponent(Component component, Component parent) { 285 Dimension p=parent.getSize(); 286 Dimension comp=component.getSize(); 287 Point oldPos=parent.getLocation(); 288 Point newPos=new Point(); 289 newPos.x=oldPos.x+(p.width-comp.width)/2; 290 newPos.y=oldPos.y+(p.height-comp.height)/2; 291 component.setLocation(newPos); 292 } 293 294 public static Object invokeValueOf(Class clazz, String s) { 295 try { 296 Class [] signature={String .class}; 297 java.lang.reflect.Method m=clazz.getMethod("valueOf",signature); 298 Object [] params={s}; 299 Object result=m.invoke(null,params); 300 return result; 301 } catch (Exception e) { 302 return null; 303 } 304 } 305 306 public static Object invokeMethod(Object o, String methodName, Class [] signature, Object [] parameters) { 307 try { 308 java.lang.reflect.Method m=o.getClass().getMethod(methodName,signature); 309 Object result=m.invoke(o,parameters); 310 return result; 311 } catch (Exception e) { 312 return null; 313 } 314 } 315 316 public static Object invokeMethod(Object o, String methodName, Class signatureSingle, Object parameterSingle) { 317 return invokeMethod(o, methodName, new Class [] {signatureSingle}, new Object [] {parameterSingle}); 318 } 319 320 public static List invokeOnAll(Collection c, String methodName, Class [] signature, Object [] parameter) { 321 List l = new ArrayList(); 322 for (Iterator it = c.iterator(); it.hasNext(); ) { 323 Object o = it.next(); 324 Object result = invokeMethod(o, methodName, signature, parameter); 325 l.add(result); 326 } 327 return l; 328 } 329 330 public static void fireEvent(Collection listeners, String methodName, EventObject event) { 331 invokeOnAll(listeners, methodName, new Class [] {event.getClass()}, new Object [] {event}); 332 } 333 334 337 public static String getDocumentText(Document d) { 338 try { 339 return d.getText(d.getStartPosition().getOffset(),d.getLength()); 340 } catch (javax.swing.text.BadLocationException ble) { 341 return null; 342 } 343 } 344 345 348 public static void setDocumentText(Document d, String s) { 349 try { 350 d.remove(d.getStartPosition().getOffset(),d.getLength()); 351 d.insertString(d.getStartPosition().getOffset(),s,null); 352 } catch (javax.swing.text.BadLocationException ble) { 353 throw new Error ("INTERNAL ERROR: Toolbox.setDocumentText"); 354 } 355 } 356 357 public static Collection filterCollectionOnType(Collection c, Class type) { 358 Collection result=new ArrayList(); 359 for (Iterator it=c.iterator();it.hasNext();) { 360 Object o=it.next(); 361 if (type.isAssignableFrom(o.getClass())) { 362 result.add(o); 363 } 364 } 365 return result; 366 } 367 368 public static Map filterMapOnType(Map m, Class type) { 369 OrderedHashMap result=new OrderedHashMap(); 370 for (Iterator it=m.entrySet().iterator();it.hasNext();) { 371 Map.Entry entry=(Map.Entry )it.next(); 372 if (type.isAssignableFrom(entry.getValue().getClass())) { 373 result.put(entry.getKey(),entry.getValue()); 374 } 375 } 376 return result; 377 } 378 379 public static Component findChildComponent(Container c, Class childType) { 380 Component[] children=c.getComponents(); 381 for (int i=0;i<children.length;i++) { 382 if (childType==children[i].getClass()) { 383 return children[i]; 384 } 385 } 386 for (int i=0;i<children.length;i++) { 388 if (children[i] instanceof Container) { 389 Component found=findChildComponent((Container)children[i],childType); 390 if (found!=null) { 391 return found; 392 } 393 } 394 } 395 return null; 396 } 397 398 public static Component findChildComponentCloseTo(Container c, Class childType, Component anker) { 399 Component[] children=c.getComponents(); 400 int index = -1; 402 for (int i=0; (index == -1) && (i<children.length); i++) { 403 if (children[i]==anker) { 404 index = i; 405 } 406 } 407 if (index != -1) { 408 int closest = -1; 409 for (int i=0; i<children.length; i++) { 411 if (childType==children[i].getClass()) { 412 if ( (closest == -1) || (abs(index-i)<abs(index-closest)) ) { 413 closest = i; 414 } 415 } 416 } 417 if (closest != -1) { 418 return children[closest]; 419 } else { 420 return null; 421 } 422 } else { 423 for (int i=0;i<children.length;i++) { 425 if (children[i] instanceof Container) { 426 Component found=findChildComponentCloseTo((Container)children[i],childType, anker); 427 if (found!=null) { 428 return found; 429 } 430 } 431 } 432 } 433 return null; 434 } 435 436 public static void drawString(Graphics g, String s, Point p, int anchor, Insets shift, Color backgroundColor, Insets backgroundBorder) { 437 java.awt.FontMetrics fm=g.getFontMetrics(); 438 int w=fm.stringWidth(s); 439 int h=fm.getHeight(); 440 if ((anchor&NORTH)!=0) { p.y+=(h+shift.top); 443 } else if ((anchor&SOUTH)==0) { p.y+=(h/2); 445 } else { p.y-=shift.bottom; 447 } 448 if ((anchor&EAST)!=0) { p.x-=(w+shift.right); 450 } else if ((anchor&WEST)==0) { p.x-=(w/2); 452 } else { p.x+=shift.left; 454 } 455 if (backgroundColor!=null) { 456 if (backgroundBorder==null) { 457 backgroundBorder=new Insets(0,0,0,0); 458 } 459 Color foregroundColor=g.getColor(); 460 g.setColor(backgroundColor); 461 java.awt.Rectangle r=new java.awt.Rectangle (); 462 r.x=p.x-backgroundBorder.left; 463 r.y=p.y-fm.getAscent()-backgroundBorder.top; 464 r.width=w+backgroundBorder.left+backgroundBorder.right; 465 r.height=h+backgroundBorder.top+backgroundBorder.bottom; 466 g.fillRect(r.x,r.y,r.width,r.height); 467 g.setColor(foregroundColor); 468 } 469 g.drawString(s,p.x,p.y); 470 } 471 472 public static void drawString(Graphics g, String s, Point p, int anchor, Insets shift) { 473 drawString(g,s,p,anchor,shift,null,null); 474 } 475 476 public static void drawString(Graphics g, String s, Point p, int anchor) { 477 drawString(g,s,p,anchor,new Insets(0,0,0,0)); 478 } 479 480 483 public static void setLocationCentered(Component c, Point p) { 484 Dimension size=c.getSize(); 485 c.setLocation(p.x-size.width/2,p.y-size.height/2); 486 } 487 488 public static String replace(String s, String search, String repl) { 489 int pos=s.indexOf(search); 490 if (pos>=0) { 491 return s.substring(0,pos)+repl+replace(s.substring(pos+search.length()),search,repl); 492 } else { 493 return s; 494 } 495 } 496 497 public static List explode(String s, char seperator) { 498 StringTokenizer st=new StringTokenizer(s,String.valueOf(seperator),false); 499 List l=new ArrayList(); 500 while (st.hasMoreTokens()) { 501 l.add(st.nextToken()); 502 } 503 return l; 504 } 505 506 public static List explode(String s) { 507 return explode(s,','); 508 } 509 510 public static String implode(Collection c, char separator) { 511 StringBuffer sb=new StringBuffer (); 512 for (Iterator it=c.iterator();it.hasNext();) { 513 String s=(String )it.next(); 514 sb.append(s); 515 if (it.hasNext()) { 516 sb.append(separator); 517 } 518 } 519 return sb.toString(); 520 } 521 522 public static String implode(Collection c) { 523 return implode(c,','); 524 } 525 526 529 public static List getLines(String s) { 530 List l = new ArrayList(); 531 if ((s!=null) && (s.length()>0)) { 532 int start = 0; 533 int pos = s.indexOf('\n'); 534 String line; 535 while (pos != -1) { 536 line = s.substring(start, pos); 537 l.add(line); 538 if (pos < s.length()) { 539 start = pos + 1; 540 pos = s.indexOf('\n', start); 541 } else { 542 pos = -1; 543 } 544 } 545 line = s.substring(start); 546 l.add(line); 547 } 548 return l; 549 } 550 551 public static boolean isYes(String s) { 552 if (s!=null) { 553 s=s.trim().toLowerCase(); 554 return (s.equals("yes")||s.equals("true")||s.equals("on")); 555 } else { 556 return false; 557 } 558 } 559 560 public static boolean isNo(String s) { 561 if (s!=null) { 562 s=s.trim().toLowerCase(); 563 return (s.equals("no")||s.equals("false")||s.equals("off")); 564 } else { 565 return false; 566 } 567 } 568 569 public static String replaceCharsWithStrings(String s, char[] c, String [] r) { 570 int len=s.length(); 571 StringBuffer sb=new StringBuffer (); 572 int[] pos=new int[c.length]; 573 int firstIndex=-1; 574 int first=len; 575 int lastPos=0; 576 for (int i=0;i<c.length;i++) { 578 int p=s.indexOf(c[i]); 579 pos[i]=p; 580 if ((p!=-1)&&(p<first)) { 581 first=p; 582 firstIndex=i; 583 } 584 } 585 do { 586 String part=s.substring(lastPos,first); 587 sb.append(part); 588 if (first<len) { sb.append(r[firstIndex]); 590 lastPos=first+1; 591 if (lastPos<len) { pos[firstIndex]=s.indexOf(c[firstIndex],lastPos); 593 } else { 594 pos[firstIndex]=-1; 595 } 596 first=len; 598 for (int i=0;i<c.length;i++) { 599 int p=pos[i]; 600 if ((p!=-1)&&(p<first)) { 601 first=p; 602 firstIndex=i; 603 } 604 } 605 } else { 606 lastPos=len; 607 } 608 } while (lastPos<len); 609 return sb.toString(); 610 } 611 612 617 public static URL getResourceURL(String resString) throws MalformedURLException { 618 if (resString.startsWith("res:")) { 619 resString = resString.substring(4); 620 java.net.URL url = ClassLoader.getSystemClassLoader().getResource(resString); 621 return url; 622 } else { 623 return new java.net.URL (resString); 624 } 625 } 626 627 public static URL findResource(String resString, Object ref) { 628 return findResource(resString, ref.getClass().getClassLoader()); 629 } 630 631 public static URL findResource(String resString, ClassLoader cl) { 632 java.net.URL url = (cl != null) ? cl.getResource(resString) : null; 634 if (url == null) { 636 url = ClassLoader.getSystemClassLoader().getResource(resString); 637 } 638 return url; 639 640 } 641 642 645 public static Object instantiateClass(String classname, Class ensureType) throws ClassNotFoundException , IllegalAccessException , InstantiationException { 646 Class cl = Class.forName(classname); 647 if (!ensureType.isAssignableFrom(cl)) { 648 throw new IllegalAccessException ("cannot instantiate class '"+classname+"' - not a subclass/implementation of '"+ensureType.getName()+"'"); 649 } 650 return cl.newInstance(); 651 } 652 653 662 public static Properties parseKeyValuePairs(String s) { 663 StringTokenizer st = new StringTokenizer(s, " \t\n=\";", false); 665 Properties p = new Properties(); 666 while (st.hasMoreTokens()) { 667 String key = st.nextToken(); 668 if (st.hasMoreTokens()) { 669 String val = st.nextToken(); 670 p.put(key, val); 671 } 672 } 673 return p; 674 } 675 676 679 public static String trimLeft(String s) { 680 int pos=0; 681 while ((pos<s.length())&&(Character.isWhitespace(s.charAt(pos)))) { 682 pos++; 683 } 684 return s.substring(pos); 685 } 686 687 690 public static String trimRight(String s) { 691 int pos=s.length(); 692 while ((pos>=1)&&(Character.isWhitespace(s.charAt(pos-1)))) { 693 pos--; 694 } 695 return s.substring(0,pos); 696 } 697 698 public static int abs(int i) { 699 if (i>=0) { 700 return i; 701 } else { 702 return -i; 703 } 704 } 705 706 709 private static int getPrimitiveTypeIndex(String typename) { 710 for (int i=0;i<primitiveTypeWrappers[0].length;i++) { 711 if (primitiveTypeWrappers[0][i].equals(typename)) { 712 return i; 713 } 714 } 715 return -1; 716 } 717 718 } | Popular Tags |