1

I'm on week three of a Java class. I am working on a class assignment that is due next week. I can complete the assignment without any problem using the console as output, which is acceptable. However, the Professor also suggested we research JTextArea and consider using it for our program output.

I found some code from a tutorial and was able to at least get a text block to appear with my first line of text to appear. But as I write the actual program, I need to continue to add additional lines to the text block as the program progresses.

When I attempt to use the following line of code in the main method to display text line 2, I get an error saying, "non-static variable textarea cannot be referenced from a static context".

textarea.append("Product1\t3\t$3.01\t$9.03");

Here is the code I have so far. Thanks in advance for any help!

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

public class ta extends JFrame{
JTextArea textarea;


public ta(){
setLayout(new FlowLayout ());
textarea = new JTextArea ("Product\tQuantity\tLine Cost\tOrder Cost\n", 5,30);
add(textarea);
}



public static void main(String[] args) {

ta gui = new ta();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(500,200);
gui.setVisible(true);

textarea.append("Product1\t3\t$3.01\t$9.03");
}
}

1 Answer 1

0

You can not reference textarea (which is a instance field) from a static context (ie from within main).

Instead, move textarea.append("Product1\t3\t$3.01\t$9.03"); to be within your constructor

public ta(){
    setLayout(new FlowLayout ());
    textarea = new JTextArea ("Product\tQuantity\tLine Cost\tOrder Cost\n", 5,30);
    add(textarea);
    textarea.append("Product1\t3\t$3.01\t$9.03");
}

Or provide some other "update" method for your ta class which you can call

You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others

2
  • I appreciate your reply and link to the Code Conventions for Java. I tested moving the line of code in the constructor and it worked, but does not solve my problem. My program is going to prompt the user for a product number and quantity. It will then use this input to update the JTextArea. If I'm running my program from main(), I know how to build the string from the input, but I'm not sure how to append this string in main() to the JTextArea? Should I write the entire program from the ta class that way any string I want to append to the JTextArea has access? Thanks for your help!
    – Brent
    Aug 21, 2015 at 17:34
  • Why not write a "append" method for ta which you can use an instance of ta to call with... Aug 21, 2015 at 21:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.