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

18

我正在使用JScrollPane封装JTable。根据配置,有一些未被表格占用的空间。它呈灰色(看起来像是透明的,并且可以看到后面的组件)。如何将此区域设置为特定颜色?

这是一个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;
        }
    }
}

这里是我想要“上色”的区域。在这个SSCCE中,我尝试使用表格和滚动窗格的setOpaque(boolean)setBackgroundColor(Color)方法来实现,但没有成功。

enter image description here

你能告诉我我做错了什么吗?

1个回答

34

不要这样写:

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

调用:

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

1
JScrollPane 无法设置为不透明。 - mKorbel
@mKorbel 意思是......那么为什么这个方法还存在呢? - Branislav Lazic
关于JTable,这里有一个有趣的问题被问了好几次,我不知道答案。 - mKorbel
@mKorbel .. 嗯?每个组件都可以是不透明的(或不是)。 - kleopatra
@mKorbel OP 的唯一错误是将颜色应用到了错误的组件上(scrollPane vs. viewport),透明度与此无关:两者默认都是不透明的。而标题在别处;-) - kleopatra
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接