更改 JTable 背景颜色

Change JTable Background Color

我正在尝试在基于 swing 的 GUI 中更改 JTable 的背景。我已将 table 添加到 JScrollPane。但是,table 中没有单元格的区域不会改变颜色。我尝试更改滚动窗格的背景和前景色。但是,这也无济于事。我需要编辑 JTable 的哪个组件来更改白色背景。下面是我的部分代码。

public class UiColors {
    public static Color BACKGROUND_COLOR_DARK = new Color(30,30,30);
    public static Color BACKGROUND_COLOR_LIGHT = new Color(70,70,70);
    public static Color GOLDEN_TEXT = new Color(255, 215, 0);
}

JTable 代码

JScrollPane mdScrolPane = new JScrollPane();
mdScrolPane.setBackground(UiColors.BACKGROUND_COLOR_DARK);
mdScrolPane.setOpaque(false);
mdScrolPane.setForeground(UiColors.BACKGROUND_COLOR_DARK);
contentPane.add(mdScrolPane, "cell 1 0 1 5,grow");

mdTableModel = new ReadOnlyTableModel();

for (String col : columnNames) {
    mdTableModel.addColumn(col);
}

marketDataTable = new JTable(mdTableModel);
marketDataTable.setFillsViewportHeight(true);
marketDataTable.setToolTipText("Quotes");
marketDataTable.setBorder(null);
marketDataTable.setForeground(new Color(255, 215, 0));
marketDataTable.setBackground(UiColors.BACKGROUND_COLOR_DARK);
marketDataTable.setOpaque(false);
mdScrolPane.setColumnHeaderView(marketDataTable);
mdScrolPane.setViewportView(marketDataTable);

试试这行,对我有用:

mdScrolPane.getViewport().setBackground(UiColors.BACKGROUND_COLOR_DARK);

并尝试在 JscrollPanel`` 声明之前替换以下代码:

替换如下代码位置:

mdTableModel = new ReadOnlyTableModel();

for (String col : columnNames) {
    mdTableModel.addColumn(col);
}

marketDataTable = new JTable(mdTableModel);
marketDataTable.setFillsViewportHeight(true);
marketDataTable.setToolTipText("Quotes");
marketDataTable.setBorder(null);
marketDataTable.setForeground(new Color(255, 215, 0));
marketDataTable.setBackground(UiColors.BACKGROUND_COLOR_DARK);
marketDataTable.setOpaque(false);

之前:

JScrollPane mdScrolPane = new JScrollPane();