Drag and drop TXT file into TextArea - java

Here I have text area called sourceTx in which I drag and drop files, then I read content of that file with BufferedReader. As you can see from bellow code I set file from which I am reading content with absolutepath.
So, when I drag an drop some .txt file it works, it reads content and put it in text area, but when I also drag and drop some folder for example it also reads some content and put it in text area.
So I want set this drag and drop to read only .txt files? How I can get that?
Here is code of that method:
public void dragDrop(){
sourceTx.setOnDragOver(new EventHandler <DragEvent>() {
#Override
public void handle(DragEvent event) {
Dragboard db = event.getDragboard();
if(db.hasFiles()){
event.acceptTransferModes(TransferMode.ANY);
for(File file:db.getFiles()){
String absolutePath = file.getAbsolutePath();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(absolutePath)));
String line = null;
String text = "";
String nl = System.getProperty("line.separator", "\n");
while((line = br.readLine()) != null)
text += line + nl;
sourceTx.setText( text.trim() );
} catch (Exception e) {
MessageBox.show(MessageBoxType.ERROR, I18n.localize("File Error"), I18n.localize("Error while reading content from selected file"));
} finally{
if(br != null)
try {
br.close();
} catch (Exception e) {}
}
}
}else{
event.setDropCompleted(false);
}
event.consume();
}
});
}

Hi there try to read your file with recursion
...
for (File file : db.getFiles()) {
sourceTx.setText(handleFile(file));
}
...
private String handleFile(File file) {
String ret = "";
if (file.isDirectory()) {
for (File f : file.listFiles()) {
ret.concat(handleFile(f));
}
} else {
/*this is your filereader*/
String absolutePath = file.getAbsolutePath();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(absolutePath)));
String line = null;
String text = "";
String nl = System.getProperty("line.separator", "\n");
while ((line = br.readLine()) != null)
text += line + nl;
ret.concat(text.trim());
} catch (Exception e) {
MessageBox.show(MessageBoxType.ERROR, I18n.localize("File Error"), I18n.localize("Error while reading content from selected file"));
} finally {
if (br != null)
try {
br.close();
} catch (Exception e) {
}
}
}
return ret;
}

I found a good resource online on using drag and drop.
Here are some classes/things that you might want to investigate:
java.awt.dnd.*
I practically copied this from a tutorial online but here is some code (not mine, but tested and it works):
public class MyFrame extends JFrame
{
// insert other code here
JLabel myLabel = new JLabel("My stuff here");
// Create the drag and drop listener
MyDragDropListener myDragDropListener = new MyDragDropListener(this);
// Connect the label with a drag and drop listener
new DropTarget(myLabel, myDragDropListener);
// then just add the label
// also have a method something like "get" which will be used so that the listener can send
// the list of files dropped here, and you can process it here
}
Now for the MyDragDropListener.
import java.awt.dnd.*;
import java.awt.datatransfer.*;
import java.io.File;
import java.util.List;
public class MyDragDropListener implements DropTargetListener
{
MyFrame frame; // initialize in a constructor that takes in the frame
#Override
public void dragEnter(DropTargetDragEvent event) {
}
#Override
public void dragExit(DropTargetEvent event) {
}
#Override
public void dragOver(DropTargetDragEvent event) {
}
#Override
public void dropActionChanged(DropTargetDragEvent event) {
}
#Override
public void drop(DropTargetDropEvent event)
{
// This is the main chunk of the drag and drop.
event.acceptDrop(DnDConstants.ACTION_COPY);
Transferable transferable = event.getTransferable();
DataFlavor[] flavors = transferable.getTransferDataFlavors();
for(DataFlavor flavor : flavors)
{
if(flavor.isFlavorJavaFileListType())
{
List myFiles = (List) transferable.getTransferData(flavor);
frame.get(myFiles);
}
}
}
}
You can use this to create a JFrame to drag and drop the files, then check if the filename contains ".txt" ( I am not sure if Java has methods of determining the type of file even if it has no extensions .) If it contains ".txt" then you can open it in the TextArea.
If anyone can please help me find the original tutorial/site, I would really appreciate it. Also sorry for the formatting of the answer.

