0
有在DefaultTreeCellRenderer
一種稱爲setBackgroundSelectionColor()
,讓你當你選擇一個JTree
一個項目更改選擇的顏色。當我進入DefaultTreeCellRenderer
的源代碼時,選擇顏色在paint()
之前設置爲getBackgroundSelectionColor()
。覆蓋選擇顏色 - JTree的
下面的代碼中,我試圖通過簡單覆蓋paint
方法來更改選擇顏色。問題是,即使在paint方法中手動設置,顏色保持不變。即使在paint
中不再使用getBackgroundSelectionColor()
,方法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;
}
}
}
編輯
什麼它目前看起來像
這是工作的罰款我猜 - > https://i.stack.imgur.com/Inh6K.png,張貼Screensh。的GUI –
@ΦXocę웃Пepeúpaツ不幸的是,它看起來像我編輯中的照片 – Dan
@ΦXocę웃Пepeúpaツ如果它在JDK 8上使用Windows 10有所作爲u112 – Dan