java - JTextArea 的前景色没有改变

标签 java colors jtextarea foreground

我试图将这个半透明的JTextArea的前景字体颜色更改为黑色,但它仍然是蓝灰色的。我做错了什么?

    // [8]*HELP TEXTAREA
    JTextArea help_text = new JTextArea () {
        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            Insets insets = getInsets();
            int x = insets.left;
            int y = insets.top;
            int width = getWidth() - (insets.left + insets.right);
            int height = getHeight() - (insets.top + insets.bottom);
            g2d.setColor(new Color(255, 0, 0, 70));
            g2d.fillRect(x, y, width, height);
            super.paintComponent(g);
        }
    };
    help_text.setFont(new Font(Font.MONOSPACED,Font.BOLD, 70));
    help_text.setForeground(Color.black);
    help_text.setOpaque(false);
    help_text.setLineWrap(true);
    help_text.setWrapStyleWord(true);
    help_text.setEditable(false);
    help_text.setEnabled(false);
    help_text.setHighlighter(null); 
    help_text.setText("Some help text . ..");
    // [8]*HELP PANE
    JScrollPane help_pane = new JScrollPane(help_text);
    help_pane.setOpaque(false);
    help_pane.getViewport().setOpaque(false);  

最佳答案

更改:

@Override
protected void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    Insets insets = getInsets();
    int x = insets.left;
    int y = insets.top;
    int width = getWidth() - (insets.left + insets.right);
    int height = getHeight() - (insets.top + insets.bottom);
    g2d.setColor(new Color(255, 0, 0, 70));
    g2d.fillRect(x, y, width, height);
    super.paintComponent(g);
}

进入:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g.create();

    Insets insets = getInsets();
    int x = insets.left;
    int y = insets.top;
    int width = getWidth() - (insets.left + insets.right);
    int height = getHeight() - (insets.top + insets.bottom);
    g2d.setColor(new Color(255, 0, 0, 70));
    g2d.fillRect(x, y, width, height);

    g2d.dispose();
}

我相信这应该可以解决您的问题,因为从您的代码看来,它有两个潜在的问题:

  • 您将通过调用 super.paintComponent(g) 作为最后一行代码来取消正在进行的所有绘制
  • 您正在更改收到的 Graphics 对象的状态,该对象由整个组件层次结构使用,以及应保留哪个状态

关于java - JTextArea 的前景色没有改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23508816/

相关文章:

java - 如何反转 int 的顺序而不将其转换为字符串

java - 如何指定输入

从键盘获取字符串中的 java.util.InputMismatchException

flutter/Dart : How to get single colors from Colorgradient?

java - 读取从 JTextArea 输入的最后一个字符

java - JDIALOG 没有看到其他类

css - Sass Color 函数 - 包括多个

WPF datagrid 单元格颜色取决于先前的单元格值

JavaIO : Reading text files as they are seen

java - JPanel 中的 JTextArea 不同类一个窗口...可能吗?