JScrollPane and JTextArea scrolling - java

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);
}

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.

Saving JTextArea to a .txt file with a button

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)

Save From buffered reader to JTextArea

I want to make the result of my buffered reader to appear in a text area, but It doesn't work for me.
I want the text area to get the result exactly as the system out print do, it is for more than one line, I tried to set the text area with string s but didn't work, just give me the result of one line.
Here is my Code:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.ScrollPane;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Window extends JFrame {
/**
* Launch the application.
* #throws FileNotFoundException
*/
public static void main(String[] args) {
Window frame = new Window();
frame.setTitle("SWMA Extractor");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setBounds(50, 50, 665, 550);
//frame.setLocation(500, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.getContentPane().setLayout(null);
}
/**
* Create the frame.
*/
public Window() {
setResizable(false);
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel path = new JLabel("File Location");
path.setHorizontalAlignment(SwingConstants.CENTER);
path.setBounds(20, 11, 74, 23);
contentPane.add(path);
final JTextField location = new JTextField();
location.setBounds(104, 12, 306, 20);
contentPane.add(location);
location.setColumns(10);
final JTextArea textArea = new JTextArea();
ScrollPane scrollPane = new ScrollPane();
scrollPane.setBounds(20, 80, 605, 430);
contentPane.add(scrollPane);
scrollPane.add(textArea);
JButton btn = new JButton("Get Info.");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
File output = null;
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s;
int lineNumber = 1;
while((s = br.readLine()) != null) {
if (s.contains("System")) {
System.out.println(s);
String nextLine = br.readLine();
System.out.println(nextLine);
String nextLine1 = br.readLine();
System.out.println(nextLine1);
String nextLine2 = br.readLine();
System.out.println(nextLine2);
String nextLine3 = br.readLine();
System.out.println(nextLine3);
System.out.println();
}
}
lineNumber++;
} catch (IOException e2) {
e2.printStackTrace();
}
}
});
btn.setBounds(433, 11, 192, 23);
contentPane.add(btn);
JButton clr = new JButton("Clear");
clr.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String getLocation = location.getText();
String s;
try {
textArea.setText("");
location.setText("");
} catch (Exception e1) {
}
}
});
clr.setBounds(20, 45, 605, 23);
contentPane.add(clr);
}
}
I see you say you tried setting the text, but the setText method actually replaces the whole current text with the new one:
JTextComponent #1669:
((AbstractDocument)doc).replace(0, doc.getLength(), t,null);
You should use insert or append methods:
Replace
System.out.println(s);
with
textArea.append(s);
Also, check the following question for a better way of doing this:
Opening, Editing and Saving text in JTextArea to .txt file
private void fileRead(){
try{
FileReader read = new FileReader("filepath");
Scanner scan = new Scanner(read);
while(scan.hasNextLine()){
String temp = scan.nextLine() + System.lineSeparator();
storeAllString = storeAllString + temp;
}
}
catch (Exception exception) {
exception.printStackTrace();
}
}
#Hovercraft's suggestion is very good. If you don't want to process the file in any way, you could directly read it into the JTextArea:
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
textArea.read(br, "Stream description");
} catch (IOException e2) {
e2.printStackTrace();
}

Not getting whole string when string has space in java

