Java JList and JTextArea - jlist

I am stuck on a java project.
I am working with TXT files, and i have the open these TXT files from the JList.
Since i am a total noob at this, it took me a few hours to manage to make the JList work. But now i am stuck at the JTextArea.
The idea is this: clicking on a item from the JList (item = a TXT file from a folder), it should open that TXT file in the JTextArea to view it.
..here is my code so far ..it's a bit long:
-JButton for the search and putting the TXT files in the JList:
JButton searchSearchButton = new JButton("Search");
searchSearchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultListModel model1 = new DefaultListModel();
File dir = new File("C:\\Users\\Zoli\\Desktop\\New folder");
File[] matches = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(searchKeywordTextField.getText()) && name.endsWith(".txt");
}
});
for(File f : matches){
model1.addElement(f.getName());
}
searchList.setModel(model1);
}
});
searchSearchButton.setBounds(186, 43, 89, 23);
linuxSearchPane.add(searchSearchButton);
-This is the JTextArea and the JList code:
final JTextArea searchTextArea = new JTextArea();
JScrollPane searchTextAreaScrollPane = new JScrollPane(searchTextArea);
searchTextAreaScrollPane.setBounds(316, 43, 496, 430);
linuxSearchPane.add(searchTextAreaScrollPane);
final JList searchList = new JList();
searchList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
searchList.setVisibleRowCount(20);
searchList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
searchTextArea.setText("");
for(Object o : searchList.getSelectedValuesList()){
searchTextArea.append(o.toString()+"\r\n");
}
}
});
-All i managed to do is, when i select an item from the JList, it prints out the item name in the JTextArea not what it contains in the TXT.
Here is a picture to show you:
picture
could anyone please help me with this...i have zero idea...i have read about JList, and JTextArea, but nothing even points to what i need...
Please help.

