I'm making a program that requires to save user input. So I would like to know how to save JTextArea to text file and when you close and re-open program text is still in JTextArea.
Also sorry for my bad grammar.
package main;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.EtchedBorder;
public class main extends JFrame {
JLabel statusbar;
public main() {
initUI();
}
public final void initUI() {
JPanel panel = new JPanel();
statusbar = new JLabel("");
statusbar.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
panel.setLayout(null);
JTextArea area1;
area1 = new JTextArea(90, 25);
area1.setBounds(20, 20, 200, 25);
area1.setBackground(Color.white);
area1.setForeground(Color.BLACK);
area1.setText("");
panel.add(area1);
add(panel);
add(statusbar, BorderLayout.SOUTH);
setTitle("Viskis");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton o = (JButton) e.getSource();
String label = o.getText();
statusbar.setText("");
} }
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
main ms = new main();
ms.setVisible(true);
new main();
}
});
}
}
Here are some helper methods to help you read and write from Files. Look in the JavaDoc for getText() and setText() for getting and setting the text of the JTextArea.
I recommend reading the SwingWorker tutorials and using these methods in a SwingWorker, lest you lock up your GUI while saving/reading the Files
/**
* Writes a String text to a File specified by filename
*
* #param filename The filename/path of the File we would like to write the text to
* #param text The text to write to the File
*
*/
public static void writeToFile(String filename, String text) {
BufferedWriter writer = null; // This could go in a try-with-resources if you wanna get fancy
try {
writer = new BufferedWriter(new FileWriter(new File(filename))); // Open a File for writing
writer.write(text); // write the text to the file
} catch ( IOException e) {
/* We could not open the File for writing, or could not write to the File */
} finally {
try {
if (writer != null) {
writer.close(); // we are done writing to the File, close the connection
}
} catch (IOException e) {
/* We could not close the connection to the File */
}
}
}
/**
* Reads all lines from a File specified by filename
*
* #param filename The filename/path of the File we would like to read text from
*
* #return An list of Strings containing each line of the File
*/
public static List<String> readFromFile(String filename) {
BufferedReader reader = null; // This could go in a try-with-resources if you wanna get fancy
List<String> lines = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader(new File(filename))); // Open a File for writing
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} catch (IOException e) {
/* We could not open the File for reading, or could not read from the File */
} finally {
try {
if (reader != null) {
reader.close(); // we are done reading from the File, close the connection
}
} catch (IOException e) {
/* We could not close the connection to the File */
}
}
return lines;
}
Write and read file on a swing thread is not recommanded. Use mvc pattern. Create a data model with field binded to your component. Create an adapter to update model and write file
Then your component will always up to date with your model
Use model to write data(with the adapter) and read file will update your model with the adapter
For exemple, Focus listener will call adapter to do the task. Or you can use an obseevee pattern when you Object if modified.
This code worked for me with 'nam' as the current date and 'name' an input in a jTextField.
try {
con=Connect.ConnectDB();
pst.execute();
Date date=new Date();
SimpleDateFormat sd=new SimpleDateFormat("dd-mm-yyyy-h-m-s");
String nam= sd.format(date);
String name=CaseNoField.getText();
CaseNoField.setText("");
FileWriter writer=new FileWriter( "C:\\path"+name+"("+nam+")"+".txt");
BufferedWriter bw=new BufferedWriter( writer );
JCaseArea.write( bw );
bw.close();
JCaseArea.setText("");
JCaseArea.requestFocus();
JOptionPane.showMessageDialog(null, "Case Saved");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
Related
I've managed to make the input into a string which is available within the same class but I want to make it so the input string can be available in different classes. Current class is OpenDetails and I want the string selectedFile to be available in a different class called OpenFileInfo. How would I set it so the result from selectedFile can be stored in either selectedRequirement or make it available in other classes?
I'm new to Java so if someone could help thank you.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class OpenFile
{
String selectedRequirement = "";
public static void main(String a[])
{
JFrame parent = new JFrame();
String selectedFile;
selectedFile = JOptionPane.showInputDialog(parent, "Add a new module");
if(selectedFile.equalsIgnoreCase(selectedFile)){
//Makes the user input case insensitive
}
final JTextArea edit = new JTextArea(60,100);
JButton read = new JButton("Open "+ selectedFile +".txt");
read.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileReader reader = new FileReader(selectedFile + ".txt");
BufferedReader br = new BufferedReader(reader);
edit.read( br, null );
br.close();
edit.requestFocus();
}
catch(Exception e2) { System.out.println(e2); }
}
});
JButton write = new JButton("Save "+ selectedFile + ".txt");
write.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileWriter writer = new FileWriter(selectedFile + ".txt");
BufferedWriter bw = new BufferedWriter( writer );
edit.write( bw );
bw.close();
edit.setText("");
edit.requestFocus();
}
catch(Exception e2) {}
}
});
System.out.println("Module: " + selectedFile);
JFrame frame = new JFrame("Requirements");
frame.getContentPane().add( new JScrollPane(edit), BorderLayout.NORTH );
frame.getContentPane().add(read, BorderLayout.WEST);
frame.getContentPane().add(write, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
As you are running from a static context, you need to define selectedRequirement as static:
private static String selectedRequirement = "";
To make selectedRequirement equal to selectedFile, simply say selectedRequirement = selectedFile; towards the end of the main function (maybe where you print it already).
To make selectedRequirement available to other classes, you need to create a "getter function" in the OpenFIle class (outside of the main function) like:
public String getSelectedRequirement(){
return selectedRequirement;
}
As pointed out in the comments, it would be a good idea for you (or anyone who finds this in the future) to look at some tutorials on getters, setters, and general encapsulation.
I am working on project "Distributed Web Crawler using Java RMI".
The web crawls the pages and displays the URLs on two consoles-- a client one and a server one.
My problem is that I have to read these URLs from the console and display it under a Text Area in a window. I have tried a lot but the URLs are not getting displayed in Text Area.
However they were getting displayed on the console.
My code is:
import java.net.*;
import java.io.*;
import java.util.Date;
import java.io.File;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.Channels;
import java.rmi.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class UCDemo implements ActionListener {
static String dispServerURL;
JFrame f1;
JPanel p1;
JLabel l1;
JLabel l2;
JTextField t1;
JTextArea t2;
JButton b1;
public void showFrame() {
f1 = new JFrame("Web Crawler");
p1 = new JPanel();
f1.setSize(7000, 7000);
f1.setVisible(true);
f1.setBackground(Color.pink);
f1.getContentPane().add(p1);
l1 = new JLabel("Enter seed URL");
t1 = new JTextField(100);
b1 = new JButton("Start");
l2 = new JLabel("Result");
t2 = new JTextArea(200, 200);
p1.add(l1);
p1.add(t1);
p1.add(b1);
p1.add(l2);
p1.add(t2);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
try {
DispServerIntf dispServerIntf = (DispServerIntf) Naming.lookup(dispServerURL);
if (ae.getSource() == b1) {
String n1, k;
InputStreamReader ir = new InputStreamReader(System.in);
n1 = t1.getText();
int c = 0;
Document document = null;
URL hp = new URL(n1);
URLConnection hpcon = hp.openConnection();
try {
document = Jsoup.parse(hp, 3000);
} catch (IOException e) {
e.printStackTrace();
}
for (Element element : document.getElementsByTag("a")) {
c++;
ReadableByteChannel rbc = Channels.newChannel(hp.openStream());
FileOutputStream fos = new FileOutputStream("te.html");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
if (c <= 7) {
Document doc_tmp = null;
URL hp_tmp = new URL(element.attr("href"));
t2.setText("" + hp_tmp);
URLConnection hpcontmp = hp_tmp.openConnection();
/**
* try { doc_tmp=Jsoup.parse(hp_tmp,3000); }
* catch(IOException e) {e.printStackTrace(); } for
* (Element ele: doc_tmp.getElementsByTag("a")) {
* System.out.println(ele.attr("href")); }
**/
ReadableByteChannel rbc_tmp = Channels.newChannel(hp_tmp.openStream());
FileOutputStream fos_tmp = new FileOutputStream("te" + c + ".html");
fos_tmp.getChannel().transferFrom(rbc_tmp, 0, Long.MAX_VALUE);
} else {
dispServerIntf.send(element.attr("href"));
}
}
/**
* BufferedReader in=new BufferedReader(new
* InputStreamReader(hpcon.getInputStream())); String inputline;
* while((inputline=in.readLine())!=null)
* System.out.println(inputline); in.close();
**/
}
} catch (Exception e) {
}
}
public static void main(String args[]) {
dispServerURL = "rmi://" + args[0] + "/DispServer";
new UCDemo().showFrame();
}
}
One problem is that you are doing all the work in a loop on the AWT thread (the "event dispatch thread") within the actionPerformed method, and updating the GUI in that loop.
This means that the GUI will not be updated properly (because the thread that updates the GUI is busy doing the HTML parsing work, and does not become free to process GUI events). You probably need to do the main loop in a separate thread, then update the GUI in the AWT thread using invokeLater().
See:
this tutorial, for example,
and the linked introduction to threading in Swing.
The official Swing Java Tutorial on this topic, which assumes you have read...
...the Concurrency lesson
Also, you always set the text to a single value, so you would only see the latest URL, not a list of them:
t2.setText("" + hp_tmp);
Hi all I am creating a simple text editor as a project and I have hit a snag when it comes to saving the content typed as a file. I can save the file using the Save As principle with a dialog box prompting the user to enter a filename.
The problem I am having is implementing the Save so that it saves to the file that is opened without having to go to the dialog box each time, like it would if someone did Ctrl+S. Anyone have any ideas how I would implement this feature?
Here's some of my code:
JMenuItem saveFile = new JMenuItem(new AbstractAction("Save") {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser save = new JFileChooser();
File filename = save.getSelectedFile();
if(opened == false && saved == false) {
save.showSaveDialog(null);
int confirmationResult;
if(filename.exists()) {
confirmationResult = JOptionPane.showConfirmDialog(getParent(), "Replace existing file?");
if(confirmationResult == JOptionPane.YES_OPTION) {
saveFile(filename);
}
} else {
saveFile(filename);
}
} else {
saveFile(filename);
}
}
});
saveFile.setPreferredSize(new Dimension(100, 20));
saveFile.setEnabled(true);
save method:
private void saveFile(File filename) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
writer.write(textArea.getText());
writer.close();
saved = true;
editorWindow.setTitle("JavaText - " + filename.getName());
} catch (IOException err) {
err.printStackTrace();
}
}
If you store the opened File object somewhere in your application you can then just pass that into your saveFile method on a key press using a KeyListener or KeyAdapter. Without seeing more of the application it's hard to tell where would be best to put it, but if you just store it in a variable somewhere you can refer back to it.
Store the file name somewhere
if(nameOfFile != null) then don't show the dialog box and go to save method
else show dialog box and call the save method
That's what I would do
The following program shows the implementation of 'Save' & 'Save as' functionality for text editors. Running it will shows a JFrame with a JTextArea , save JButton & save as JButton.
import java.awt.BorderLayout;
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.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class MyFrame extends JFrame {
private boolean alreadySaved = false;
private BufferedWriter bw;
private JFileChooser fileChooser;
private JTextArea jta;
private File file;
private JButton save;
private JPanel mainPanel;
private JButton saveAs;
public MyFrame() {
initComponents();
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (!alreadySaved) {
int response = fileChooser.showSaveDialog(getParent());
file = fileChooser.getSelectedFile();
if (response == JFileChooser.APPROVE_OPTION) {
writeFile();
alreadySaved = true;
}
} else
writeFile();
}
});
saveAs.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
int response = fileChooser.showSaveDialog(getParent());
file = fileChooser.getSelectedFile();
if (response == JFileChooser.APPROVE_OPTION) {
writeFile();
alreadySaved = true;
}
}
});
} // END of Constructor
public void writeFile() {
try {
bw = new BufferedWriter(new FileWriter(file));
bw.write(jta.getText());
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void initComponents() {
fileChooser = new JFileChooser();
saveAs = new JButton("Save as");
jta = new JTextArea(10, 40);
mainPanel = new JPanel();
mainPanel.setBackground(Color.red);
save = new JButton("Save");
mainPanel.add(save);
mainPanel.add(saveAs);
this.setLayout(new BorderLayout());
this.add(jta);
this.add(mainPanel, BorderLayout.SOUTH);
this.pack();
this.setLocationRelativeTo(null);
}
public static void main(String[] args) {
new MyFrame().setVisible(true);
}
}
I'm working on JTable that reads text from a .txt file. the txt file gets updated dynamically after 3 sec. Now when I run the application, everything is good except that the output of .txt files comes in JTable from the second line. The first line of txt file doesn't appear on my JTable. Can anyone help? Here's the code:
public class InterfaceFrame extends JFrame implements ActionListener{
public static void main(String[] args) throws
URISyntaxException,
IOException,
InterruptedException {
panel.setSize(100,100);
panel.add(table);
model.fireTableStructureChanged();
table.setModel(model);
InsertFileToJtable model = new InsertFileToJtable();
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
RowSorter<TableModel> sorter =
new TableRowSorter<TableModel>(model);
table.setRowSorter(sorter);
JScrollPane scrollpane = new JScrollPane(table);
panel.add(scrollpane, BorderLayout.CENTER);
JButton button = new JButton("Show View");
panel.add( button, BorderLayout.SOUTH );
tabbedPane.addTab("Process",null,scrollpane,"");
}
I might be doin something wrong in making the text file. Here's the code which generated the .txt file.:
import java.io.*;
import java.util.StringTokenizer;
public class GetProcessList
{
private String GetProcessListData()
{
Process p;
Runtime runTime;
String process = null;
try {
System.out.println("Processes Reading is started...");
//Get Runtime environment of System
runTime = Runtime.getRuntime();
//Execute command thru Runtime
p=runTime.exec("ps -e"); //For Linux
//Create Inputstream for Read Processes
InputStream inputStream = p.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//Read the processes from sysrtem and add & as delimeter for tokenize the output
String line = bufferedReader.readLine();
process = "&";
while (line != null) {
line = bufferedReader.readLine();
process += line + "&";
}
//Close the Streams
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
System.out.println("Processes are read.");
} catch (IOException e) {
System.out.println("Exception arise during the read Processes");
e.printStackTrace();
}
return process;
}
void showProcessData()
{
try {
//Call the method For Read the process
String proc = GetProcessListData();
//Create Streams for write processes
//Given the filepath which you need.Its store the file at where your java file.
OutputStreamWriter outputStreamWriter =
new OutputStreamWriter(new FileOutputStream("ProcessList.txt"));
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
//Tokenize the output for write the processes
StringTokenizer st = new StringTokenizer(proc, "&");
while (st.hasMoreTokens()) {
bufferedWriter.write(st.nextToken()); //Write the data in file
bufferedWriter.newLine(); //Allocate new line for next line
}
//Close the outputStreams
bufferedWriter.close();
outputStreamWriter.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
Heres the code that reads ProcessList.txt and gives output into JTable:
import java.io.*;
import java.awt.*;
import java.util.*;import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.*;
public class InsertFileToJtable extends AbstractTableModel{
Vector data;
Vector columns;
private String[] colNames = {"<html><b>PID</b></html>","<html><b>TTY</b</html>",<html> <b>time</b></html>","<html><b>Process Name</b></html>",};
public InsertFileToJtable() {
String line;
data = new Vector();
columns = new Vector();
try {
FileInputStream fis = new FileInputStream("ProcessList.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
while (st1.hasMoreTokens())
columns.addElement(st1.nextToken());
while ((line = br.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line, " ");
while (st2.hasMoreTokens())
data.addElement(st2.nextToken());
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public int getRowCount() {
return data.size() / getColumnCount();
}
public int getColumnCount() {
return columns.size();
}
public Object getValueAt(int rowIndex, int columnIndex) {
return (String) data.elementAt((rowIndex * getColumnCount())
+ columnIndex);
}
#Override
public String getColumnName(int column) {
return colNames[column];
}
#Override
public Class getColumnClass(int col){
return getValueAt(0,col).getClass();
}
}
I'd do this a little differently, avoiding an intermediate text file. Instead,
Use ProcessBuilder, which "can be invoked repeatedly from the same instance." You can read the output as shown here and parse it into a suitable data structure, e.g. List<List<String>>.
ProcessBuilder pb = new ProcessBuilder("ps -ef");
Start a javax.swing.Timer having a three second period; invoke pb.start() in the timer's listener.
When parsing concludes, fireTableDataChanged() in your AbstractTableModel, shown here.
Presto, your table updates with the latest result every three seconds.
How to put a dropdown list that has the list of every string, and when I select a item on that list then push the load button it will only show up what's on that String. Here's my code, I actually put the number of the string and and show the String's data using while statements.
How can I actually put a Dropdown list and it's content will be a number registered on every string. Just like this
1 231231
2 123124
3 123124
4 232312
If I select 4 and press "Load" it will show "232312"
and everytime I save a data a unique number will be registered in every line, just like
"4" is the unique no. and 232312 is it's data
package datasaving;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;
public class Datasaving {
/**
* #param args the command line arguments
* #throws FileNotFoundException
* #throws IOException
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
JPanel panel = new JPanel();
JFrame frame = new JFrame();
final JTextField input0 = new javax.swing.JTextField(20);
final JTextField input1 = new javax.swing.JTextField(20);
final JTextField out = new javax.swing.JTextField(20);
final JTextField line = new javax.swing.JTextField(20);
JButton save = new javax.swing.JButton("Save");
JButton load = new javax.swing.JButton("Load");
frame.add(panel);
frame.setSize(240,200);
panel.add(input0);
panel.add(input1);
panel.add(save);
panel.add(line);
panel.add(out);
panel.add(load);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
File file = new File("data.dat");
try {
try (FileWriter writer = new FileWriter(file, true)) {
String data0 = input0.getText();
String data1 = input1.getText();
writer.write(data0+":"+data1+"\n");
}
System.out.println("Data Saved");
} catch (IOException | HeadlessException z) {
JOptionPane.showMessageDialog(null, e);
}
}
});
load.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int lines = Integer.parseInt(line.getText());
try {
FileInputStream fs= new FileInputStream("data.dat");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
for(int i = 0; i < lines; ++i) {
br.readLine();
}
out.setText(br.readLine());
JOptionPane.showMessageDialog(null, "Loaded");
} catch ( IOException | HeadlessException es) {
JOptionPane.showMessageDialog(null, e);
}
}
});
}
}
for example:
John blahblahblahblah
Keith blahblahblahblah
Joe blahblahblahblah
Kenneth blahblahblahblah
Christian blahblahblahblah
The first word "Names" will be added to JList or JComboBox
how to make the names a Array. I know how to use .split(); but I don't know how to make that happen in every lines in the file
1) JTextField doesn't support multi-line. Try JTextArea instead. With text areas, you can use myTextArea.append() to add lines as you read them.
2) But actually, it sounds like a JComboBox or a JList might be what you're really looking for:
http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html
3) Your basic program looks OK
'Hope that helps!