Saving JTextArea to a .txt file with a button - java

if I enter text in the JTextArea and click the "Save" button, the JTextArea text should write/save into a .txt file. Is my try & catch in the correct place being in the event handler method or should parts of it be in the constructor?
This is my code:
package exercises;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class SimpleNotePadApp extends JFrame implements ActionListener {
JButton button1 = new JButton("Open");
JButton button2 = new JButton("Save");
public SimpleNotePadApp(String title) {
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 350);
setLayout(null);
JTextArea newItemArea = new JTextArea();
newItemArea.setLocation(3, 3);
newItemArea.setSize(297, 282);
getContentPane().add(newItemArea);
button1.setLocation(30,290);
button1.setSize(120, 25);
getContentPane().add(button1);
button2.setLocation(150,290);
button2.setSize(120, 25);
getContentPane().add(button2);
}
public static void main(String[] args) {
SimpleNotePadApp frame;
frame = new SimpleNotePadApp("Text File GUI");
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1)
{
try {
PrintWriter out = new PrintWriter(new FileWriter("TestFile.txt"));
newItemArea.getText();
newItemArea.write(out);
out.println(newItemArea);
out.flush();
out.close();
} catch (IOException e1) {
System.err.println("Error occurred");
e1.printStackTrace();
}
}
}
}
Thanks in advance