I DID IT!!!
Here's the code:
final JTextArea searchTextArea = new JTextArea();
JScrollPane searchTextAreaScrollPane = new JScrollPane(searchTextArea);
searchTextAreaScrollPane.setBounds(316, 43, 496, 430);
linuxSearchPane.add(searchTextAreaScrollPane);
final JList searchList = new JList();
searchList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
searchList.setVisibleRowCount(20);
searchList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
searchTextArea.setText("");
String root = "C:\\Users\\Zoli\\Desktop\\New folder\\";
String filename;
String lineRead = "";
String fileContent = "";
try {
for(Object o : searchList.getSelectedValuesList()){
filename = o.toString();
FileReader reader = new FileReader(root + filename);
BufferedReader buffer = new BufferedReader(reader);
while(lineRead != null){
try {
lineRead = buffer.readLine();
} catch (IOException e1) {
e1.printStackTrace();
}
if(lineRead != null){
fileContent = fileContent + lineRead + "\r\n";
searchTextArea.setText(fileContent);
}
}
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
Also here's the picture to see how it works: picture

Related

Delete button stops working sporadically, only on Windows, when using our editor plugin

We are developing a markdown editor plugin for eclipse. My colleagues who are using Windows 10 encounter a bug that causes keys to stop working. The most common key is delete, other times it is ctrl + s.
Here is the code for the editor extension:
public class MarkdownEditor extends AbstractTextEditor {
private Activator activator;
private MarkdownRenderer markdownRenderer;
private IWebBrowser browser;
public MarkdownEditor() throws FileNotFoundException {
setSourceViewerConfiguration(new TextSourceViewerConfiguration());
setDocumentProvider(new TextFileDocumentProvider());
// Activator manages connections to the Workbench
activator = Activator.getDefault();
markdownRenderer = new MarkdownRenderer();
}
private IFile saveMarkdown(IEditorInput editorInput, IDocument document, IProgressMonitor progressMonitor) {
IProject project = getCurrentProject(editorInput);
String mdFileName = editorInput.getName();
String fileName = mdFileName.substring(0, mdFileName.lastIndexOf('.'));
String htmlFileName = fileName + ".html";
IFile file = project.getFile(htmlFileName);
String markdownString = "<!DOCTYPE html>\n" + "<html>" + "<head>\n" + "<meta charset=\"utf-8\">\n" + "<title>"
+ htmlFileName + "</title>\n" + "</head>" + "<body>" + markdownRenderer.render(document.get())
+ "</body>\n" + "</html>";
try {
if (!project.isOpen())
project.open(progressMonitor);
if (file.exists())
file.delete(true, progressMonitor);
if (!file.exists()) {
byte[] bytes = markdownString.getBytes();
InputStream source = new ByteArrayInputStream(bytes);
file.create(source, IResource.NONE, progressMonitor);
}
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
private void loadFileInBrowser(IFile file) {
IWorkbench workbench = PlatformUI.getWorkbench();
try {
if (browser == null)
browser = workbench.getBrowserSupport().createBrowser(Activator.PLUGIN_ID);
URL htmlFile = FileLocator.toFileURL(file.getLocationURI().toURL());
browser.openURL(htmlFile);
IWorkbenchPartSite site = this.getSite();
IWorkbenchPart part = site.getPart();
site.getPage().activate(part);
} catch (IOException | PartInitException e) {
e.printStackTrace();
}
}
#Override
public void init(IEditorSite site, IEditorInput editorInput) throws PartInitException {
super.init(site, editorInput);
IDocumentProvider documentProvider = getDocumentProvider();
IDocument document = documentProvider.getDocument(editorInput);
IFile htmlFile = saveMarkdown(editorInput, document, null);
loadFileInBrowser(htmlFile);
}
#Override
public void doSave(IProgressMonitor progressMonitor) {
IDocumentProvider documentProvider = getDocumentProvider();
if (documentProvider == null)
return;
IEditorInput editorInput = getEditorInput();
IDocument document = documentProvider.getDocument(editorInput);
if (documentProvider.isDeleted(getEditorInput())) {
if (isSaveAsAllowed()) {
/*
* 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors.
* Changed Behavior to make sure that if called inside a regular save (because
* of deletion of input element) there is a way to report back to the caller.
*/
performSaveAs(progressMonitor);
} else {
}
} else {
// Convert document from string to string array with each instance a single line
// of the document
String[] stringArrayOfDocument = document.get().split("\n");
String[] formattedLines = PipeTableFormat.preprocess(stringArrayOfDocument);
StringBuilder builder = new StringBuilder();
for (String line : formattedLines) {
builder.append(line);
builder.append("\n");
}
String formattedDocument = builder.toString();
// Calculating the position of the cursor
ISelectionProvider selectionProvider = this.getSelectionProvider();
ISelection selection = selectionProvider.getSelection();
int cursorLength = 0;
if (selection instanceof ITextSelection) {
ITextSelection textSelection = (ITextSelection) selection;
cursorLength = textSelection.getOffset(); // etc.
activator.log(Integer.toString(cursorLength));
}
// This sets the cursor on at the start of the file
document.set(formattedDocument);
// Move the cursor
this.setHighlightRange(cursorLength, 0, true);
IFile htmlFile = saveMarkdown(editorInput, document, progressMonitor);
loadFileInBrowser(htmlFile);
performSave(false, progressMonitor);
}
}
private IProject getCurrentProject(IEditorInput editorInput) {
IProject project = editorInput.getAdapter(IProject.class);
if (project == null) {
IResource resource = editorInput.getAdapter(IResource.class);
if (resource != null) {
project = resource.getProject();
}
}
return project;
}
}
Here is the repository: https://github.com/borisv13/GitHub-Flavored-Markdown-Eclipse-Plugin
Any help is accepted

When merging PDF files using itext the result pdf show 0 bytes in android studio

My code is here; I was selecting PDF files from a SD card or internal phone memory using the showFileChooser() method then from onActivityResult(), the files go to mergePdfFiles(View view) method, and from there the files go to createPdf(String[] srcs).
Here is the complete code of my activity:
//Below is onCreate();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mergedpdf);
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, locations);
// public void fileSelected(File file ) {
// locations.add(file.toString());
// adapter.notifyDataSetChanged();
// }
NewText = (TextView)findViewById(R.id.textView);
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
listView = (ListView)findViewById(R.id.list_items);
btn = (ImageView) findViewById(R.id.imageView8);
btnconvert = (ImageView) findViewById(R.id.imageView11);
btnconvert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// btTag=((Button)v).getTag().toString();
try {
createPdf( locations);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Toast.makeText(Mergedpdf.this, "button clicked", Toast.LENGTH_SHORT).show();
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// btTag=((Button)v).getTag().toString();
showFileChooser();
NewText.setText("Below Files are Selected");
}
});
}
//this is mergedfiles();
public void mergePdfFiles(View view){
Toast.makeText(Mergedpdf.this, "merge function", Toast.LENGTH_SHORT).show();
try {String[] srcs= new String[locations.size()];
for(int i = 0;i<locations.size();i++) {
srcs[i] = locations.get(i);
}
// String[] srcs = {txt1.getText().toString(), txt2.getText().toString()};
createPdf(srcs);
}catch (Exception e){e.printStackTrace();}
}
//This method create merged pdf file
public void createPdf (String[] srcs) {
try {
// Create document object
File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Merged-PDFFiles");
if (!docsFolder.exists()) {
docsFolder.mkdir();
Log.i(TAG, "Created a new directory for PDF");
}
Date date = new Date();
#SuppressLint("SimpleDateFormat") final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date);
Document document = new Document();
// pdfCopy = new File(docsFolder.getAbsolutePath(),pdf+"Images.pdf");
// Document document = new Document();
//PdfWriter.getInstance(document, output);
// Create pdf copy object to copy current document to the output mergedresult file
PdfCopy copy = new PdfCopy(document, new FileOutputStream(docsFolder + "/" + timeStamp +"combine.pdf"));
Toast.makeText(Mergedpdf.this, "merged pdf saved", Toast.LENGTH_SHORT).show();
// Open the document
document.open();
PdfReader pr;
int n;
for (int i = 0; i < srcs.length; i++) {
// Create pdf reader object to read each input pdf file
pr = new PdfReader(srcs[i].toString());
// Get the number of pages of the pdf file
n = pr.getNumberOfPages();
for (int page = 1; page <= n; page++) {
// Import all pages from the file to PdfCopy
copy.addPage(copy.getImportedPage(pr, page));
}
}
document.close(); // close the document
} catch (Exception e) {
e.printStackTrace();
}
}
//below is showfilechooser(); method
private void showFileChooser () {
Log.e("AA", "bttag=" + btTag);
String folderPath = Environment.getExternalStorageDirectory() + "/";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
Uri myUri = Uri.parse(folderPath);
intent.setDataAndType(myUri, "application/pdf");
Intent intentChooser = Intent.createChooser(intent, "Select a file");
startActivityForResult(intentChooser,PICKFILE_RESULT_CODE);
}
//below is onActivityResult(); method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
if (requestCode == PICKFILE_RESULT_CODE) {
if (resultCode == RESULT_OK) {
String FilePath = data.getData().getPath();
locations.add(FilePath);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.listview,locations);
listView.setAdapter(adapter);
}
}
}
}
//And my declared variables before oncreate().
public com.itextpdf.text.Document Document;
public PdfCopy Copy;
public ByteArrayOutputStream ms;
TextView NewText;
private TextView txt1;
private Button bt1, bt2,bt3;
private Handler handler;
ListView listView;
ArrayList<String> locations = new ArrayList<>();
ArrayAdapter<String> adapter;
ImageView btn, btnconvert, btn3;
private static final String TAG = "PdfCreator";
private final int PICKFILE_RESULT_CODE=10;
private String btTag = "";

Add a Bitmap image in a PDF document in Android

please, how can i directly pass a bitmap image to a pdf file. I have made a graph with GraphView and at the end i convert it to Bitmap, inside an OnClickListener:
write.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
Bitmap bitmap;
graph.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(graph.getDrawingCache());
graph.setDrawingCacheEnabled(false);
String filename = "imagen";
FileOperations fop = new FileOperations();
fop.write(filename, bitmap);
if (fop.write(filename,bitmap)) {
Toast.makeText(getApplicationContext(),
filename + ".pdf created", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(getApplicationContext(), "I/O error",
Toast.LENGTH_SHORT).show();
}
}
});
The problem is that in the class FileOperations:
public FileOperations() {
}
public Boolean write(String fname, Bitmap bm) {
try {
String fpath = "/sdcard/" + fname + ".pdf";
File file = new File(fpath);
if (!file.exists()) {
file.createNewFile();
}
Document document = new Document();
PdfWriter.getInstance(document,
new FileOutputStream(file.getAbsoluteFile()));
document.open();
String filename = bm.toString();
com.itextpdf.text.Image image =com.itextpdf.text.Image.getInstance(filename);
document.add(image);
document.add(new Paragraph("Hello World2!"));
// step 5
document.close();
Log.d("Suceess", "Sucess");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
}
I want to know how can i pass the bitmap Image to add it in the pdf document, i do this but i think this works only when i give it a path.
String filename = bm.toString();
com.itextpdf.text.Image image =com.itextpdf.text.Image.getInstance(filename);
I just solve it:
document.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
document.add(myImg);
in the FileOperations class

Adding new revision for document in DropBox through android api

I want to add a new revision to the document(Test.doc) in Dropbox using android api. Can anyone share me any sample code or links. I tried
FileInputStream inputStream = null;
try {
DropboxInputStream temp = mDBApi.getFileStream("/Test.doc", null);
String revision = temp.getFileInfo().getMetadata().rev;
Log.d("REVISION : ",revision);
File file = new File("/sdcard0/renamed.doc");
inputStream = new FileInputStream(file);
Entry newEntry = mDBApi.putFile("/Test.doc", inputStream, file.length(), revision, new ProgressListener() {
#Override
public void onProgress(long arg0, long arg1) {
Log.d("","Uploading.. "+arg0+", Total : "+arg1);
}
});
} catch (Exception e) {
System.out.println("Something went wrong: " + e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {}
}
}
New revision is created for first time. When i execute again, another new revision is not getting created.

excel file upload using apache file upload

I am developing an testing automation tool in linux system. I dont have write permissions for tomcat directory which is located on server. I need to develop an application where we can select an excel file so that the excel content is automatically stored in already existing table.
For this pupose i have written an form to select an file which is posted to a servlet CommonsFileUploadServlet where i am storing the uploaded file and then calling ReadExcelFile class which reads the file path and create a vector for data in file which is used to sstore data in database.
My problem is that i am not able to store the uploaded file in directory. Is it necessary to have permission rights for tomcat to do this. Can i store the file on my system and pass the path to ReadExcelFile.class
Please guide me
My code is as follows:
Form in jsp
CommonsFileUploadServlet class code:
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory ();
fileItemFactory.setSizeThreshold(1*1024*1024);
fileItemFactory.setRepository(new File("/home/example/Documents/Project/WEB-INF/tmp"));
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while(itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if(item.isFormField()) {
out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
} else {
out.println("Field Name = "+item.getFieldName()+
", File Name = "+item.getName()+
", Content type = "+item.getContentType()+
", File Size = "+item.getSize());
File file = new File("/",item.getName());
String realPath = getServletContext().getRealPath("/")+"/"+item.getName();
item.write(file);
ReadExcelFile ref= new ReadExcelFile();
String res=ref.insertReq(realPath,"1");
}
out.close();
}
}catch(FileUploadException ex) {
log("Error encountered while parsing the request",ex);
} catch(Exception ex) {
log("Error encountered while uploading file",ex);
}
}
}
ReadExcelFile code:
public static String insertReq(String fileName,String sno) {
//Read an Excel File and Store in a Vector
Vector dataHolder=readExcelFile(fileName,sno);
//store the data to database
storeCellDataToDatabase(dataHolder);
}
public static Vector readExcelFile(String fileName,String Sno)
{
/** --Define a Vector
--Holds Vectors Of Cells
*/
Vector cellVectorHolder = new Vector();
try{
/** Creating Input Stream**/
//InputStream myInput= ReadExcelFile.class.getResourceAsStream( fileName );
FileInputStream myInput = new FileInputStream(fileName);
/** Create a POIFSFileSystem object**/
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
/** Create a workbook using the File System**/
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
int s=Integer.valueOf(Sno);
/** Get the first sheet from workbook**/
HSSFSheet mySheet = myWorkBook.getSheetAt(s);
/** We now need something to iterate through the cells.**/
Iterator rowIter = mySheet.rowIterator();
while(rowIter.hasNext())
{
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
Vector cellStoreVector=new Vector();
short minColIndex = myRow.getFirstCellNum();
short maxColIndex = myRow.getLastCellNum();
for(short colIndex = minColIndex; colIndex < maxColIndex; colIndex++)
{
HSSFCell myCell = myRow.getCell(colIndex);
if(myCell == null)
{
cellStoreVector.addElement(myCell);
}
else
{
cellStoreVector.addElement(myCell);
}
}
cellVectorHolder.addElement(cellStoreVector);
}
}catch (Exception e){e.printStackTrace(); }
return cellVectorHolder;
}
private static void storeCellDataToDatabase(Vector dataHolder)
{
Connection conn;
Statement stmt;
String query;
try
{
// get connection and declare statement
int z;
for (int i=1;i<dataHolder.size(); i++)
{
z=0;
Vector cellStoreVector=(Vector)dataHolder.elementAt(i);
String []stringCellValue=new String[10];
for (int j=0; j < cellStoreVector.size();j++,z++)
{
HSSFCell myCell = (HSSFCell)cellStoreVector.elementAt(j);
if(myCell==null)
stringCellValue[z]=" ";
else
stringCellValue[z] = myCell.toString();
}
try
{
//inserting into database
}
catch(Exception error)
{
String e="Error"+error;
System.out.println(e);
}
}
stmt.close();
conn.close();
System.out.println("success");
}
catch(Exception error)
{
String e="Error"+error;
System.out.println(e);
}
}
POI will happily open from an old InputStream, it needn't be a File one.
I'd suggest you look at the Commons FileUpload Streaming API and consider just passing the excel part straight to POI without touching the disk