如何为JTextPane设置默认背景颜色

4
我已经在网络上搜寻过并尝试了几种方法来设置JTextPane的默认背景色,但仍然显示默认的白色。我正在尝试模拟控制台输出,并且需要整个背景都是黑色,即使没有文本。
似乎setCharacterAttributes()setParagraphAttributes()只处理插入的文本,但其余的背景仍然是默认的白色。
我看到有关设置背景颜色可能存在错误的信息。
我该如何做呢?
这是纯文本,不是任何 HTML。
谢谢!
更新:
我最终找到了一些可行的方法。
使用setBackground(Color.BLACK)只会设置插入文本下方的背景,但在我的 Windows 机器上,JTextPane的其余背景仍为默认的白色。
我开始考虑修改UIDefault,这样就可以了!我用了以下代码:
UIDefaults defs = UIManager.getDefaults();
defs.put("TextPane.background", new ColorUIResource(Color.BLACK));
defs.put("TextPane.inactiveBackground", new ColorUIResource(Color.BLACK));

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

我尝试过的所有其他方法都会使JTextPane的其余部分保留为白色,我尝试了许多不同的“解决方案”。

谢谢你的回复。


2
我在Windows 7上使用JDK4/5/6/7从未遇到过问题。请发布一个SSCCE以演示问题。 - camickr
你尝试过使用setBackground吗? - MadProgrammer
2个回答

4

请尝试这个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;

/**
 * https://dev59.com/tXjZa4cB1Zd3GeqPZxik
 */
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;
      }
    });
  }
}

0

不必使用系统默认值,也可以针对特定项目进行设置。 这是我正在使用的代码,它在很大程度上基于您的笔记:

        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);


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