Your try ... catch is in the correct spot, but the contents should just be:
PrintWriter out = new PrintWriter(new FileWriter("TestFile.txt"));
newItemArea.write(out);
out.close();
Consider using try-with-resources, and the .close() becomes unnecessary:
try ( PrintWriter out = new PrintWriter(new FileWriter("TestFile.txt")) {
newItemArea.write(out);
} catch (IOException e1) {
System.err.println("Error occurred");
e1.printStackTrace();
}
Also, you'll need to attach the ActionListener to the JButton during the construction:
button2.addActionListener(this);
(this is the SimpleNotePadApp instance, which implements ActionListener)
Finally, you'll want:
if(e.getSource() == button2)
... since button2 is your "Save" button (not button1)

Related

How can I make six buttons in Java inside one JFrame according to the instructions?

One button will make new file in the source, the second button will write what is in the text field on my JFrame inside that file, third button will do the exact opposite (write from that file to the text field), fourth button will delete text from the file, but not the file as a whole, fifth button will close the project window and the sixth one will delete the file. I need also that the layout around buttons needs to be colored and I would like if the project will tell me if the file was created/deleted too. I hope you can help me with that. I'm trying this all day but something still doesn't work. If I make some progress, I will comment here.
Edit:
For now I have this, but it doesn't show anything:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class project2 {
public static void main(String[] args) {
JFrame window = new JFrame("New window");
JButton button = new JButton ("Create");
JButton writeto = new JButton ("Write to file");
JButton close = new JButton ("Close");
JButton delete = new JButton ("Delete file");
JTextField field = new JTextField();
JLabel text = new JLabel("Testing");
JButton writefrom = new JButton("Write from file");
JButton deletetext = new JButton("Delete");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(550,450);
window.setVisible(true);
}
}
I did it somehow. I think I just didn't know how to make the buttons to appear, but after I found some functional parts of code on the internet, I did what I wanted. I think I was too rushed so I asked here, but hopefully that's okay. It would be good to make this project to take less rows, so more answers will be appreciated, but I'm already happy with the functionality.
Anyways here's my code for the six buttons:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class project {
public static void main(String[] args) {
JFrame window = new JFrame("New window");
JButton button = new JButton ("Create");
button.setBounds(80,20,100,30);
JButton writeto = new JButton ("Write to file");
writeto.setBounds(80,80,100,30);
JButton close = new JButton ("Close");
close.setBounds(80,140,100,30);
JButton delete = new JButton ("Delete file");
delete.setBounds(80,200,100,30);
JTextField field = new JTextField();
field.setBounds(80,380,100,30);
JLabel text = new JLabel("Testing");
text.setBounds(110,440,100,30);
JButton writefrom = new JButton("Write from file");
writefrom.setBounds(80,260,120,30);
JPanel panel = new JPanel();
panel.setBounds(75,15,110,40);
JButton deletetext = new JButton("Delete");
deletetext.setBounds(80,320,100,30);
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
File file = new File("file.txt");
try {
if (file.createNewFile()) {
text.setText("Created");
}
else {
text.setText("Not created");
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
writeto.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
FileWriter writeto = new FileWriter("file.txt");
writeto.write(field.getText());
writeto.close();
field.setText("");
text.setText("Task successful");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
text.setText("Task unsuccessful");
}
}
});
close.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
delete.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
File delete = new File("file.txt");
if (delete.delete()) {
text.setText("Deleted");
}
else {
text.setText("Not deleted");
}
}
});
writefrom.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
File writefrom = new File("file.txt");
try {
Scanner scanner = new Scanner(writefrom);
while (scanner.hasNextLine()) {
String data = scanner.nextLine();
field.setText(data);
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
panel.setBackground(Color.GREEN);
deletetext.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try {
FileWriter deletetext = new FileWriter("file.txt");
deletetext.write("");
deletetext.close();
field.setText("");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
text.setText("Task unsuccessful");
}
}
});
window.add(button);
window.add(writeto);
window.add(close);
window.add(delete);
window.add(field);
window.add(text);
window.add(writefrom);
window.add(panel);
window.setLayout(null);
window.add(deletetext);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(300,600);
window.setVisible(true);
}
}
Below is my rewrite of your application. Note the following:
You should almost always use a layout manager (rather than setting the layout to null and calling method setBounds). In the below code I use BoxLayout.
After you read or writer a file, you should close it. In the below code I use try-with-resources to ensure that the file is closed.
Rather than using anonymous, inner classes to implement the ActionListeners, I use method references.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Project2 {
private static final String FILE_NAME = "file.txt";
private JLabel text;
private JTextField field;
private void addComponentToPanel(Component cmpt, JPanel panel) {
panel.add(cmpt);
panel.add(Box.createRigidArea(new Dimension(0, 10)));
}
private void close(ActionEvent event) {
System.exit(0);
}
private void createAndDisplayGui() {
JFrame window = new JFrame("New Window");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(createPanel(), BorderLayout.CENTER);
window.pack();
window.setLocationByPlatform(true);
window.setVisible(true);
}
private JButton createButton(String text,
int mnemonic,
String tooltip,
Dimension prefSize,
ActionListener listener) {
JButton button = new JButton(text);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
if (prefSize != null) {
button.setMaximumSize(prefSize);
}
if (mnemonic > 0) {
button.setMnemonic(mnemonic);
}
if (tooltip != null && !tooltip.isEmpty()) {
button.setToolTipText(tooltip);
}
button.addActionListener(listener);
return button;
}
private void createFile(ActionEvent event) {
File file = new File(FILE_NAME);
try {
if (file.createNewFile()) {
text.setText("Created");
}
else {
text.setText("Not created");
}
}
catch (IOException e1) {
e1.printStackTrace();
}
}
private JPanel createPanel() {
JPanel panel = new JPanel();
BoxLayout layout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
panel.setLayout(layout);
panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
JButton widest = createButton("Write from file",
KeyEvent.VK_F,
"Display file contents.",
null,
this::writeFrom);
Dimension dim = widest.getPreferredSize();
addComponentToPanel(createButton("Create",
KeyEvent.VK_R,
"Create file.",
dim,
this::createFile),
panel);
addComponentToPanel(createButton("Write to file",
KeyEvent.VK_T,
"Write entered text to file.",
dim,
this::writeTo),
panel);
addComponentToPanel(createButton("Close",
KeyEvent.VK_C,
"Close application.",
dim,
this::close),
panel);
addComponentToPanel(createButton("Delete file",
KeyEvent.VK_E,
"Delete the file.",
dim,
this::delete),
panel);
addComponentToPanel(widest, panel);
addComponentToPanel(createButton("Delete",
KeyEvent.VK_D,
"Delete file contents.",
dim,
this::deleteText),
panel);
field = new JTextField();
addComponentToPanel(field, panel);
text = new JLabel("Testing");
text.setAlignmentX(Component.CENTER_ALIGNMENT);
addComponentToPanel(text, panel);
return panel;
}
private void delete(ActionEvent event) {
File delete = new File(FILE_NAME);
if (delete.delete()) {
text.setText("Deleted");
}
else {
text.setText("Not deleted");
}
}
private void deleteText(ActionEvent event) {
try (FileWriter deletetext = new FileWriter(FILE_NAME)) {
deletetext.write("");
deletetext.close();
field.setText("");
}
catch (IOException e1) {
e1.printStackTrace();
text.setText("Task unsuccessful");
}
}
private void writeFrom(ActionEvent event) {
File writefrom = new File(FILE_NAME);
try (Scanner scanner = new Scanner(writefrom)) {
while (scanner.hasNextLine()) {
String data = scanner.nextLine();
field.setText(data);
}
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
private void writeTo(ActionEvent event) {
try (FileWriter writeto = new FileWriter(FILE_NAME)) {
writeto.write(field.getText());
writeto.close();
field.setText("");
text.setText("Task successful");
}
catch (IOException e1) {
e1.printStackTrace();
text.setText("Task unsuccessful");
}
}
public static void main(String[] args) {
Project2 proj2 = new Project2();
EventQueue.invokeLater(() -> proj2.createAndDisplayGui());
}
}
This is how the GUI looks when I run the above code.

JScrollPane and JTextArea scrolling

I am outputting some logs into the a JTextArea enclosed in JScrollPane but the auto scrolling functionality when the output reaches the bottom of the textArea is not working. I have attempted several methods that I saw online but none works. Below is my part of my code so far.
JTextArea ouputLogPane = new JTextArea();
JScrollPane outputPane = new JScrollPane(ouputLogPane);
outputPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
outputPane.setBounds(75, 501, 746, 108);
contentPane.add(outputPane);
Now I in another class am reading from a source file and appending log details to the textArea using the code below.
public void readFile(JTextArea outputLog, JScrollPane scrollPane){
count = 0;
while(moreLinesToRead){
if(count % 100 == 0){
outputLog.update(outputLog.getGraphics());
outputLog.append("Completed Reading"+ count + " Records "\n");
DefaultCaret caret = (DefaultCaret)outputLog.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
outputLog.update(outputLog.getGraphics());
//tried the one below but did not work either
//outputLog.setCaretPosition(outputLog.getDocument().getLength());
}
count++;
}
}
Finally I am calling this method in the when a button is clicked as below.
JButton btnNewButton = new JButton("Start Reading");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
migrationUtil.readFile(ouputLogPane,outputPane);
}
});
So basically the complete output prints only after the execution finished. I read that I might have to use a separate thread to handle it but not very sure on how to proceed.
EDIT
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class ReadingExample extends JFrame {
private JPanel contentPane;
private Connection conn;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ReadingExample frame = new ReadingExample();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ReadingExample() {
//setResizable(false);
setFont(new Font("Dialog", Font.BOLD, 13));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 936, 720);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new LineBorder(new Color(0, 0, 0), 2));
setContentPane(contentPane);
contentPane.setLayout(null);
final JTextArea ouputLogPane = new JTextArea();
final JScrollPane outputPane = new JScrollPane(ouputLogPane);
//outputPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
outputPane.setBounds(67, 189, 746, 108);
contentPane.add(outputPane);
JButton btnNewButton = new JButton("Start Reading");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
File file = new File("file.txt");
FileReader fileReader = null;
try {
fileReader = new FileReader(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
try {
while((line = bufferedReader.readLine()) != null) {
ouputLogPane.append(line + "\n");
ouputLogPane.setCaretPosition(ouputLogPane.getDocument().getLength());
try {
Thread.sleep(200);
} catch (InterruptedException ee) {
ee.printStackTrace();
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 14));
btnNewButton.setBounds(358, 620, 167, 29);
contentPane.add(btnNewButton);
//JPanel panel_3 = new JPanel();
//panel_3.setBorder(new TitledBorder(null, "Process Log", TitledBorder.LEADING, TitledBorder.TOP, null, null));
//panel_3.setBounds(57, 173, 769, 132);
//contentPane.add(panel_3);
}
}
What you want to do is read the file in a separate thread, so that your Swing thread is not blocked by it, allowing you to update the text area at the same time.
You still need to update the GUI on the Swing thread however, so you do this by calling SwingUtilities.invokeLater(runnable).
Here is a working example (Note I added a Thread.sleep(200) so you can see it being updated):
import javax.swing.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class ReadingExample {
public static void main(String[] args) {
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jFrame.setLocationRelativeTo(null);
JPanel mainPanel = new JPanel(new BorderLayout());
JTextArea jTextArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(jTextArea);
scrollPane.setPreferredSize(new Dimension(300, 300));
mainPanel.add(scrollPane, BorderLayout.CENTER);
JButton btnNewButton = new JButton("Start Reading");
mainPanel.add(btnNewButton, BorderLayout.SOUTH);
jFrame.setContentPane(mainPanel);
jFrame.pack();
jFrame.setVisible(true);
btnNewButton.addActionListener(e -> {
new Thread(() -> {
File file = new File("file.txt");
try (FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
String line;
while((line = bufferedReader.readLine()) != null) {
final String fLine = line;
SwingUtilities.invokeLater(() -> {
jTextArea.append(fLine + "\n");
jTextArea.setCaretPosition(jTextArea.getDocument().getLength());
});
Thread.sleep(200);
}
} catch (Exception e1) {
e1.printStackTrace();
}
}).start();
});
}
}
There are two ways to scroll to the bottom. You can manipulate the scroll bar:
JScrollBar scrollBar = scrollPane.getVerticalScrollBar();
scrollBar.setValue(scrollBar.getMaximum());
Or, you can use the more reliable scrollRectToVisible method:
try {
textArea.scrollRectToVisible(
textArea.modelToView(
textArea.getDocument().getLength()));
} catch (BadLocationException e) {
throw new RuntimeException(e);
}

Java JCheckBox ActionListener

I have a program that is a list of notes that can be added by the user. Every note is loaded through a for loop and given a JCheckBox on runtime from the notes.txt. How do I add an actionlistener for my JCheckBoxes when they are only instance based and not permanent code?
(e.g. they don't have their own variable names?)
I need to update notes.txt with a 0 or a 1 based on if the JCheckBox is checked or not. Here is my code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SideNotes {
public static JPanel panel = new JPanel();
private static JButton add = new JButton("Add note");
JCheckBox[] notes;
public SideNotes() {
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(add);
loadNotes();
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
addNote();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
}
public void addNote() throws IOException {
String note = JOptionPane.showInputDialog("Enter note: ", null);
JCheckBox jcb = new JCheckBox(note, false);
panel.add(jcb);
panel.revalidate();
panel.repaint();
File file = new File("notes.txt");
FileWriter writer = new FileWriter(file, true);
BufferedWriter brw = new BufferedWriter(writer);
brw.write(note);
brw.newLine();
brw.close();
}
private void loadNotes() {
File file = new File("notes.txt");
if (file.exists()) {
try {
FileInputStream fs = new FileInputStream(file);
BufferedReader br = new BufferedReader(
new InputStreamReader(fs));
BufferedReader reader = new BufferedReader(new FileReader(
"notes.txt"));
int lines = 0;
while (reader.readLine() != null)
lines++;
reader.close();
notes = new JCheckBox[lines];
for (int i = 0; i < notes.length; i++) {
String note = br.readLine();
int checked = note.charAt(note.length() - 1);
System.out.println(checked);
if (checked == 49) {
note = note.substring(0, note.length() - 1);
notes[i] = new JCheckBox(note, true);
} else {
note = note.substring(0, note.length() - 1);
notes[i] = new JCheckBox(note, false);
}
panel.add(notes[i]);
panel.revalidate();
panel.repaint();
}
br.close();
} catch (Exception e1) {
}
} else {
System.out.println("File does not exist");
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(200, 400);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(add);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
new SideNotes();
}
}
Create a generic ActionListener outside the loop where you create the checkboxes:
ActionListener al = new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JCheckBox checkbox = (JCheckBox)e.getSource();
// do something with the checkbox
}
}
Then after you create the checkbox you add the ActionListener to the checkbox
notes[i].addActionListener(al);
panel.add(notes[i]);

Making my ERROR message in GUI disappear

I have this simple GUI that ask for a string and then write it to a text file but if no input is given the JLabel shows an error message and i want that error message to stay for 5 seconds
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.*;
import javax.swing.JFrame;
import net.miginfocom.swing.MigLayout;
public class Q1 extends JFrame {
private JLabel lblString, lblMessage;
private JTextField txtString;
private JButton btnStore;
private JPanel thePanel;
public static void main(String[] args) {
new Q1();
}// End of main
public Q1() {
super("Store your text");
this.setSize(600, 100);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thePanel = new JPanel(new MigLayout());
lblString = new JLabel("Enter Your Text :");
txtString = new JTextField(50);
btnStore = new JButton("Store");
// Listener for Store Button
ListenerForButton lForButton = new ListenerForButton();
btnStore.addActionListener(lForButton);
lblMessage = new JLabel();
thePanel.add(lblString);
thePanel.add(txtString, "wrap");
thePanel.add(btnStore, "skip,split2");
thePanel.add(lblMessage, "gapleft 200");
this.add(thePanel);
this.setResizable(false);
this.setVisible(true);
}// End of constructor
// Listener implement
public class ListenerForButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnStore) {
if (txtString.getText().equals("")) {
lblMessage.setText("ERROR-NO Text is given !");
lblMessage.setForeground(Color.red);
} else {
try {
String str = txtString.getText();
File file = new File("appending-Text-File.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file.getName(),
true);
BufferedWriter bufferWritter = new BufferedWriter(
fileWritter);
bufferWritter.newLine();// Write a new line
bufferWritter.write(str);
bufferWritter.close();
lblMessage.setText("String is successfully stored !");
txtString.setText("");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}// End actionPerfomred
}
}// End of Class
Try updating your if block as:
if (txtString.getText().equals("")) {
lblMessage.setText("ERROR-NO Text is given !");
lblMessage.setForeground(Color.red);
Thread.currentThread().sleep(5000);
lblMessage.setText("");
}

how to insert or append new line on top of the jtextarea in java swing?

how to insert or append new line on top of the jtextarea in java swing ?
i want to to append jtextarea and add the new line on top of the jtextarea
please help me how to do this.
You can do this:
textArea.setText("The new text\n" + textArea.getText());
Or, an even better solution would be this:
try {
textArea.getDocument().insertString(0, "The new text\n", null);
} catch (BadLocationException e) {
e.printStackTrace();
}
Your best option is to directly modify the underlying Document of the JTextArea.
Here is a small demonstration of this:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
public class TestTextArea {
private void initUI() {
JFrame frame = new JFrame("test");
final JTextArea textarea = new JTextArea(24, 80);
JButton addText = new JButton("Add line");
addText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
textarea.getDocument().insertString(0, "New line entered on " + new Date() + "\n", null);
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(textarea));
frame.add(addText, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestTextArea().initUI();
}
});
}
}
textArea.setText("this is new line" + "\n" + textArea.getText())

Categories

Resources