Related

Java implementing a FileOpener

So am trying to make a button where it opens a FileChoser to import an image .
My probleme is :
1-I want the fileChoser to display only images-files(.jpg ...).
2-When the FileOpener opens , the other windows should be Disabled until the
FileOpener is disposed . In my case , they are disabled but when I click on them my programe crashes for some reason .
3-If there is a better FileOpener it will be welcomed , this si not mine I found it on the net .
Here's my source code :
public class FileOpener {
private JFileChooser file_chooser = new JFileChooser();
StringBuilder path = new StringBuilder();
public File choosed() {
File file = null;
if(file_chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = file_chooser.getSelectedFile();
Scanner input = null;
try {
input = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("Fail");
e.printStackTrace();;
}
while(input.hasNext()) {
path.append(input.nextLine());
}
input.close();
}
return file;
}
public String getPath() {
return path.toString();
}
}
And here's my call (Where there is a probleme is the enable-disable window) :
Button button_2 = new Button(composite_1, SWT.FLAT);
button_2.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
shell.setEnabled(false);
FileOpener v = new FileOpener();
File file = v.choosed();
if(file != null) {
Image image = new Image(shell.getDisplay(), file.getPath());
Image image2 = main.ScaleImage(image, Image_input);
Image_input.setImage(image2);
}
shell.setEnabled(true);
}
});
Notice that this code works , but am trying just to fix the bugs,the "ScaleImage" fonction reScale the chosen Image to fit my label.
I managed to fix the Enable-disable problem simply by removing all what was interfering with the shell :
Button button_2 = new Button(composite_1, SWT.FLAT);
button_2.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
FileOpener v = new FileOpener();
File file = v.choosed();
shell.forceActive();
if(file != null) {
Image image = new Image(shell.getDisplay(), file.getPath());
Image image2 = main.ScaleImage(image, Image_input);
Image_input.setImage(image2);
}
}
});
I fixed completly my probleme by using FileDialog :
Button button_2 = new Button(composite_1, SWT.FLAT);
button_2.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
FileDialog test = new FileDialog(shell);
test.open();
File file = new File(test.getFilterPath()+"\\"+test.getFileName());
if(file != null) {
Image image = new Image(shell.getDisplay(), file.getPath());
Image image2 = main.ScaleImage(image, Image_input);
Image_input.setImage(image2);
}
}
});
Thanks for greg-449 for the answer .I didn't know how to exactly work with the new GUI but to get the file path :
test.getFilterPath()+"\\"+test.getFileName()

How to access another object from within a listener in Java

I have a listener on one of the elements of the menu class GraphMenu() in my program that that needs to call a method of an existing object created outside that class and I can't seem to find a way to implement this.
I'm defining the method of the panel I need to call in the GraphPanel() class:
public class GraphPanel extends JPanel {
private JLabel textLabel, graphicLabel;
private JTextArea textArea;
private JPanel graphPanel;
public void appendTextArea(String s) {
textArea.append(s + '\n');
}
The listener of the GraphMenu() I need to call that method in is:
public class GraphMenu {
...
// Add the action listeners that identify the code to execute when the options are selected.
menuItemLoad.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
final JFileChooser fc = new JFileChooser();
// you can set the directory with the setCurrentDirectory method.
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
// User has selected to open the file.
File file = fc.getSelectedFile();
try {
// Open the selected file
BufferedReader reader = new BufferedReader(new FileReader(file));
// Output the contents to the console.
String nextLine = reader.readLine();
while ( nextLine != null ) {
panel.appendTextArea(nextLine);
System.out.println(nextLine);
nextLine = reader.readLine();
}
reader.close();
} catch (IOException e1) {
System.err.println("Error while reading the file");
}
};
}
});
...
Is there a way I can call the appendTextArea() on the panel object as in the example above?
I'm creating the two objects of class GraphPanel() and GraphMenu() in the main function:
GraphPanel panel = new GraphPanel();
frame.getContentPane().add(panel);
GraphMenu menu = new GraphMenu();
frame.setJMenuBar(menu.setupMenu());

