简体   繁体   English

JScrollPane中的JTable,如何设置背景?

[英]JTable in JScrollPane, how to set background?

I am using a JScrollPane to wrap a JTable . 我正在使用JScrollPane来包装JTable Depending on the configuration, there is some space that is not occupied by the table. 根据配置,有一些空间未被表占用。 It is drawn gray (it looks like it is transparent and you can just see the component in the back). 它被绘制为灰色(看起来它是透明的,你可以看到后面的组件)。 How can I set this area to be a certain color? 如何将此区域设置为某种颜色?

Here is a SSCCE to illustrate. 这是一个SSCCE来说明。

import java.awt.Color;
import java.util.Vector;

import javax.swing.JDialog;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class DialogDemo extends JDialog {
    public static void main(final String[] args) {
        final DialogDemo diag = new DialogDemo();
        diag.setVisible(true);
    }

    public DialogDemo() {
        super();
        setTitle("SSCCE");

        final Vector<Vector<String>> rowData = new Vector<Vector<String>>();
        final Vector<String> columnNames = new VectorBuilder<String>().addCont("Property").addCont("Value");
        rowData.addElement(new VectorBuilder<String>().addCont("lorem").addCont("ipsum"));
        rowData.addElement(new VectorBuilder<String>().addCont("dolor").addCont("sit amet"));
        rowData.addElement(new VectorBuilder<String>().addCont("consectetur").addCont("adipiscing elit."));
        rowData.addElement(new VectorBuilder<String>().addCont("Praesent").addCont("posuere..."));

        final JTable table = new JTable(rowData, columnNames);
        JScrollPane pane = new JScrollPane(table);

        // ************* make that stuff white! *******************
        table.setBackground(Color.white);
        table.setOpaque(true);
        pane.setBackground(Color.white);
        pane.setOpaque(true);
        // ************* make that stuff white! *******************

        add(pane);
        pack();

        setLocationRelativeTo(null);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    }

    class VectorBuilder<T> extends Vector<T> {
        public VectorBuilder<T> addCont(final T elem) {
            addElement(elem);
            return this;
        }
    }
}

And here you can see the area, which I want to "colorize". 在这里你可以看到我想要“着色”的区域。 In the SSCCE, I try to do that by using setOpaque(boolean) and setBackgroundColor(Color) of the table and scroll pane, with no success. 在SSCCE中,我尝试通过使用表和滚动窗格的setOpaque(boolean)setBackgroundColor(Color)来做到这一点,但没有成功。

在此输入图像描述

Can you tell me, what I am doing wrong? 你能告诉我,我做错了什么吗?

Instead of this: 而不是这个:

table.setBackground(Color.white);
table.setOpaque(true);
pane.setBackground(Color.white);
pane.setOpaque(true);

call: 呼叫:

pane.getViewport().setBackground(Color.WHITE);

不要使用不透明,试试这个:

pane.getViewport().setBackground(Color.WHITE);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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