Java 更改 JTextArea 的背景颜色会引发异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19029097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing background color of JTextArea throws exceptions
提问by Shivam Sharma
I have a swing application, and I've written code to change the background color of the JTextArea. However, it gives me exceptions.
我有一个swing 应用程序,我已经编写了代码来更改JTextArea 的背景颜色。但是,它给了我例外。
Here is the code:
这是代码:
//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);
}
}
采纳答案by mKorbel
you need to move code line
frame.setVisible(true);
as last code in voidexecute()
because you added
JTextArea
to the already visible Swing GUI, that isn't builded onInitial Thread
another important:
rename
public class TextArea {
topublic class MyTextArea
{, becauseTextArea
is reserved Java word forawt.TextArea
TextArea x=new TextArea();
andx.execute()
; should be wrapped intoinvokeLater
, more to se inOracle tutorial Initial Thread
您需要将代码行移动
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
回答by Dev
your textarea taken all the space of frame.
您的 textarea 占用了框架的所有空间。
add two more lines in the code, then text area taken specfic portion of frame.
在代码中再添加两行,然后文本区域取帧的特定部分。
area.setBounds(20,20,100,30);
frame.setLayout(null);