How to fit JTextArea as my file require?

I want my JTextArea to show text as in the txt file. But it is showing the whole text in only row.
http://pastebin.com/Y8vWUvtg
package jBoxThreadTry;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class GuestFinal extends JFrame implements Runnable {
private JLabel test;
private JTextArea txtArea;
private String titleBar;
private static String fileName;
private String[] CSEterms = {"CSE11.txt", "CSE12.txt", "CSE21.txt",
"CSE22.txt", "CSE31.txt", "CSE32.txt", "CSE41.txt", "CSE42.txt"};
private boolean threadAliveFlag;
public GuestFinal(boolean threadAliveFlag) {
// TODO Auto-generated constructor stub
// super()
this.threadAliveFlag = threadAliveFlag;
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (threadAliveFlag) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
setVisible(true);
setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH);
/*test = new JLabel("yes");
add(test);
*/
setTitle(titleBar);
threadAliveFlag = false;
}
} catch (Exception e) {
// TODO: handle exception
}
}
public void setBool(boolean b) {
// TODO Auto-generated method stub
threadAliveFlag = b;
}
public void setTitleBar(String string) {
// TODO Auto-generated method stub
titleBar = "Syllabus for " + string;
}
public void setFileToShow(int selectedIndex) {
// TODO Auto-generated method stub
fileName = CSEterms[selectedIndex];
showFile(fileName);
}
private void showFile(String fName) {
// TODO Auto-generated method stub
try {
FileInputStream fstream = new FileInputStream("syllabusDir\\"
+ fName);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
String line = br.readLine();
StringBuilder strBuilder = new StringBuilder();
while (line != null) {
// Print the content on the console
System.out.println(line);
strBuilder.append(line);
line = br.readLine();
}
String everything = strBuilder.toString();
txtArea = new JTextArea(everything);
add(txtArea);
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
"I want my JTextArea to show text as in the txt file. But it is showing the whole text in only row"
while (line != null) {
// Print the content on the console
System.out.println(line);
strBuilder.append(line);
line = br.readLine();
}
A string is just a long sequence of character. So what you are doing is just appending to the same sequence of characters. The way to separate lines is to make use of the line separator \n character. So you want to append that after every line.
strBuilder.append(line);
strBuilder.append("\n");
Alternativelive, not much of a difference in this case, but JTextArea also has an append method.
UPDATE
The most resonable approach is to just use the JTextArea.read() method, which you can pass the BufferedReader to, and that will read the whole file the text area. No need to loop and append.
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
JTextArea area = new JTextArea(10, 50);
area.read(reader, null);
Simple as that
This block of code:
while (line != null) {
// Print the content on the console
System.out.println(line);
strBuilder.append(line);
line = br.readLine();
}
change strBuilder.append(line); to strBuilder.append(line+"\n");
Append will not add the newline as you are intending here.
Also, use txtArea.setLineWrap(true); to ensure lines will always be wrapped if you are looking for that functionality.
Just to add a convenient way to read files using streams and NIO
public String readFile(String fName) throws IOException {
List<String> contents = Files.readAllLines(FileSystems.getDefault().getPath("syllabusDir\\"
+ fName));
return contents
.stream()
.collect(Collectors.joining("\n"));
}
Also see java.nio.file.Files#readAllLines(java.nio.file.Path, java.nio.charset.Charset)

How to save desktop application state?

I am creating an editor in java. I would like to know how to save an intermediate state in java?
For Example when user wants to save the changes done on the editor, how could it be done and also should be reloaded later.
Eg. powerpoint application is saved as .ppt or .pptx. Later the same .ppt while could be opened for further editions. I hope I am clear with my requirement.
The Preferences API with user preferences; most recently edited files, per file maybe timestamp + cursor position, GUI settings.
To save the contents of JTextPane you can serialize the DefaultStyledDocument of JTextPane in a file using proper way of serialization. And when you want to load the content again you can deserialize the same and display it on the JTextPane . Consider the code given below:
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class SaveEditor extends JFrame implements ActionListener{
public static final String text = "As told by Wikipedia\n"
+"Java is a general-purpose, concurrent, class-based, object-oriented computer programming language."
+ "It is specifically designed to have as few implementation "
+ "dependencies as possible. It is intended to let application developers write once, run anywhere (WORA), "
+ "meaning that code that runs on one platform does not need to be recompiled to run on another. "
+ "Java applications are typically compiled to bytecode (class file) that can run on any Java virtual "
+ "machine (JVM) regardless of computer architecture. Java is, as of 2012, one of the most popular programming "
+ "languages in use, particularly for client-server web applications, with a reported 10 million users.";
JTextPane pane ;
DefaultStyledDocument doc ;
StyleContext sc;
JButton save;
JButton load;
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
SaveEditor se = new SaveEditor();
se.createAndShowGUI();
}
});
} catch (Exception evt) {}
}
public void createAndShowGUI()
{
setTitle("TextPane");
sc = new StyleContext();
doc = new DefaultStyledDocument(sc);
pane = new JTextPane(doc);
save = new JButton("Save");
load = new JButton("Load");
JPanel panel = new JPanel();
panel.add(save);panel.add(load);
save.addActionListener(this);load.addActionListener(this);
final Style heading2Style = sc.addStyle("Heading2", null);
heading2Style.addAttribute(StyleConstants.Foreground, Color.red);
heading2Style.addAttribute(StyleConstants.FontSize, new Integer(16));
heading2Style.addAttribute(StyleConstants.FontFamily, "serif");
heading2Style.addAttribute(StyleConstants.Bold, new Boolean(true));
try
{
doc.insertString(0, text, null);
doc.setParagraphAttributes(0, 1, heading2Style, false);
} catch (Exception e)
{
System.out.println("Exception when constructing document: " + e);
System.exit(1);
}
getContentPane().add(new JScrollPane(pane));
getContentPane().add(panel,BorderLayout.SOUTH);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == save)
{
save();
}
else if (evt.getSource() == load)
{
load();
}
}
private void save()//Saving the contents .
{
JFileChooser chooser = new JFileChooser(".");
chooser.setDialogTitle("Save");
int returnVal = chooser.showSaveDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
if (file != null)
{
FileOutputStream fos = null;
ObjectOutputStream os = null;
try
{
fos = new FileOutputStream(file);
os = new ObjectOutputStream(fos);
os.writeObject(doc);
JOptionPane.showMessageDialog(this,"Saved successfully!!","Success",JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (fos != null)
{
try
{
fos.close();
}
catch (Exception ex){}
}
if (os != null)
{
try
{
os.close();
}
catch (Exception ex){}
}
}
}
else
{
JOptionPane.showMessageDialog(this,"Please enter a fileName","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
private void load()//Loading the contents
{
JFileChooser chooser = new JFileChooser(".");
chooser.setDialogTitle("Open");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = chooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
if (file!= null)
{
FileInputStream fin = null;
ObjectInputStream ins = null;
try
{
fin = new FileInputStream(file);
ins = new ObjectInputStream(fin);
doc = (DefaultStyledDocument)ins.readObject();
pane.setStyledDocument(doc);
JOptionPane.showMessageDialog(this,"Loaded successfully!!","Success",JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (fin != null)
{
try
{
fin.close();
}
catch (Exception ex){}
}
if (ins != null)
{
try
{
ins.close();
}
catch (Exception ex){}
}
}
}
else
{
JOptionPane.showMessageDialog(this,"Please enter a fileName","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
}

JTable reading text files from second line

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.

Categories