5

我有一个swing 应用程序,并且我编写了代码来更改JTextArea 的背景颜色。但是,它给了我例外。

这是代码:

//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);
    }
}
4

2 回答 2

4
  • 您需要将代码行frame.setVisible(true);作为 void 中的最后一个代码移动execute()

  • 因为您添加JTextArea到已经可见的 Swing GUI,它不是建立在Initial Thread

  • 另一个重要的:

    • 重命名 public class TextArea {public class MyTextArea{,因为TextArea它是 Java 的保留字awt.TextArea

    • TextArea x=new TextArea();x.execute(); 应该被包裹进去invokeLater,更多的被塞进去Oracle tutorial Initial Thread

于 2013-09-26T13:16:01.670 回答
0

你的 textarea 占据了框架的所有空间。

在代码中再添加两行,然后文本区域取帧的特定部分。

area.setBounds(20,20,100,30);
frame.setLayout(null);
于 2013-09-26T13:15:13.893 回答