Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing background color of JTextArea throws exceptions

Tags:

java

swing

I have a swing application, and I've written code to change the background color of the JTextArea. However, it gives me exceptions.

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);
    }
}
like image 586
Shivam Sharma Avatar asked Oct 02 '22 20:10

Shivam Sharma


1 Answers

  • you need to move code line frame.setVisible(true); as last code in void execute()

  • because you added JTextArea to the already visible Swing GUI, that isn't builded on Initial Thread

  • another important:

    • rename public class TextArea { to public class MyTextArea {, because TextArea is reserved Java word for awt.TextArea

    • TextArea x=new TextArea(); and x.execute(); should be wrapped into invokeLater, more to se in Oracle tutorial Initial Thread

like image 99
mKorbel Avatar answered Oct 07 '22 19:10

mKorbel