0

I am trying to use JTextArea.setText in java to put me something up to the window. I wanted to get my screensize into textarea, however, one of two .setText() is not showing anything to the screen.

My code:

public class SimpleFrame {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Demo");
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        double hi = d.getHeight();
        double wi = d.getWidth();
        JTextArea area = new JTextArea(10, 10);
        area.setEditable(false);
        area.setText("height: " + hi);
        area.setText("width: " + wi);
        frame.setSize(400, 400);
        frame.add(area); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
    }
}

Output:

width: 1920.0
James Z
  • 12,209
  • 10
  • 24
  • 44
sumu00
  • 49
  • 7

1 Answers1

4

You need to append your text with area.append("..."); since area.setText("..."); overrides the content.

public void append(String str): Appends the given text to the end of the document.

public void setText(String t): Sets the text of this TextComponent to the specified text.

pzaenger
  • 11,381
  • 3
  • 45
  • 46
  • Thank you for fast answer. It works:). By the way, I was wondering how do I add (append) non-string type of variables. Like I want to do append(height) without a text. Is that possible? – sumu00 Oct 12 '17 at 22:02
  • I guess `area.append("" + height);` should do the trick. Otherwise you could convert `height` to String with `Double.toString(height);` or something like this. There should be plenty of [examples here on SO](https://stackoverflow.com/questions/5766318/converting-double-to-string). Edit: @sumu00 My bad, you are right ;) Should be: `String.valueOf(height);` – pzaenger Oct 12 '17 at 22:08
  • Yeah "" should do it. Double.ToString gives error, not possible to use toString on primitive type – sumu00 Oct 12 '17 at 22:09