0

在我们的应用程序中,我们必须使用 css 来自定义 Swing 组件的外观。现在我们有一些手动编写的 css 引擎,但是速度很慢并且需要大量额外的代码来应用一个 css 文件。所以现在我们尝试使用 Synth 的外观来让 ui 的变化更加原生

对于大多数组件,我们设置名称并将它们用于绑定到样式。但也有几个滚动条,它们有不同的 css 和不同的外观。影响滚动条拇指的唯一方法是用户区域 ScrollBarThumb,我们无法为其设置名称,因为它不是 JComponent。由于使用区域而不是名称,因此不可能有不同的拇指。有什么解决方法吗?

4

1 回答 1

3

在此处输入图像描述 在此处输入图像描述

从代码(Java6)

import com.sun.java.swing.Painter;
import java.awt.Color;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class ScrollDemo extends JFrame {

    private static final long serialVersionUID = 1L;

    public ScrollDemo() {
        JTextField field = new JTextField();
        String[] columnNames = {"Column"};
        Object[][] data = {
            {"A"}, {"B"}, {"C"}, {"D"}, {"E"}, {"F"},
            {"A"}, {"B"}, {"C"}, {"D"}, {"E"}, {"F"},
            {"A"}, {"B"}, {"C"}, {"D"}, {"E"}, {"F"},
            {"A"}, {"B"}, {"C"}, {"D"}, {"E"}, {"F"},
            {"A"}, {"B"}, {"C"}, {"D"}, {"E"}, {"F"},};

        add(new JScrollPane(new JTable(data, columnNames)));
        pack();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (Exception fail) {
        }
        UIManager.getLookAndFeelDefaults().put("ScrollBar:ScrollBarThumb[Enabled].backgroundPainter",
                new FillPainter(new Color(255, 169, 191)));
        UIManager.getLookAndFeelDefaults().put("ScrollBar:ScrollBarThumb[MouseOver].backgroundPainter",
                new FillPainter(new Color(127, 255, 191)));
        UIManager.getLookAndFeelDefaults().put("ScrollBar:ScrollBarTrack[Enabled].backgroundPainter",
                new FillPainter(new Color(0, 212, 255)));
        UIManager.getLookAndFeelDefaults().put("ScrollBar:\"ScrollBar.button\".size", 20);
        //UIManager.getLookAndFeelDefaults().put("ScrollBar.decrementButtonGap", 10);
        //UIManager.getLookAndFeelDefaults().put("ScrollBar.incrementButtonGap", 10);
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ScrollDemo scrollDemo = new ScrollDemo();
            }
        });
    }
}

class FillPainter implements Painter<JComponent> {

    private final Color color;

    public FillPainter(Color c) {
        color = c;
    }

    @Override
    public void paint(Graphics2D g, JComponent object, int width, int height) {
        g.setColor(color);
        g.fillRect(0, 0, width - 1, height - 1);
    }
}
于 2012-07-05T15:21:31.203 回答