我想为我的应用程序的用户提供即时更改字体大小的更改...但是我可以做些什么来放大或缩小JTree图标(即节点打开/节点关闭)?...通常我说的是标准(金属)L& F ......我不清楚这些图像实际保存在哪里(我在java目录上快速搜索.gif,.bmp,.png和.jpg到no果)。
如果你有一个64 x 64像素的GIF,是否有Java方法可以向上或向下缩放?或者我是否必须拥有一组不同大小的图标文件(gif或png或其他)? java是否提供了一组不同大小的相同图标(已关闭/打开的JTree文件夹)...或者它是否只为您提供了一种尺寸的图标选择?
答案 0 :(得分:2)
您可以缩放UIManager.getIcon返回的默认图标,如果树的单元格渲染器是DefaultTreeCellRenderer,您可以在那里设置新图标:
static Icon scale(Icon icon, double scaleFactor, JTree tree) {
int width = icon.getIconWidth();
int height = icon.getIconHeight();
width = (int) Math.ceil(width * scaleFactor);
height = (int) Math.ceil(height * scaleFactor);
BufferedImage image =
new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.scale(scaleFactor, scaleFactor);
icon.paintIcon(tree, g, 0, 0);
g.dispose();
return new ImageIcon(image);
}
static void updateIcons(JTree tree) {
Font defaultFont = UIManager.getFont("Tree.font");
Font currentFont = tree.getFont();
double newScale = (double)
currentFont.getSize2D() / defaultFont.getSize2D();
DefaultTreeCellRenderer renderer =
(DefaultTreeCellRenderer) tree.getCellRenderer();
renderer.setOpenIcon(
scale(UIManager.getIcon("Tree.openIcon"), newScale, tree));
renderer.setClosedIcon(
scale(UIManager.getIcon("Tree.closedIcon"), newScale, tree));
renderer.setLeafIcon(
scale(UIManager.getIcon("Tree.leafIcon"), newScale, tree));
Collection<Integer> iconSizes = Arrays.asList(
renderer.getOpenIcon().getIconHeight(),
renderer.getClosedIcon().getIconHeight(),
renderer.getLeafIcon().getIconHeight());
// Convert points to pixels
Point2D p = new Point2D.Float(0, currentFont.getSize2D());
FontRenderContext context =
tree.getFontMetrics(currentFont).getFontRenderContext();
context.getTransform().transform(p, p);
int fontSizeInPixels = (int) Math.ceil(p.getY());
tree.setRowHeight(
Math.max(fontSizeInPixels, Collections.max(iconSizes) + 2));
}
缩放节点句柄图标可能更具挑战性。您可以调用BasicTreeUI的setCollapsedIcon和setExpandedIcon方法,但在放置节点和行时似乎没有考虑不同的句柄大小。