I'm still new to java, so dumb question is coming. I've been working on a simple software using JFrame, PrintWriter, File, and Scanner to create and read a text file, I save the file with the name you typed and then with the data you input into a JTextField, the problem is: As soon as you type one space it doesn't save the text after the space to the .txt file:
Input
waitFor it
WriteToFile(textarea.getText(), name.getText());
// my function input text name
Output:
waitFor
But if I input the text manually this way:
WriteToFile("waitFor it", name.getText());
// my function input text name
Output:
waitFor it
Which leads me to think that my function might not be causing this, but again I'm a noob.
Main.java
package creator;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import library.Database;
public class Main extends Database{
public static void main(String[] args) {
JFrame frame = new JFrame();
JButton button = new JButton("Erase");
JButton button2 = new JButton("Add");
JButton button3 = new JButton("Save to Database");
Font font = new Font("Courier", Font.BOLD, 12);
Font font2 = new Font("Courier", Font.BOLD, 14);
final JTextField name = new JTextField();
final JTextField editorPane = new JTextField();
final JTextField textarea = new JTextField();
final JScrollPane scroll = new JScrollPane (textarea,
JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
frame.setTitle("Array Creator");
frame.setSize(401, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setLayout(null);
frame.add(button);
frame.add(name);
frame.add(button2);
frame.add(button3);
frame.add(editorPane);
frame.add(scroll);
button.setBounds(0, 200, 80, 22);
name.setBounds(82, 200, 80, 22);
button2.setBounds(164, 200, 80, 22);
button3.setBounds(246, 200, 148, 22);
editorPane.setBounds(100,175,200,18);
scroll.setBounds(50, 10, 300, 160);
textarea.setEditable(false);
button.setFont(font);
name.setFont(font);
button2.setFont(font);
button3.setFont(font);
editorPane.setFont(font);
textarea.setFont(font2);
textarea.setText("[");
frame.setVisible(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textarea.setText("[");
editorPane.setText("");
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textarea.setText(textarea.getText()+"["+editorPane.getText()+"],");
editorPane.setText("");
}
});
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String temp = textarea.getText();
temp = temp.substring(0, temp.length()-1);
textarea.setText(temp+"]");
editorPane.setText("");
WriteToFile(textarea.getText(), name.getText());
}
});
name.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent arg0) {
}
public void keyReleased(KeyEvent arg0) {
textarea.setText(readFile(name.getText()));
}
public void keyPressed(KeyEvent arg0) {
}
});
}
}
Database.java
package library;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
public class Database {
public static String WriteToFile(String data, String name){
String output = "ERROR";
PrintWriter writer = null;
try {
writer = new PrintWriter(name+".txt", "UTF-8");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
writer.println(data);
writer.close();
File file = new File(name+".txt");
try {
#SuppressWarnings("resource")
Scanner sc = new Scanner(file);
output = sc.next();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return output;
}
public static String readFile(String name){
String output = "[";
File file = new File(name+".txt");
try {
#SuppressWarnings("resource")
Scanner sc = new Scanner(file);
output = sc.next();
} catch (FileNotFoundException e) {
}
return output;
}
}
May someone provide me an explanation on why this is?
Instead
output = sc.next();
use
output = sc.nextLine();
Reference: Scanner#next() vs Scanner#nextLine()

HyperLinkListener to cancel and save file

Issues:
When I keep contentType of textpane as text/html, then the text typed moves to the right, for ex : if type "asd", then 'Message:' appears on the left and 'asd' appears on the right of the textpane
When adding a file, how do I write a HyperLinkListener for this. I've commented 'Save' and 'Cancel' in the code. How do I get the name of what I click (Cancel or Save), so that I can write appropriate code for these two links?
Code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import java.awt.FlowLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import javax.swing.event.HyperlinkListener;
import javax.swing.event.HyperlinkEvent;
public class SampleTextPane extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextPane textPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SampleTextPane frame = new SampleTextPane();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public SampleTextPane() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(new BorderLayout(0, 0));
JPanel panel_1 = new JPanel();
panel.add(panel_1, BorderLayout.CENTER);
panel_1.setLayout(new BorderLayout(0, 0));
textPane = new JTextPane();
textPane.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent arg0) {
// Cancel
// To cancel the progress
// Save
// To save the file
}
});
textPane.setEditable(false);
textPane.setContentType("text/html");
panel_1.add(textPane);
JPanel panel_2 = new JPanel();
panel.add(panel_2, BorderLayout.SOUTH);
panel_2.setLayout(new BorderLayout(0, 0));
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent key) {
if(key.getKeyCode()==KeyEvent.VK_ENTER){
if(!textField.getText().trim().isEmpty()){
sendMessage(textField.getText());
textField.setText("");
}
}
}
});
panel_2.add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("+");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser fileChoose = new JFileChooser();
int returnVal = fileChoose.showOpenDialog(getParent());
if(returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChoose.getSelectedFile();
String desc = file.getName().trim();
sendFileToUser(file, desc);
}
}
});
panel_2.add(btnNewButton, BorderLayout.EAST);
}
protected void sendFileToUser(File file, String desc) {
StyledDocument doc = textPane.getStyledDocument();
SimpleAttributeSet set = new SimpleAttributeSet();
StyleConstants.setForeground(set, Color.BLACK);
StyleConstants.setBold(set, true);
StyleConstants.setAlignment(set, StyleConstants.ALIGN_LEFT);
try {
doc.insertString(doc.getLength(), " File : "+desc, set);
HTMLEditorKit editorKit = (HTMLEditorKit)textPane.getEditorKit();
HTMLDocument doc1 = (HTMLDocument)textPane.getDocument();
try {
editorKit.insertHTML(doc1, doc.getLength(), "Save Cancel\n", 0, 0, null);
} catch (BadLocationException | IOException e) {
e.printStackTrace();
}
} catch (BadLocationException e) {
e.printStackTrace();
}
}
protected void sendMessage(String text) {
StyledDocument doc = textPane.getStyledDocument();
SimpleAttributeSet set = new SimpleAttributeSet();
StyleConstants.setForeground(set, Color.BLACK);
StyleConstants.setBold(set, true);
StyleConstants.setAlignment(set, StyleConstants.ALIGN_LEFT);
try {
doc.insertString(doc.getLength(), " Message : ", set);
doc.insertString(doc.getLength(), text+"\n", textPane.getStyle(StyleContext.DEFAULT_STYLE));
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
How do I get the name of what I click (Cancel or Save),
Did you specify the URL for the Hyperlink?
The JEditorPane API show an example of how to access the URL from the HyperlinkEvent.

Categories

Resources