You might be able to override the paintComponent(Graphics)
method of JTree
to paint selection rectangles directly:
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
import javax.swing.tree.*;
public class ColorTreeTest {
private static final Color SELC = Color.RED;
public JComponent makeUI() {
FocusListener fl = new FocusListener() {
@Override public void focusGained(FocusEvent e) {
e.getComponent().repaint();
}
@Override public void focusLost(FocusEvent e) {
e.getComponent().repaint();
}
};
DefaultTreeCellRenderer r = new DefaultTreeCellRenderer() {
@Override public Component getTreeCellRendererComponent(
JTree tree, Object value, boolean selected, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
JLabel l = (JLabel) super.getTreeCellRendererComponent(
tree, value, selected, expanded, leaf, row, false);
l.setBackground(selected ? Color.RED
: tree.getBackground());
l.setOpaque(true);
return l;
}
};
JPanel p = new JPanel(new GridLayout(1, 2));
for (JTree t : Arrays.asList(new ColorTree1(), new ColorTree2())) {
t.addFocusListener(fl);
t.setCellRenderer(r);
t.setOpaque(false);
p.add(new JScrollPane(t));
}
return p;
}
static class ColorTree1 extends JTree {
@Override public void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
if (getSelectionCount() > 0) {
g.setColor(SELC);
for (int i : getSelectionRows()) {
Rectangle r = getRowBounds(i);
g.fillRect(r.x, r.y, getWidth() - r.x, r.height);
}
}
super.paintComponent(g);
if (getLeadSelectionPath() != null) {
Rectangle r = getRowBounds(getRowForPath(getLeadSelectionPath()));
g.setColor(hasFocus() ? SELC.darker() : SELC);
g.drawRect(r.x, r.y, getWidth() - r.x - 1, r.height - 1);
}
}
}
static class ColorTree2 extends JTree {
private static final Color SELC = Color.RED;
@Override public void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
if (getSelectionCount() > 0) {
g.setColor(SELC);
//@see http://ateraimemo.com/Swing/TreeRowSelection.html
for (int i : getSelectionRows()) {
Rectangle r = getRowBounds(i);
g.fillRect(0, r.y, getWidth(), r.height);
}
}
super.paintComponent(g);
if (getLeadSelectionPath() != null) {
Rectangle r = getRowBounds(getRowForPath(getLeadSelectionPath()));
g.setColor(hasFocus() ? SELC.darker() : SELC);
g.drawRect(0, r.y, getWidth() - 1, r.height - 1);
}
}
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new ColorTreeTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…