【问题标题】:Change JTree node icons according to the depth level根据深度级别更改 JTree 节点图标
【发布时间】:2011-06-06 03:56:20
【问题描述】:

我正在寻找更改我的 JTree (Swing) 的不同图标

Java 文档解释了如何在节点是否为叶子时更改图标,但这真的不是我要搜索的内容。

对我来说,节点是否是叶子并不重要,或者,如果节点位于三个深度级别的第一个/第二个/第三个深度级别,我只想更改图标。

【问题讨论】:

    标签: java swing icons jtree


    【解决方案1】:

    实现自定义TreeCellRenderer - 为组件使用JLabel,并使用存储在树中的对象数据随意设置其图标。如果对象是原始的(例如字符串),您可能需要包装对象以存储其深度等。

    http://download.oracle.com/javase/7/docs/api/javax/swing/tree/TreeCellRenderer.html http://www.java2s.com/Code/Java/Swing-JFC/TreeCellRenderer.htm

    【讨论】:

      【解决方案2】:

      作为自定义TreeCellRenderer 的替代方案,您可以替换collapsedIconexpandedIcon 的UI 默认值:

      Icon expanded = new TreeIcon(true, Color.red);
      Icon collapsed = new TreeIcon(false, Color.blue);
      UIManager.put("Tree.collapsedIcon", collapsed);
      UIManager.put("Tree.expandedIcon", expanded);
      

      TreeIcon 只是Icon 接口的一个实现:

      class TreeIcon implements Icon {
      
          private static final int SIZE = 14;
          private boolean expanded;
          private Color color;
      
          public TreeIcon(boolean expanded, Color color) {
              this.expanded = expanded;
              this.color = color;
          }
      
          //@Override
          public void paintIcon(Component c, Graphics g, int x, int y) {
              Graphics2D g2d = (Graphics2D) g;
              g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                  RenderingHints.VALUE_ANTIALIAS_ON);
              g2d.setPaint(color);
              if (expanded) {
                  g2d.fillOval(x + SIZE / 4, y, SIZE / 2, SIZE);
              } else {
                  g2d.fillOval(x, y + SIZE / 4, SIZE, SIZE / 2);
              }
          }
      
          //@Override
          public int getIconWidth() {
              return SIZE;
          }
      
          //@Override
          public int getIconHeight() {
              return SIZE;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2012-02-01
        • 2011-09-03
        • 1970-01-01
        • 2011-10-26
        • 2013-02-04
        • 2011-01-13
        • 1970-01-01
        • 1970-01-01
        • 2011-01-16
        相关资源
        最近更新 更多