How to append data in JTextArea in Java? - java

I am using this code to show text in a JTextArea:
jTextArea1.setText(jTextArea1.getText() + text + "\r\n");
jTextArea1.repaint();
But it shows an exception:
java.lang.NullPointerException

You never instantiated your JTextArea. Also, you might want to check out JTextArea#append.

jTextArea1.setText(jTextArea1.getText() + text + "\r\n");
StringBuilder sb = new StringBuilder();
if(jTextArea1.getText().trim().length() > 0){
sb.append(jTextArea1.getText().trim());
}
sb.append(text).append("\r\n");
jTextArea1.setText(sb.toString());
Above two friends gave you answer.
I want to explain it. Because first times I also met that problem. I solved that, but today solve as above code snippet.

As Jeffrey pointed out, you have to create an object instance before you call non-static methods on it. Otherwise, you will get a NullPointerException. Also note that appending a text to a JTextArea can be done easily by calling its JTextArea.append(String) method. See the following example code for more detail.
package test;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class Main {
public static void main(String[] args) {
Main m = new Main();
m.start();
}
private void start() {
JTextArea ta = new JTextArea();
ta.append("1\n");
ta.append("2\n");
ta.append("3\n");
JFrame f = new JFrame();
f.setSize(320, 200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(ta);
f.setVisible(true);
}
}

The following code adds text to the text area. Note that the text system uses the '\n' character internally to represent newlines; for details, see the API documentation for DefaultEditorKit.
private final static String newline = "\n";
...
textArea.append(text + newline);
Source

Related

Calculator in Swing Java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class calc implements ActionListener
{
JFrame f;
JPanel p;
JTextField jt1,jt2,jt3;
JButton j1,j2;
static double a=0,b=0,result=0;
static int operator=0;
calc()
{
f = new JFrame();
p = new JPanel();
jt1 = new JTextField(20);
jt2 = new JTextField(20);
j1 = new JButton("+");
j2 = new JButton("-");
jt3 = new JTextField();
f.add(p);
p.add(jt1);
p.add(jt2);
p.add(j1);
p.add(j2);
j1.addActionListener(this);
j2.addActionListener(this);
f.setVisible(true);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()=="+")
{
a=Double.parseDouble(jt1.getText());
operator = 1;
b=Double.parseDouble(jt2.getText());
switch(operator)
{
case 1: result=(a+b);
}
jt3.setText(result);
}
}
public static void main(String [] args)
{
calc obj = new calc();
}
}
i'm making a calculator using java swing, the output of this code is:
calc.java:48 error: incompatible types: double cannot be converted to String
jt3.setText(result);
i think this is not a big error, well help me to get rid of this, i just want to sum didn't add more functions like multiply or minus or etc, i just want to run as small code first then i'll add more functions to it well help will be appreciated thanks.
Easy way is:
//jt3.setText(result);
jt3.setText("" + result);
This will force the compiler to create a String of the two values.
Use jt3.setText(String.valueOf(result));.
.setText() only accept String type.
You can see it in Class TextField.
Class text can accept only string values.
where the result you provided as an argument is Double
You can use this to convert it as a string
string converted = Double.toString(result);
This error is because JTextField is expecting a String to set the text to it, not a double, so, you need to either:
jt3.setText(String.valueOf(result));
Or
jt3.setText("" + result);
The first one will convert result to a String value, while the second one will concatenate an empty String to result, and return a String as well.
However one last suggestion I want you to take note of is, don't use single letter variables, make them more descriptive, for example:
JFrame f; //This should be JFrame frame;
The same for the JPanel and the rest of your variables, since in larger programs it could be hard to remember that f means a JFrame and not the conversion to Fahrenheit from Celsius or a formula like F = m * a, it may be confusing and really hard to debug / understand later on.
And also as has been said in the comments above, use .equals to compare String in Java, see How do I compare strings in Java? for more on this

Java - JPanel - painting contents of a text file with an arraylist - Only works the first time

