2013-09-26 19 views
3

我有一个swing应用程序,并且编写了代码来更改JTextArea的背景颜色。但是,它给了我例外。更改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); 
    } 
} 
+0

是什么,因此这个问题吗? – 2013-09-26 13:06:35

+0

是什么问题? –

+0

在JAVA中改变JTextArea的背景颜色给出了意想不到的结果。为什么? –

回答

3
  • 你需要移动代码行中无效​​

  • frame.setVisible(true);去年代码,因为您添加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

0

您的拍摄帧的所有空间textarea的。

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

area.setBounds(20,20,100,30); 
frame.setLayout(null); 
+0

非常不好的建议,你在这个答案中提供,关于使用'null'布局,这个布局最后会被使用,当所有其他的选项被完全处理时。但在这种情况下,布局管理器完全可以按照规定执行其职责。 –