gpt4 book ai didi

java - 更改 JTextArea 的背景颜色会引发异常

转载 作者:搜寻专家 更新时间:2023-11-01 03:06:57 24 4
gpt4 key购买 nike

我有一个 swing 应用程序,我编写了代码来更改 JTextArea 的背景颜色。但是,它给了我异常(exception)。

代码如下:

//1.JtextArea will work after maximize.
//2.on typing text,background will slowly transform to black line by line.

import java.awt.*;
import javax.swing.*;

public class TextArea {

JTextArea area;
JFrame frame;

public static void main(String args[])
{
TextArea x = new TextArea();
x.execute();
}

void execute()
{
frame = new JFrame();
frame.setVisible(true);
frame.setSize(600,600);
frame.setTitle("Temp Area");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

area = new JTextArea();
frame.add(area,BorderLayout.CENTER);

Color c = new Color(0,0,0,100);
area.setBackground(c);
}
}

最佳答案

  • 您需要将代码行 frame.setVisible(true); 移动到 void execute()

  • 因为您将 JTextArea 添加到已经可见的 Swing GUI,所以它不是基于 Initial Thread 构建的

  • 另一个重要的:

    • public class TextArea { 重命名为 public class MyTextArea {,因为 TextAreaawt 的保留 Java 字。文本区域

    • TextArea x=new TextArea();x.execute();应该被包装到 invokeLater 中,更多信息请参见 Oracle tutorial Initial Thread

关于java - 更改 JTextArea 的背景颜色会引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19029097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com