【问题标题】:Foreground color of JTextArea does not changeJTextArea 的前景色不变
【发布时间】:2014-05-07 04:35:45
【问题描述】:

我尝试将这个半透明的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);  

【问题讨论】:

  • 在你做你自己的“定制”事情之前你不应该打电话给super.paintComponent(g)吗?
  • @John3136 文字变成浅红色,几乎看不见。

标签: java colors jtextarea foreground


【解决方案1】:

变化:

@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 对象的状态,该对象由整个组件层次结构使用,应该保留哪个状态

【讨论】:

  • 谢谢,它现在可以工作了......我刚刚发现出了什么问题,我也不得不删除 help_text.setEnabled(false); ,这是问题所在。
猜你喜欢
  • 1970-01-01
  • 2013-07-06
  • 2021-02-13
  • 2020-07-28
  • 2018-02-14
  • 2020-05-13
  • 1970-01-01
  • 1970-01-01
  • 2013-01-30
相关资源
最近更新 更多