gpt4 book ai didi

java - 调用了自定义 CellRenderer 但似乎没有效果

转载 作者:行者123 更新时间:2023-11-30 09:22:44 24 4
gpt4 key购买 nike

简单来说:为什么下面的小例子在树形控件的第三项上没有显示浅灰色背景?

代码创建了一个 JTree,用三个字符串填充它(直接传递给构造函数)并重写 getCellRenderer() 方法以返回自定义 MyTreeCellRenderer 类的实例,该类具有硬编码检查以设置背景第 2 行任何单元格的颜色为浅灰色。但是在运行时,所有单元格都只有常规(白色)背景色。

import java.awt.Color;
import java.awt.Component;

import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeCellRenderer;

@SuppressWarnings("serial")
public class MainFrame extends JFrame {

public MainFrame() {
final MyTreeCellRenderer treeRenderer = new MyTreeCellRenderer();
JTree tree = new JTree(new Object[] { "First", "Second", "Third" }) {
@Override
public TreeCellRenderer getCellRenderer() {
return treeRenderer;
}
};
tree.setRootVisible(false);

add(tree);

setSize(400, 300);
setVisible(true);
}

public class MyTreeCellRenderer extends DefaultTreeCellRenderer {
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
Component c = super.getTreeCellRendererComponent(tree, value, isSelected, expanded, leaf, row, hasFocus);
if (row == 2) {
c.setBackground(Color.LIGHT_GRAY);
} else {
c.setBackground(Color.WHITE);
}
return c;
}
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new MainFrame();
}
});
}

}

最佳答案

DefaultTreeCellRendererJLabel 的子类, 必须是 opaque用于显示颜色。

image

JComponent c = (JComponent) super.getTreeCellRendererComponent(tree,
value,isSelected, expanded, leaf, row, hasFocus);
c.setOpaque(true);

关于java - 调用了自定义 CellRenderer 但似乎没有效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16360782/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com