我想让我的jTable
背景是透明的(这是可行的),而且我想为table.setSelectionBackground
颜色创建一个渐变。
这是我目前拥有的。它成功创建了透明背景,但是当我选择一行时没有setSelectionBackground
颜色。
这就是我创建我的方式jTable
:
agentTable = new JTable(agentModel);
agentTable.setRowHeight(55);
agentTable.getTableHeader().setReorderingAllowed(false);
agentTable.setIntercellSpacing(new Dimension(0, 0));
agentTable.setShowGrid(false);
agentTable.setRowSelectionAllowed(true);
agentTable.setTableHeader(null);
agentTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
agentTable.setForeground(new java.awt.Color(0, 0, 0));
agentTable.setSelectionBackground(new java.awt.Color(85, 159, 204));
agentTable.setSelectionForeground(new java.awt.Color(255, 255, 255));
agentTable.setPreferredScrollableViewportSize(agentTable.getPreferredSize());
agentTable.setDefaultRenderer(Object.class, new MyRenderer());
agentTable.getColumnModel().getColumn(1).setCellRenderer(new SecutiryBadgeTableCellRenderer());
agentScrollPane = new JScrollPane(agentTable);
agentScrollPane.setMinimumSize(new Dimension(150, 50));
agentScrollPane.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, new java.awt.Color(187, 187, 187)));
agentScrollPane.setOpaque(false);
agentScrollPane.getViewport().setOpaque(false);
这是我的两个渲染器:
public class MyRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setBorder(noFocusBorder);
if (isSelected) {
} else {
setOpaque(false);
}
return this;
}
}
public static class SecutiryBadgeTableCellRenderer extends DefaultTableCellRenderer {
protected static BufferedImage background;
private JLabel subImage;
public SecutiryBadgeTableCellRenderer() {
setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/agentImageBgSmall.png")));
setLayout(new GridBagLayout());
subImage = new JLabel();
subImage.setHorizontalAlignment(JLabel.LEFT);
subImage.setVerticalAlignment(JLabel.TOP);
subImage.setBorder(new EmptyBorder(9, 6, 0, 0));
add(subImage);
setOpaque(false);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, null, isSelected, hasFocus, row, column);
Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (value instanceof Image) {
Image img = (Image) value;
subImage.setIcon(new ImageIcon((Image) value));
subImage.setSize(subImage.getPreferredSize());
} else {
subImage.setIcon(null);
}
setBorder(noFocusBorder);
return this;
}
}
奇怪的是,当我选择它时,行的颜色正在改变,但我无法显示背景颜色。我真的很想让背景颜色成为渐变色。
我怎么能做到这一点?