简体   繁体   English

如何更改Java中无法编辑的JTextPane的背景颜色?

[英]How can I change the background color of an uneditable JTextPane in Java?

I have a JTextPane that has pane.setEditable(false) which forces it to have a 'greyed-out' background color. 我有一个JTextPane ,它具有pane.setEditable(false)强制它具有“灰色”背景色。

After trying setBackground(Color.WHITE) (which doesn't work), I tried looking around the net for an answer but not managed to find one yet. 在尝试了setBackground(Color.WHITE) (不起作用)之后,我尝试在网上寻找答案,但仍未找到答案。

Can anyone help me on this one please? 有人可以帮我吗?

Note that for some Look and Feel like Nimbus that don't respect background property, you can use this code : 请注意,对于某些不尊重背景属性的外观(如Nimbus),可以使用以下代码:

private static class Painter extends javax.swing.plaf.nimbus.AbstractRegionPainter {
    private final Color color;

    private Painter(Color color) {
        this.color = color;
    }
    @Override
    protected AbstractRegionPainter.PaintContext getPaintContext() {
        return new AbstractRegionPainter.PaintContext(null, null, false);
    }

    @Override
    protected void doPaint(Graphics2D g, JComponent c, 
            int width, int height, Object[] extendedCacheKeys) {
        g.setColor(c.isEnabled() ? c.getBackground() : color);
        g.fillRect(0, 0, width, height);
    }
}

This defines a new custom painter for the background. 这为背景定义了一个新的自定义画家。 For Nimbus, apply it to your JTextPane jtp this way: 对于Nimbus,请通过以下方式将其应用于JTextPane jtp

        UIDefaults defaults = UIManager.getLookAndFeelDefaults();
        Painter painter = new Painter(color);
        String key = "TextPane[Disabled].backgroundPainter";
        defaults.put(key, painter);
        jtp.putClientProperty("Nimbus.Overrides", defaults);
        jtp.putClientProperty("Nimbus.Overrides.InheritDefaults", false);

Actually try this one: 其实试试这个:

UIManager.put("TextPane.disabledBackground", Color.WHITE);

I think it should be TextPane.disabledBackground , if not try : TextPane.inactiveBackground 我认为应该是TextPane.disabledBackground ,如果不尝试的话: TextPane.inactiveBackground

To change text back ground color I believe: Try setDisabledTextColor on the pane. 我相信要更改文本的背景色:请尝试在窗格上使用setDisabledTextColor

I found out what it was - it was because I had pane.setOpaque(false) , I couldn't change the background color without first either removing this or changing it to true. 我发现它是什么-那是因为我有pane.setOpaque(false) ,如果不先删除或将其更改为true,便无法更改背景色。

setBackground(Color.white) worked after altering this. setBackground(Color.white)更改后工作。

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

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