简体   繁体   中英

Change JTable Background Color

I am trying to change the background of a JTable in a swing based GUI. I have added the table to a JScrollPane . However, the area of the table where there are no cells does not change color. I tried changing the background and foreground color of the scroll pane. However, that does not help either. What component of JTable do I need to edit to change the white background. Below is the part of my code.

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);
}

Code for 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);

在此处输入图片说明

Try this line, that work for me :

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

And try to replace the following code before JscrollPanel`` declaration :

Replace the following code position :

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);

To be Befor :

JScrollPane mdScrolPane = new JScrollPane();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM