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)
Related
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());
I have a label that isn't updating in the same instance of the GUI.
If I click the jButton that should update the value on a jLabel ("testLabel" from block of code), I have to run the java program again to see the change appear. How can I get it to appear on button click in the same instance?
I know about invokelater and I've been playing with it trying to get it to update in real time, but with no luck. I've been stuck on this for awhile now so any help is appreciated.
With the block of code listed below I still have to run a new instance of the GUI to get the value to update.
Related code:
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MISControlPanel window = new MISControlPanel();
window.frame.setVisible(true);
// testLabel.setText(CN);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
JButton searchComputerButton = new JButton("Search");
searchComputerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String line;
BufferedWriter bw = null;
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(tempFile));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// String lineToRemove = "OU=Workstations";
String s = null;
Process p = null;
/*
* try { // p = Runtime.getRuntime().exec(
* "cmd /c start c:\\computerQuery.bat computerName"); } catch
* (IOException e1) { // TODO Auto-generated catch block
* e1.printStackTrace(); }
*/
try {
p = Runtime.getRuntime().exec("c:\\computerQuery.bat");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
StringBuffer sbuffer = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(p
.getInputStream()));
try {
while ((line = in.readLine()) != null) {
System.out.println(line);
// textArea.append(line);
String dn = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
LdapName ldapName = new LdapName(dn);
String commonName = (String) ldapName.getRdn(
ldapName.size() - 1).getValue();
}
ComputerQuery.sendParam();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvalidNameException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally
{
try {
fw.close();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ComputerQuery.sendParam();
}
});
try (BufferedReader br = new BufferedReader(new FileReader(
"resultofbatch.txt"))) {
final Pattern PATTERN = Pattern.compile("CN=([^,]+).*");
try {
while ((sCurrentLine = br.readLine()) != null) {
String[] tokens = PATTERN.split(","); // This will return
// you a array,
// containing the
// string array
// splitted by what
// you write inside
// it.
// should be in your case the split, since they are
// seperated by ","
// System.out.println(sCurrentLine);
CN = sCurrentLine.split("CN=", -1)[1].split(",", -1)[0];
System.out.println(CN);
testLabel.setText(CN);
}
Full Class Code
http://pastebin.com/havyqMxP
Computer Query Class (Small Class)
http://pastebin.com/Q89BCjya
As promised... here is a simple example of fetching an URL content using swing worker to decouple the task of getting the contents (the long running task) from the task that update the swing components. This will show an example of how you should approach this issue...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingWorker;
/* FrameDemo.java requires no other files. */
public class MainWindow extends JFrame {
private static final Logger LOOGER = Logger.getLogger(MainWindow.class.getName());
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private JLabel statusLabel = new JLabel("Status");
private JButton actionButton = new JButton("Push me");
public MainWindow() {
super("FrameDemo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
statusLabel = new JLabel("Status");
actionButton = new JButton("Push me");
statusLabel.setPreferredSize(new Dimension(400, 50));
actionButton.setPreferredSize(new Dimension(100, 50));
getContentPane().setLayout(new BorderLayout());
getContentPane().add(statusLabel, BorderLayout.NORTH);
getContentPane().add(actionButton, BorderLayout.CENTER);
actionButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// THIS METHOD IS INVOKED WITHIN THE EVENT DISPATCH THREAD!!.. SO IS CRUCIAL TO NOT PERFORM
// HERE LONG TIME RUNNING TASKS...
actionButton.setEnabled(false); // let's disable this button, in order to avoid invoking
// multiple times the same task and messing up the entire app...
UrlFechterSwingWorker urlFechterSwingWorker = new UrlFechterSwingWorker();
urlFechterSwingWorker.execute();
}
});
}
public void display() {
pack();
setVisible(true);
}
private class UrlFechterSwingWorker extends SwingWorker<String, String> {
#Override
public String doInBackground() { // this method is executed under a worker thread
BufferedReader in;
StringBuilder sb = new StringBuilder();
try {
URL url = new URL("http://www.stackoverflow.com");
in = new BufferedReader(new InputStreamReader(url.openStream()));
String line = in.readLine();
while (line != null) {
sb.append(line);
publish(line); // publish partial results....
line = in.readLine();
}
in.close();
} catch (Exception e) {
LOOGER.log(Level.SEVERE, "", e);
}
return sb.toString();
}
#Override
protected void process(List<String> readedLines) { // this method in the Event dispatch Thread
// do what you want to do with the readedLines....
statusLabel.setText("The doInBackground read... " + readedLines.size() + " lines");
}
#Override
public void done() { // this method in the Event dispatch Thread
// do what you want when the process finish
actionButton.setEnabled(true); // well.. at least i would like to enable the button again...
}
}
public static void main(String[] args) {
MainWindow mainWindow = new MainWindow();
mainWindow.display();
}
}
Here are more tips:
After you understand (more or less) how things are working in the above example.. you will have to implement a proper doInBackground method that perform all the LDAP stuff, for this you will have to make your mind to conceive a way of informing the progress to a end user... i mean, look my example, is very poor regarding progress advance.. all the thing that i am stating is that, we read "a number of lines" from a given url. You should think what is the best way to inform progress regarding your task.. there is no template for this except the understanding of the underlying domain model.
Have in mind that swing workers has two ways to inform about the progress.
One is using the publish and process method in conjunction. (Like the example above)
Other is to to modify internal properties (progress and state) inside the method doInBackground, and attach a PropertyChangeListener to the swing worker. This propertyChangeListener object has a method whose signature is public void propertyChange(PropertyChangeEvent evt) (a little more complex, on my point of view..)
Patience and good luck!
My GUI application allows users to type into a JTextField object stating the name of a file to open and display its contents onto a JTextArea object. If the entered information consists of the file name then it shall retrieve its contents otherwise, in other case, it shall be a directory then it shall display the files and folders. Right now, I'm stuck as in the setText() of my JTextArea does not display contents correctly. It only display once which means to say there's some problem with my while loop. Could you guys help me out here please?
Please note the code below has been altered to the correct working version provided all the helpful contributors below.
Main class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
class MyFileLister extends JPanel implements ActionListener {
private JLabel prompt = null;
private JTextField userInput = null;
private JTextArea textArea = null;
public MyFileLister()
{
prompt = new JLabel("Enter filename: ");
prompt.setOpaque(true);
this.add(prompt);
userInput = new JTextField(28);
userInput.addActionListener(this);
this.add(userInput);
textArea = new JTextArea(10, 30);
textArea.setOpaque(true);
JScrollPane scrollpane = new JScrollPane(textArea);
this.add(textArea, BorderLayout.SOUTH);
}
Scanner s = null;
File af = null;
String[] paths;
public void actionPerformed(ActionEvent f)
{
try
{
s = new Scanner(new File(userInput.getText()));
while(s.hasNextLine())
{
String as = s.nextLine();
textArea.append(as + "\n");
textArea.setLineWrap(truea);
}
}
catch(FileNotFoundException e)
{
af = new File(userInput.getText());
paths = af.list();
System.out.println(Arrays.toString(paths));
String tempPath = "";
for(String path: paths)
{
tempPath += path + "\n";
}
textArea.setText(tempPath);
}
}
}
Driver class:
import java.util.*;
import java.awt.*;
import javax.swing.*;
class TestMyFileLister {
public static void main(String [] args)
{
MyFileLister thePanel = new MyFileLister();
JFrame firstFrame = new JFrame("My File Lister");
firstFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
firstFrame.setVisible(true);
firstFrame.setSize(500, 500);
firstFrame.add(thePanel);
}
}
Here's one of the screenshot which I have to achieve. It shows that when the user's input is on a directory it displays the list of files and folders under it.
I tried to put in an if statement to see if I can slot in a show message dialog but I seriously have no idea where to put it.
public void actionPerformed(ActionEvent f)
{
try
{
s = new Scanner(new File(userInput.getText()));
if(af == null)
{
System.out.println("Error");
}
while(s.hasNextLine())
{
String as = s.nextLine();
textArea.append(as + "\n");
textArea.setLineWrap(true);
}
}
catch(FileNotFoundException e)
{
af = new File(userInput.getText());
paths = af.list();
System.out.println(Arrays.toString(paths));
String tempPath = "";
for(String path: paths)
{
tempPath += path + "\n";
}
textArea.setText(tempPath);
}
}
You're outputting text to textArea based on the Last File on the list !!! ( don't set your text to JTextArea directly inside a loop, the loop is fast and the UI can't render it, so concatenate the string then set it later after the loop finishes ).
// These lines below are causing only last file shown.
for(String path: paths)
{
textArea.setText(path);
}
Here is your modified version for MyFileLister class :
public class MyFileLister extends JPanel implements ActionListener {
private JLabel prompt = null;
private JTextField userInput = null;
private JTextArea textArea = null;
public MyFileLister()
{
prompt = new JLabel("Enter filename: ");
prompt.setOpaque(true);
this.add(prompt);
userInput = new JTextField(28);
userInput.addActionListener(this);
this.add(userInput);
textArea = new JTextArea(10, 30);
textArea.setOpaque(true);
JScrollPane scrollpane = new JScrollPane(textArea);
this.add(scrollpane, BorderLayout.SOUTH);
}
Scanner s = null;
File af ;
String[] paths;
public void actionPerformed(ActionEvent f)
{
try
{
s = new Scanner(new File(userInput.getText()));
while(s.hasNext())
{
String as = s.next();
textArea.setText(as);
}
}
catch(FileNotFoundException e)
{
af = new File(userInput.getText());
paths = af.list();
System.out.println(Arrays.toString(paths));
String tempPath="";
for(String path: paths)
{
tempPath+=path+"\n";
}
textArea.setText(tempPath);
}
}
}
Output :
Code:
public void actionPerformed(ActionEvent ae) {
try (Scanner s = new Scanner(new File(userInput.getText()))) {
while (s.hasNextLine()) {
String as = s.nextLine();
textArea.append(as + "\n");
textArea.setLineWrap(true);
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this,
"File not found",
"No File Error",
JOptionPane.ERROR_MESSAGE);
}
}
Notes:
Just try to read your file line by line so you can copy the same structure from your file into your JTextArea.
Use setLineWrap method and set it to true
read here http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html#setLineWrap(boolean)
use append method in order to add text to end of your JTextArea
read here
http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html#append(java.lang.String)
Use JOptionPane to show error message to an user
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.
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.