I have a program with a JMenuBar. Inside the JMenuBar has a JButton, the JButton opens up a JMenu that has 2 JMenuItems. When you click on one of the items, it opens a second JFrame, and prints the contents of a text file line by line.
If you select the other option (in the same session), it should change the JFrame title (this works), and print the contents of the other text file (this doesn't work).
I've pinpointed what the issue is, but I have no clue on why this issue is occurring. What's occurring is the code works perfectly the first time it displays the contents of the text file. However, the second time it does not change the text.
What I've found during the second time is described in the comments. Start at the setDocument method, and then move to the paintComponent method.
Here is the class with the issue (there are several other classes for the program, but the issue is solely within this class)...
package PeriodicTable;
import javax.swing.JPanel;
import java.util.ArrayList;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.awt.Graphics;
import java.awt.Color;
import java.lang.Override;
class DocumentPanel extends JPanel {
private ArrayList<String> aryDocument;
DocumentPanel(){
super();
setBackground(Color.white);
}
#Override
protected void paintComponent(Graphics gr){
super.paintComponent(gr);
//aryDocument holds the contents of the old text file (should have the contents of the other text file)
for(int index = 0; index < aryDocument.size(); index++){
//enters loop, re-prints the old document
gr.drawString(aryDocument.get(index), 5, (index + 1)*10);
}
}
public void setDocument(String strFileDirectory){ //places contents of text file in an array (line by line)
//aryDocument is null at this time
aryDocument = new ArrayList<String>();
//aryDocument is empty at this time
try(BufferedReader reader = new BufferedReader(new FileReader(strFileDirectory))){
for(String strLine; (strLine = reader.readLine()) != null; ){
aryDocument.add(strLine);
}
reader.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
//aryDocument holds the contents of the other text file
this.revalidate();
}
}
The following method is in a class called Table (Table implements ActionListener). This method is called by actionPerformed, who uses the ActionCommand value to determine what action does what.
private void loadTextFile(String strName, String strFileDirectory){
DocumentPanel clsDocumentPanel = new DocumentPanel();
if(frmDocument == null){
frmDocument = new JFrame(strName);
frmDocument.setPreferredSize(new Dimension(600, 700));
clsDocumentPanel.setDocument(strFileDirectory);
frmDocument.add(clsDocumentPanel);
frmDocument.pack();
frmDocument.setVisible(true);
}else{
if(!(frmDocument.getTitle().equals(strName))){
frmDocument.setTitle(strName);
clsDocumentPanel.setDocument(strFileDirectory);
frmDocument.pack();
frmDocument.setVisible(true);
}
}
}
I've rechecked strFileDirectory and confirmed they are the correct values.
What versions/programs/etc am I using?
Java 8
Notepad
Command Prompt
My question in clearly stated...
Why isn't aryDocument's value changing when it goes into paintComponent (after loading the other text file)? How can I fix it?
Here,
DocumentPanel clsDocumentPanel = new DocumentPanel(); // <- yes, here!
if(frmDocument == null){
frmDocument = new JFrame(strName);
frmDocument.setPreferredSize(new Dimension(600, 700));
clsDocumentPanel.setDocument(strFileDirectory);
frmDocument.add(clsDocumentPanel);
frmDocument.pack();
frmDocument.setVisible(true);
}else{
if(!(frmDocument.getTitle().equals(strName))){
frmDocument.setTitle(strName);
clsDocumentPanel.setDocument(strFileDirectory);
frmDocument.pack();
frmDocument.setVisible(true);
}
}
you create a new instance of DocumentPanel each time the action is performed. The first time you add it to frmDocument. The second time you just call setDocument on it and let it be garbage collected. The first instance (actually attached to the displayed frame) is never updated.
So, either
store clsDocumentPanel somewhere separately, just like you store frmDocument, not as a local variable;
make frmDocument a JFrame subclass that exposes access to its document panel and call frmDocument.getDocumentPanel().setDocument(...)—but this violates Demeter's Law;
or make frmDocument a JFrame subclass that has a setDocument method that just delegates to setDocument of its panel, then just call frmDocument.setDocument(...).

Changing text size of the text someone using my program sees?

Glad to be on this very helpful website. I have a problem with my Java program that will probably either be an easy fix, or impossible to fix.
You know how when you run a program that's open in NetBeans, it shows the output within the NetBeans application? I am trying to create a program that allows anybody who puts it on their computer to execute it, even if they have not installed an IDE like NetBeans or Eclipse. And when somebody executes my program, I want it to show the same thing as when I run it in NetBeans, with the same output and everything. The program doesn't use a GUI or anything like that. I managed to create an executable .jar file with the "Clean and build project" option, and I made a .bat file that successfully executes the program. This should achieve my goal of allowing anyone to run it. When I start up the .bat file, it works, and shows a white-text-black-background screen that runs the program exactly as it ran while in NetBeans.
The problem is that when I run the program (with the .bat file), the text is too small... I've tried looking everywhere for a solution to this, but I could only find discussion about how to make things work with GUIs, or other more complicated things than what my program needs. I am willing to work with GUI stuff if it is necessary, but I don't think it will help, due to what a GUI is. From my understanding, a GUI is not one big thing, but is a user interface composed of smaller parts (such as pop-up input prompts and scroll bars) that are each made by the programmer. I don't need any fancy scroll bars etc., I just need my program to execute like it does when ran in NetBeans (pretty sure this is called the console), and I need to change the text size of the program text when it executes.
I greatly appreciate any help, even if you aren't sure if it will work or not. If the answer requires a lengthy explanation and you don't feel like explaining, that's okay; just tell me what I'd have to learn to figure this out and I can research it if necessary.
I just created one. Try using this one and tell us if it helped or not.
EDIT Added a JTextField to read data. It is more advanced code than the previous one, since it uses concurrency. I tried to make it simple, these are the functions you can use:
MyConsole (): Constructor. Create and show the console
print (String s): Print the s String
println (String s) Print the s String and add a new line
read (): Makes you wait untill the user types and presses Enter
closeConsole (): Closes the console
Here is the code:
public class MyConsole implements ActionListener {
private JFrame frame;
private JTextArea myText;
private JTextField userText;
private String readText;
private Object sync;
/*
* Main and only constructor
*/
public MyConsole() {
// Synchronization object
sync = new Object();
// Create a window to display the console
frame = new JFrame("My Console");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.setLocationRelativeTo(null);
frame.setResizable(true);
frame.setContentPane(createUI());
frame.setVisible(true);
}
/*
* Creates user interface
*/
private Container createUI() {
// Create a Panel to add all objects
JPanel panel = new JPanel (new BorderLayout());
// Create and set the console
myText = new JTextArea();
myText.setEditable(false);
myText.setAutoscrolls(true);
myText.setBackground(Color.LIGHT_GRAY);
// This will auto scroll the right bar when text is added
DefaultCaret caret = (DefaultCaret) myText.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
// Create the input for the user
userText = new JTextField();
userText.addActionListener(this);
panel.add(new JScrollPane(myText), BorderLayout.CENTER);
panel.add(userText, BorderLayout.SOUTH);
return panel;
}
/*
* Waits until a value is typed in the console and returns it
*/
public String read(){
print("==>");
synchronized (sync) {
try {
sync.wait();
} catch (InterruptedException e) {
return readText = "";
}
}
return readText;
}
/*
* Prints s
*/
public synchronized void print(String s){
// Add the "s" string to the console and
myText.append(s);
}
/*
* Prints s and a new line
*/
public synchronized void println(String s){
this.print(s + "\r\n");
}
/*
* Close the console
*/
public void closeConsole(){
frame.dispose();
}
#Override
public void actionPerformed(ActionEvent e) {
// Check if the input is empty
if ( !userText.getText().equals("") ){
readText = userText.getText();
println(" " + readText);
userText.setText("");
synchronized (sync) {
sync.notify();
}
}
}
}
Here is how to use it (an example). It just asks your age and writes something depending on your input:
public static void main(String[] args) {
MyConsole console = new MyConsole();
console.println("Hello! (Type \"0\" to exit)");
int age = 1;
do{
console.println("How old are you ?");
String read = console.read();
try {
age = Integer.valueOf(read);
if ( age >= 18){
console.println("Wow! " + age + " ? You are an adult already!");
}else if ( age > 0 ){
console.println("Oh! " + age + " ? You are such a young boy!");
}else if (age == 0){
console.println("Bye bye!");
}else{
console.println("You can't be " + age + " years old!");
}
}catch (Exception e) {
console.println("Did you write any number there ?");
}
} while ( age != 0 );
console.closeConsole();
}
And here is a image:

JTextArea won't update java

I'm trying to update a JTextArea using the .append. I'm sending in a string to the method from another class and I know the textBox method gets the string as I can use .println to test it. The only thing is it does not update the JTextArea which is strange as when I first start the program and the gui is being created i'm able to update it.
public void textBox (String text){
textArea.append(text);
}
Does anyone have any ideas? Many thanks in advance.
Try using textArea.append(text + "\n");
I too had the same problem . I solved it by adding a "\n" at the end
JTextArea textArea = new JTextArea(text);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
String appendText = "jumps over the lazy dog.";
textArea.append(appendText);

Java newbie: Swing and displaying ASCII files

G'day all,
I have an application which needs to display an ASCII file of 15 lines in a Swing component that cannot be edited by the user.
Below is my code which reads the ASCII file byte by byte. My thanks to the helpful commenters who explained that a JTextArea.setEditable(false) would be appropriate in Swing.
However, my code merely displays a string of numbers, when I personally made the ASCII file to be something quite different. Does anyone know what I am doing wrong and how to get the ASCII characters themselves to display?
import java.io.*;
import javax.swing.*;
public class LoadMap extends JFrame {
public LoadMap() throws IOException {
FileInputStream fIn = new FileInputStream("map.srn");
BufferedReader rd = new BufferedReader(new InputStreamReader(fIn, "US-ASCII"));
String map = "";
JTextArea mapArea = new JTextArea(15, 50);
try {
int c;
while ((c = rd.read()) != -1) {
map= map + c;
}
} finally {
if (rd != null) {
rd.close();
}
}
mapArea.setText(map);
mapArea.setEditable(false);
add(mapArea);
pack();
setVisible(true);
}
}
You could construct a String inside the loop, and then put the string into JLabel when you've finished.
This makes me feel like Captain Obvious, but still: just load the entire text first, and then build the label using the desired text. Or, as other posters rightly suggest, use a JTextArea since its more well-suited for multiline content.
Use a JTextArea and call
setEditable(false);
to stop the user being able to edit the data
I've just read your code through and realise that's not a comprehensive enough answer. You can't do "+" on a label. What you need to do is read the text in first and store it somewhere, then call
setText(yourTextAsString);
on your text component on screen (for which I'd still use the JTextArea), and you need to add the text area to the frame, so your code would look something like:
public LoadMap() {
String data = // read your data
JTextArea textArea = new JTextArea();
textArea.setText(data);
textArea.setEditable(false);
setLayout(new GridLayout());
add(textArea);
pack();
setVisible(true);
}
I would suggest reading the Swing tutorial to get some more info on using Swing components
A JLabel will not display line breaks (unless you use HTML). So as the others wrote, use a text area.
However, there's another hidden problem with your code: you don't specify the file's encoding, which means the file contents may be garbled if it contains non-ASCII characters and its encoding does not match Java's platform default. To fix this, do not use FileReader. Instead, use a FileInputStream and wrap it in an InputStreamReader, specifying the encoding in its constructor.
Use a JTextArea and call setEditable(false).
https://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/text/JTextComponent.html#setEditable(boolean)
Here:
String map = "";
int c;
while ((c = rd.read()) != -1) {
map= map + c;
}
What you're doing it appending int's to the string.
You should cast them to char instead.
int c;
while ((c = rd.read()) != -1) {
map= map + ( char ) c;
}
You can see much better patterns in these questions.
How do I create a Java string from the contents of a file?
https://stackoverflow.com/questions/181634/simplest-efficient-ways-to-read-binary-and-ascii-files-to-string-or-similar-in-v/324792#324792 ( see java part )
You could use a JTextArea and set it to read only:
jtextarea.setEditable(false);

Categories

Resources