【发布时间】:2016-12-03 10:11:15
【问题描述】:
DefaultTreeCellRenderer 中有一个名为setBackgroundSelectionColor() 的方法,允许您在选择JTree 上的项目时更改选择颜色。当我进入DefaultTreeCellRenderer的源代码时,选择颜色在paint()中由getBackgroundSelectionColor()设置。
在下面的代码中,我试图通过简单地覆盖paint 方法来更改选择颜色。问题是即使在绘画方法中手动设置颜色也保持不变。即使getBackgroundSelectionColor() 不再在paint 中使用,setBackgroundSelectionColor() 方法仍然有效。
为什么会这样?如何正确覆盖颜色?
不使用setBackgroundSelectionColor()
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
@SuppressWarnings("serial")
public class DirectoryExplorer extends JFrame {
private DirectoryExplorer() {
super("Directory Explorer");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(1, 1));
createPanel();
setSize(800,600);
setVisible(true);
}
private void createPanel() {
JPanel panel = new JPanel(new GridLayout(1, 1));
JTree tree = new JTree();
paintRenderer pR = new paintRenderer();
tree.setCellRenderer(pR);
//pR.setBackgroundSelectionColor(Color.RED); //Why does this work when changing value in paint doesn't
panel.add(new JScrollPane(tree));
getContentPane().add(panel);
}
public static void main(String[] args) {
new DirectoryExplorer();
}
private class paintRenderer extends DefaultTreeCellRenderer {
@Override
public void paint(Graphics g) {
Color bColor;
if (selected) {
bColor = Color.RED;//= getBackgroundSelectionColor();
} else {
bColor = getBackgroundNonSelectionColor();
if (bColor == null) {
bColor = getBackground();
}
}
//super.paint(g); //Paints the correct colors but no text
int imageOffset = -1;
if (bColor != null) {
imageOffset = getLabelStart();
g.setColor(bColor);
if(getComponentOrientation().isLeftToRight()) {
g.fillRect(imageOffset, 0, getWidth() - imageOffset, getHeight());
} else {
g.fillRect(0, 0, getWidth() - imageOffset, getHeight());
}
}
if (hasFocus) {
if (imageOffset == -1) {
imageOffset = getLabelStart();
}
if(getComponentOrientation().isLeftToRight()) {
paintFocus(g, imageOffset, 0, getWidth() - imageOffset, getHeight(), bColor);
} else {
paintFocus(g, 0, 0, getWidth() - imageOffset, getHeight(), bColor);
}
}
super.paint(g); //Paints text but wrong colors
}
private void paintFocus(Graphics g, int x, int y, int w, int h, Color notColor) {
Color bsColor = Color.RED;//= getBorderSelectionColor();
if (bsColor != null && selected) {
g.setColor(bsColor);
g.drawRect(x, y, w - 1, h - 1);
}
}
private int getLabelStart() {
Icon currentI = getIcon();
if(currentI != null && getText() != null) {
return currentI.getIconWidth() + Math.max(0, getIconTextGap() - 1);
}
return 0;
}
}
}
编辑
目前的样子
【问题讨论】:
-
我猜它工作正常 --> i.stack.imgur.com/Inh6K.png,发布一个 Screensh。图形用户界面
-
@ΦXocę웃Пepeúpaツ 不幸的是,它看起来像我正在编辑的照片
-
@ΦXocę웃Пepeúpaツ 如果在 JDK 8 u112 上使用 Windows 10 会有所不同
-
@ΦXocę웃Пepeúpaツ 我猜它适合你?
-
我正在使用 java8 windows 10 和 eclipse... 它看起来像这样 --> i.stack.imgur.com/Inh6K.png... 你呢?