【问题标题】:How to set default background color for JTextPane如何为 JTextPane 设置默认背景颜色
【发布时间】:2013-10-26 10:37:11
【问题描述】:

我已经在网上搜索了很多东西,尝试为JTextPane设置默认背景色,但它仍然显示默认的白色。

我正在尝试模拟控制台输出,我需要整个背景 是黑色的,即使没有文字。

好像setCharacterAttributes()setParagraphAttributes() 只处理 任何插入的文本,但其余的背景仍然是默认的白色。

我看到了一些关于设置背景颜色的错误。

我该怎么做?

它是纯文本,而不是任何 HTML。

谢谢!

更新:

我终于找到了有用的东西。

使用 setBackground(Color.BLACK) 只会设置背景 在任何插入的文本下,但 JTextPane 的其余背景仍然是 默认白色,在我的 Windows 机器上。

我开始考虑更改 UIDefault 并且做到了! 这是我使用的:

UIDefaults defs = UIManager.getDefaults();
defs.put("TextPane.background", new ColorUIResource(Color.BLACK));
defs.put("TextPane.inactiveBackground", new ColorUIResource(Color.BLACK));

当它开始时,没有文本,整个 JTextPane 现在是我想要的黑色 任何插入的文本都是我需要的方式。

我尝试过的所有其他内容都将 JTextPane 的其余部分留白,我尝试了 许多不同的“解决方案”。

感谢您的回复。

【问题讨论】:

  • 我在 Windows 7 上使用 JDK4/5/6/7 从来没有遇到过问题。发布您的 SSCCE 来证明该问题。
  • 你试过用setBackground吗?

标签: java swing jtextpane


【解决方案1】:

试试这个 SSCCE。它演示了在 JTextPane 上设置背景颜色。

import java.awt.Component;
import java.awt.Container;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

/**
 * http://stackoverflow.com/questions/19435181/how-to-set-default-background-color-for-jtextpane
 */
public class Q19435181 {
  public static void main(String... args) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        JFrame frame = new JFrame("Example setting background color on JTextPane");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        Container pane = frame.getContentPane();
        pane.add(blackJTextPane());
        frame.setSize(800, 600);
        frame.setVisible(true);
      }

      private Component blackJTextPane() {
        JTextPane pane = new JTextPane();
        pane.setBackground(Color.BLACK);
        pane.setForeground(Color.WHITE);
        pane.setText("Here is example text");
        return pane;
      }
    });
  }
}

【讨论】:

    【解决方案2】:

    除了使用系统默认值外,还可以针对特定项目执行此操作。 这是我正在使用的代码,主要基于您的笔记:

            Color bgColor = Color.BLACK;
            UIDefaults defaults = new UIDefaults();
            defaults.put("TextPane.background", new ColorUIResource(bgColor));
            defaults.put("TextPane[Enabled].backgroundPainter", bgColor);
            out.putClientProperty("Nimbus.Overrides", defaults);
            out.putClientProperty("Nimbus.Overrides.InheritDefaults", true);
            out.setBackground(bgColor);
    
    

    【讨论】:

      猜你喜欢
      • 2016-05-24
      • 2022-10-18
      • 2014-11-03
      • 2022-07-05
      • 2014-10-20
      • 1970-01-01
      • 2014-04-05
      • 2011-10-09
      • 2012-10-15
      相关资源
      最近更新 更多