Methods Summary |
---|
public static void | adjustFocus(javax.swing.JComponent c)Request focus on the given component if it doesn't already have it
and isRequestFocusEnabled() returns true.
if (!c.hasFocus() && c.isRequestFocusEnabled()) {
c.requestFocus();
}
|
public static boolean | canAccessSystemClipboard()checks the security permissions for accessing system clipboard
for untrusted context (see isTrustedContext) checks the
permissions for the current event being handled
boolean canAccess = false;
if (!GraphicsEnvironment.isHeadless()) {
SecurityManager sm = System.getSecurityManager();
if (sm == null) {
canAccess = true;
} else {
try {
sm.checkSystemClipboardAccess();
canAccess = true;
} catch (SecurityException e) {
}
if (canAccess && ! isTrustedContext()) {
canAccess = canCurrentEventAccessSystemClipboard(true);
}
}
}
return canAccess;
|
public static boolean | canCurrentEventAccessSystemClipboard()Returns true if EventQueue.getCurrentEvent() has the permissions to
access the system clipboard
return isTrustedContext()
|| canCurrentEventAccessSystemClipboard(false);
|
private static boolean | canCurrentEventAccessSystemClipboard(boolean checkGesture)Returns true if EventQueue.getCurrentEvent() has the permissions to
access the system clipboard and if it is allowed gesture (if
checkGesture true)
AWTEvent event = EventQueue.getCurrentEvent();
return canEventAccessSystemClipboard(event, checkGesture);
|
public static boolean | canEventAccessSystemClipboard(java.awt.AWTEvent e)Returns true if the given event has permissions to access the
system clipboard
return isTrustedContext()
|| canEventAccessSystemClipboard(e, false);
|
private static boolean | canEventAccessSystemClipboard(java.awt.AWTEvent e, boolean checkGesture)Returns true if e has the permissions to
access the system clipboard and if it is allowed gesture (if
checkGesture is true)
if (EventQueue.isDispatchThread()) {
/*
* Checking event permissions makes sense only for event
* dispathing thread
*/
if (e instanceof InputEvent
&& (! checkGesture || isAccessClipboardGesture((InputEvent)e))) {
return inputEvent_canAccessSystemClipboard((InputEvent)e);
} else {
return false;
}
} else {
return true;
}
|
public static java.lang.String | clipString(javax.swing.JComponent c, java.awt.FontMetrics fm, java.lang.String string, int availTextWidth)Clips the passed in String to the space provided. NOTE: this assumes
the string does not fit in the available space.
// c may be null here.
String clipString = "...";
int width = SwingUtilities2.stringWidth(c, fm, clipString);
// NOTE: This does NOT work for surrogate pairs and other fun
// stuff
int nChars = 0;
for(int max = string.length(); nChars < max; nChars++) {
width += fm.charWidth(string.charAt(nChars));
if (width > availTextWidth) {
break;
}
}
string = string.substring(0, nChars) + clipString;
return string;
|
public static java.lang.String | clipStringIfNecessary(javax.swing.JComponent c, java.awt.FontMetrics fm, java.lang.String string, int availTextWidth)Clips the passed in String to the space provided.
if ((string == null) || (string.equals(""))) {
return "";
}
int textWidth = SwingUtilities2.stringWidth(c, fm, string);
if (textWidth > availTextWidth) {
return SwingUtilities2.clipString(c, fm, string, availTextWidth);
}
return string;
|
public static java.lang.String | displayPropertiesToCSS(java.awt.Font font, java.awt.Color fg)
StringBuffer rule = new StringBuffer("body {");
if (font != null) {
rule.append(" font-family: ");
rule.append(font.getFamily());
rule.append(" ; ");
rule.append(" font-size: ");
rule.append(font.getSize());
rule.append("pt ;");
if (font.isBold()) {
rule.append(" font-weight: 700 ; ");
}
if (font.isItalic()) {
rule.append(" font-style: italic ; ");
}
}
if (fg != null) {
rule.append(" color: #");
if (fg.getRed() < 16) {
rule.append('0");
}
rule.append(Integer.toHexString(fg.getRed()));
if (fg.getGreen() < 16) {
rule.append('0");
}
rule.append(Integer.toHexString(fg.getGreen()));
if (fg.getBlue() < 16) {
rule.append('0");
}
rule.append(Integer.toHexString(fg.getBlue()));
rule.append(" ; ");
}
rule.append(" }");
return rule.toString();
|
public static int | drawChars(javax.swing.JComponent c, java.awt.Graphics g, char[] data, int offset, int length, int x, int y)The following draw functions have the same semantic as the
Graphics methods with the same names.
this is used for printing
if ( length <= 0 ) { //no need to paint empty strings
return x;
}
int nextX = x + getFontMetrics(c, g).charsWidth(data, offset, length);
if (isPrinting(g)) {
Graphics2D g2d = getGraphics2D(g);
if (g2d != null) {
FontRenderContext deviceFontRenderContext = g2d.
getFontRenderContext();
FontRenderContext frc = getFRC(c, null);
if (frc.isAntiAliased() || frc.usesFractionalMetrics()) {
frc = new FontRenderContext(frc.getTransform(), false, false);
}
if (frc != null
&& ! isFontRenderContextCompatible(deviceFontRenderContext,
frc)) {
TextLayout layout =
new TextLayout(new String(data,offset,length),
g2d.getFont(),
frc);
/* Use alternate print color if specified */
Color col = g2d.getColor();
if (col instanceof PrintColorUIResource) {
g2d.setColor(((PrintColorUIResource)col).getPrintColor());
}
layout.draw(g2d,x,y);
g2d.setColor(col);
return nextX;
}
}
}
// Assume we're not printing if we get here.
if (drawTextAntialiased(c) && (g instanceof Graphics2D)) {
Graphics2D g2 = (Graphics2D)g;
Object oldAAValue = g2.getRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.drawChars(data, offset, length, x, y);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
oldAAValue);
}
else {
g.drawChars(data, offset, length, x, y);
}
return nextX;
|
public static void | drawString(javax.swing.JComponent c, java.awt.Graphics g, java.lang.String text, int x, int y)Draws the string at the specified location.
// c may be null
// All non-editable widgets that draw strings call into this
// methods. By non-editable that means widgets like JLabel, JButton
// but NOT JTextComponents.
if ( text == null || text.length() <= 0 ) { //no need to paint empty strings
return;
}
if (isPrinting(g)) {
Graphics2D g2d = getGraphics2D(g);
if (g2d != null) {
TextLayout layout = new TextLayout(text, g2d.getFont(),
DEFAULT_FRC);
/* Use alternate print color if specified */
Color col = g2d.getColor();
if (col instanceof PrintColorUIResource) {
g2d.setColor(((PrintColorUIResource)col).getPrintColor());
}
layout.draw(g2d, x, y);
g2d.setColor(col);
return;
}
}
// If we get here we're not printing
if (drawTextAntialiased(c) && (g instanceof Graphics2D)) {
Graphics2D g2 = (Graphics2D)g;
Object oldAAValue = g2.getRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.drawString(text, x, y);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
oldAAValue);
}
else {
g.drawString(text, x, y);
}
|
public static float | drawString(javax.swing.JComponent c, java.awt.Graphics g, java.text.AttributedCharacterIterator iterator, int x, int y)
float retVal;
boolean isPrinting = isPrinting(g);
Color col = g.getColor();
if (isPrinting) {
/* Use alternate print color if specified */
if (col instanceof PrintColorUIResource) {
g.setColor(((PrintColorUIResource)col).getPrintColor());
}
}
Graphics2D g2d = getGraphics2D(g);
if (g2d == null) {
g.drawString(iterator,x,y); //for the cases where advance
//matters it should not happen
retVal = x;
} else {
FontRenderContext frc;
if (isPrinting) {
frc = getFRC(c, null);
if (frc.isAntiAliased() || frc.usesFractionalMetrics()) {
frc = new FontRenderContext(frc.getTransform(), false, false);
}
} else if (drawTextAntialiased(c)) {
frc = AA_FRC;
} else {
frc = g2d.getFontRenderContext();
}
TextLayout layout = new TextLayout(iterator, frc);
layout.draw(g2d, x, y);
retVal = layout.getAdvance();
}
if (isPrinting) {
g.setColor(col);
}
return retVal;
|
public static void | drawStringUnderlineCharAt(javax.swing.JComponent c, java.awt.Graphics g, java.lang.String text, int underlinedIndex, int x, int y)Draws the string at the specified location underlining the specified
character.
SwingUtilities2.drawString(c, g, text, x, y);
if (underlinedIndex >= 0 && underlinedIndex < text.length() ) {
// PENDING: this needs to change.
FontMetrics fm = g.getFontMetrics();
int underlineRectX = x + SwingUtilities2.stringWidth(c,
fm, text.substring(0,underlinedIndex));
int underlineRectY = y;
int underlineRectWidth = fm.charWidth(text.
charAt(underlinedIndex));
int underlineRectHeight = 1;
g.fillRect(underlineRectX, underlineRectY + 1,
underlineRectWidth, underlineRectHeight);
}
|
private static boolean | drawTextAntialiased(javax.swing.JComponent c)Returns whether or not text should be drawn antialiased.
fontCache = new LSBCacheEntry[CACHE_SIZE];
Object aa = java.security.AccessController.doPrivileged(
new GetPropertyAction("swing.aatext"));
AA_TEXT_DEFINED = (aa != null);
AA_TEXT = "true".equals(aa);
AA_FRC = new FontRenderContext(null, true, false);
Object dragFix = java.security.AccessController.doPrivileged(
new GetPropertyAction("sun.swing.enableImprovedDragGesture"));
DRAG_FIX = (dragFix != null);
if (!AA_TEXT_DEFINED) {
if (c != null) {
// Check if the component wants aa text
return ((Boolean)c.getClientProperty(
AA_TEXT_PROPERTY_KEY)).booleanValue();
}
// No component, assume aa is off
return false;
}
// 'swing.aatext' was defined, use its value.
return AA_TEXT;
|
public static boolean | drawTextAntialiased(boolean aaText)Returns whether or not text should be drawn antialiased.
if (!AA_TEXT_DEFINED) {
// 'swing.aatext' wasn't defined, use the components aa text value.
return aaText;
}
// 'swing.aatext' was defined, use its value.
return AA_TEXT;
|
private static java.awt.font.FontRenderContext | getFRC(javax.swing.JComponent c, java.awt.FontMetrics fm)Returns the FontRenderContext for the passed in FontMetrics or
for the passed in JComponent if FontMetrics is null
// c may be null.
if (fm instanceof FontDesignMetrics) {
return ((FontDesignMetrics)fm).getFRC();
}
if (fm == null && c != null) {
//we do it this way because we need first case to
//work as fast as possible
return getFRC(c, c.getFontMetrics(c.getFont()));
}
// PENDING: This shouldn't really happen, but if it does we
// should try and handle AA as necessary.
assert false;
return DEFAULT_FRC;
|
public static java.awt.FontMetrics | getFontMetrics(javax.swing.JComponent c, java.awt.Graphics g)Returns the FontMetrics for the current Font of the passed
in Graphics. This method is used when a Graphics
is available, typically when painting. If a Graphics is not
available the JComponent method of the same name should be used.
Callers should pass in a non-null JComponent, the exception
to this is if a JComponent is not readily available at the time of
painting.
This does not necessarily return the FontMetrics from the
Graphics.
return getFontMetrics(c, g, g.getFont());
|
public static java.awt.FontMetrics | getFontMetrics(javax.swing.JComponent c, java.awt.Graphics g, java.awt.Font font)Returns the FontMetrics for the specified Font.
This method is used when a Graphics is available, typically when
painting. If a Graphics is not available the JComponent method of
the same name should be used.
Callers should pass in a non-null JComonent, the exception
to this is if a JComponent is not readily available at the time of
painting.
This does not necessarily return the FontMetrics from the
Graphics.
if (c != null) {
// Note: We assume that we're using the FontMetrics
// from the widget to layout out text, otherwise we can get
// mismatches when printing.
return c.getFontMetrics(font);
}
return Toolkit.getDefaultToolkit().getFontMetrics(font);
|
public static java.awt.font.FontRenderContext | getFontRenderContext(java.awt.Component c)
if (c == null) {
return DEFAULT_FRC;
} else {
return getFRC(null, c.getFontMetrics(c.getFont()));
}
|
public static java.awt.Graphics2D | getGraphics2D(java.awt.Graphics g)
if (g instanceof Graphics2D) {
return (Graphics2D) g;
} else if (g instanceof ProxyPrintGraphics) {
return (Graphics2D)(((ProxyPrintGraphics)g).getGraphics());
} else {
return null;
}
|
public static int | getLeftSideBearing(javax.swing.JComponent c, java.awt.FontMetrics fm, java.lang.String string)Returns the left side bearing of the first character of string. The
left side bearing is calculated from the passed in
FontMetrics. If the passed in String is less than one
character, this will throw a StringIndexOutOfBoundsException exception.
return getLeftSideBearing(c, fm, string.charAt(0));
|
public static int | getLeftSideBearing(javax.swing.JComponent c, java.awt.FontMetrics fm, char firstChar)Returns the left side bearing of the first character of string. The
left side bearing is calculated from the passed in FontMetrics.
int charIndex = (int)firstChar;
if (charIndex < MAX_CHAR_INDEX && charIndex >= MIN_CHAR_INDEX) {
byte[] lsbs = null;
FontRenderContext frc = getFRC(c, fm);
Font font = fm.getFont();
synchronized(SwingUtilities2.class) {
LSBCacheEntry entry = null;
if (searchKey == null) {
searchKey = new LSBCacheEntry(frc, font);
}
else {
searchKey.reset(frc, font);
}
// See if we already have an entry for this pair
for (LSBCacheEntry cacheEntry : fontCache) {
if (searchKey.equals(cacheEntry)) {
entry = cacheEntry;
break;
}
}
if (entry == null) {
// No entry for this pair, add it.
entry = searchKey;
fontCache[nextIndex] = searchKey;
searchKey = null;
nextIndex = (nextIndex + 1) % CACHE_SIZE;
}
return entry.getLeftSideBearing(firstChar);
}
}
return 0;
|
private static synchronized boolean | inputEvent_canAccessSystemClipboard(java.awt.event.InputEvent ie)returns canAccessSystemClipboard field from InputEvent
if (inputEvent_CanAccessSystemClipboard_Field == null) {
inputEvent_CanAccessSystemClipboard_Field =
(Field)AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
Field field = null;
try {
field = InputEvent.class.
getDeclaredField("canAccessSystemClipboard");
field.setAccessible(true);
return field;
} catch (SecurityException e) {
} catch (NoSuchFieldException e) {
}
return null;
}
});
}
if (inputEvent_CanAccessSystemClipboard_Field == null) {
return false;
}
boolean ret = false;
try {
ret = inputEvent_CanAccessSystemClipboard_Field.
getBoolean(ie);
} catch(IllegalAccessException e) {
}
return ret;
|
private static boolean | isAccessClipboardGesture(java.awt.event.InputEvent ie)Returns true if the given event is corrent gesture for
accessing clipboard
boolean allowedGesture = false;
if (ie instanceof KeyEvent) { //we can validate only keyboard gestures
KeyEvent ke = (KeyEvent)ie;
int keyCode = ke.getKeyCode();
int keyModifiers = ke.getModifiers();
switch(keyCode) {
case KeyEvent.VK_C:
case KeyEvent.VK_V:
case KeyEvent.VK_X:
allowedGesture = (keyModifiers == InputEvent.CTRL_MASK);
break;
case KeyEvent.VK_INSERT:
allowedGesture = (keyModifiers == InputEvent.CTRL_MASK ||
keyModifiers == InputEvent.SHIFT_MASK);
break;
case KeyEvent.VK_COPY:
case KeyEvent.VK_PASTE:
case KeyEvent.VK_CUT:
allowedGesture = true;
break;
case KeyEvent.VK_DELETE:
allowedGesture = ( keyModifiers == InputEvent.SHIFT_MASK);
break;
}
}
return allowedGesture;
|
public static boolean | isFontRenderContextCompatible(java.awt.font.FontRenderContext frc1, java.awt.font.FontRenderContext frc2)
return (frc1 != null) ? frc1.equals(frc2) : frc2 == null;
|
static boolean | isPrinting(java.awt.Graphics g)
return (g instanceof PrinterGraphics || g instanceof PrintGraphics);
|
private static boolean | isTrustedContext()see RFE 5012841 [Per AppContect security permissions] for the
details
return (System.getSecurityManager() == null)
|| (AppContext.getAppContext().
get(UntrustedClipboardAccess) == null);
|
public static int | loc2IndexFileList(javax.swing.JList list, java.awt.Point point)A variation of locationToIndex() which only returns an index if the
Point is within the actual bounds of a list item (not just in the cell)
and if the JList has the "List.isFileList" client property set.
Otherwise, this method returns -1.
This is used to make WindowsL&F JFileChooser act like native dialogs.
int index = list.locationToIndex(point);
if (index != -1) {
Object bySize = list.getClientProperty("List.isFileList");
if (bySize instanceof Boolean && ((Boolean)bySize).booleanValue() &&
!pointIsInActualBounds(list, index, point)) {
index = -1;
}
}
return index;
|
public static java.lang.Object | makeIcon(java.lang.Class baseClass, java.lang.Class rootClass, java.lang.String imageFile)Utility method that creates a UIDefaults.LazyValue that
creates an ImageIcon UIResource for the
specified image file name. The image is loaded using
getResourceAsStream , starting with a call to that method
on the base class parameter. If it cannot be found, searching will
continue through the base class' inheritance hierarchy, up to and
including rootClass .
return new UIDefaults.LazyValue() {
public Object createValue(UIDefaults table) {
/* Copy resource into a byte array. This is
* necessary because several browsers consider
* Class.getResource a security risk because it
* can be used to load additional classes.
* Class.getResourceAsStream just returns raw
* bytes, which we can convert to an image.
*/
byte[] buffer = (byte[])
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
try {
InputStream resource = null;
Class<?> srchClass = baseClass;
while (srchClass != null) {
resource = srchClass.getResourceAsStream(imageFile);
if (resource != null || srchClass == rootClass) {
break;
}
srchClass = srchClass.getSuperclass();
}
if (resource == null) {
return null;
}
BufferedInputStream in =
new BufferedInputStream(resource);
ByteArrayOutputStream out =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int n;
while ((n = in.read(buffer)) > 0) {
out.write(buffer, 0, n);
}
in.close();
out.flush();
return out.toByteArray();
} catch (IOException ioe) {
System.err.println(ioe.toString());
}
return null;
}
});
if (buffer == null) {
System.err.println(baseClass.getName() + "/" +
imageFile + " not found.");
return null;
}
if (buffer.length == 0) {
System.err.println("warning: " + imageFile +
" is zero-length");
return null;
}
return new IconUIResource(new ImageIcon(buffer));
}
};
|
private static boolean | pointIsInActualBounds(javax.swing.JList list, int index, java.awt.Point point)Returns true if the given point is within the actual bounds of the
JList item at index (not just inside the cell).
ListCellRenderer renderer = list.getCellRenderer();
ListModel dataModel = list.getModel();
Object value = dataModel.getElementAt(index);
Component item = renderer.getListCellRendererComponent(list,
value, index, false, false);
Dimension itemSize = item.getPreferredSize();
Rectangle cellBounds = list.getCellBounds(index, index);
if (!item.getComponentOrientation().isLeftToRight()) {
cellBounds.x += (cellBounds.width - itemSize.width);
}
cellBounds.width = itemSize.width;
cellBounds.height = itemSize.height;
return cellBounds.contains(point);
|
public static boolean | pointOutsidePrefSize(javax.swing.JTable table, int row, int column, java.awt.Point p)Returns true if the given point is outside the preferredSize of the
item at the given row of the table. (Column must be 0).
Does not check the "Table.isFileList" property. That should be checked
before calling this method.
This is used to make WindowsL&F JFileChooser act like native dialogs.
if (table.convertColumnIndexToModel(column) != 0 || row == -1) {
return true;
}
TableCellRenderer tcr = table.getCellRenderer(row, column);
Object value = table.getValueAt(row, column);
Component cell = tcr.getTableCellRendererComponent(table, value, false,
false, row, column);
Dimension itemSize = cell.getPreferredSize();
Rectangle cellBounds = table.getCellRect(row, column, false);
cellBounds.width = itemSize.width;
cellBounds.height = itemSize.height;
// See if coords are inside
// ASSUME: mouse x,y will never be < cell's x,y
assert (p.x >= cellBounds.x && p.y >= cellBounds.y);
if (p.x > cellBounds.x + cellBounds.width ||
p.y > cellBounds.y + cellBounds.height) {
return true;
}
return false;
|
public static boolean | shouldIgnore(java.awt.event.MouseEvent me, javax.swing.JComponent c)Ignore mouse events if the component is null, not enabled, or the event
is not associated with the left mouse button.
return c == null || !c.isEnabled()
|| !SwingUtilities.isLeftMouseButton(me);
|
public static int | stringWidth(javax.swing.JComponent c, java.awt.FontMetrics fm, java.lang.String string)Returns the width of the passed in String.
return fm.stringWidth(string);
|
public static boolean | useSelectedTextColor(javax.swing.text.Highlighter$Highlight h, javax.swing.text.JTextComponent c)Determines whether the SelectedTextColor should be used for painting text
foreground for the specified highlight.
Returns true only if the highlight painter for the specified highlight
is the swing painter (whether inner class of javax.swing.text.DefaultHighlighter
or com.sun.java.swing.plaf.windows.WindowsTextUI) and its background color
is null or equals to the selection color of the text component.
This is a hack for fixing both bugs 4761990 and 5003294
Highlighter.HighlightPainter painter = h.getPainter();
String painterClass = painter.getClass().getName();
if (painterClass.indexOf("javax.swing.text.DefaultHighlighter") != 0 &&
painterClass.indexOf("com.sun.java.swing.plaf.windows.WindowsTextUI") != 0) {
return false;
}
try {
DefaultHighlighter.DefaultHighlightPainter defPainter =
(DefaultHighlighter.DefaultHighlightPainter) painter;
if (defPainter.getColor() != null &&
!defPainter.getColor().equals(c.getSelectionColor())) {
return false;
}
} catch (ClassCastException e) {
return false;
}
return true;
|