Одним из способов является использование настраиваемой рамки, которая рисует значок (и текст, если хотите), тогда вы можете вкладывать неопределенно долго.
Вот одна из таких границ:
/**
* Show a leading or trailing icon in border.
*/
public static class IconBorder implements Border
{
/**
* @param icon - icon to paint for this border
* @param top outer insets for this border
* @param left
* @param bottom
* @param right
*/
public IconBorder(Icon icon, int top, int left, int bottom, int right)
{
setIcon(icon);
top_ = top;
left_ = left;
bottom_ = bottom;
right_ = right;
rect_ = new Rectangle(0, 0, icon_.getIconWidth(), icon_.getIconHeight());
}
public Insets getBorderInsets(Component c)
{
if( icon_ == null )
return new Insets(0, 0, 0, 0);
return isTrailing_ ? new Insets(top_, left_, bottom_, icon_.getIconWidth() + right_) :
new Insets(top_, icon_.getIconWidth() + left_, bottom_, right_);
}
public boolean isBorderOpaque()
{
return false;
}
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height)
{
if( icon_ != null )
{
if( isTrailing_ )
x = width - icon_.getIconWidth() + 4;
else
x += left_ - 1;
icon_.paintIcon(c, g, x, y + top_);
rect_.x = x;
rect_.y = y;
}
}
public void setIcon(Icon icon)
{
if( icon_ != icon )
icon_ = icon;
}
public Icon getIcon()
{
return icon_;
}
public void setPosition(boolean isTrailing)
{
isTrailing_ = isTrailing;
}
public Rectangle getIconRect()
{
return rect_;
}
private final int top_;
private final int left_;
private final int bottom_;
private final int right_;
private final Rectangle rect_;
private Icon icon_;
private boolean isTrailing_ = true;
}
Я использую это, чтобы добавить значок поиска в JTextField (окно поиска в стиле браузера). getIconRect
может использоваться для проверки наведения мыши. Например, я меняю курсор на HAND_CURSOR
, когда мышь находится над значком поиска.