my dog learned polymorphism*
The moose likes Swing / AWT / SWT and the fly likes display contents of a text file in a new window Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "display contents of a text file in a new window" Watch "display contents of a text file in a new window" New topic
Author

display contents of a text file in a new window

Gopu Akraju
Ranch Hand

Joined: Jan 13, 2008
Posts: 242
I am trying to display teh contents of a text file in a new window? Can anyone please suggest on htis?
Sandeep Mukherji
Ranch Hand

Joined: Mar 23, 2008
Posts: 46
try this, this may help you.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

class NotePad
{
JFrame mainFrame;
JMenuBar menuBar;
JMenu file, edit, format, view, help;
JMenuItem finew, open, save, saveAs, pageSetup, print, exit;
JMenuItem undo, cut, copy, paste, delete, find, findNext, replace, goTo, selectAll, timeDate;
JMenuItem wordRap, font;
JMenuItem statusBar;
JMenuItem helpTopics, aboutSandeepsNotepad;
JScrollPane scrollPane;
JTextArea textArea;
JFileChooser fileChooser;
File f;
NotePad(String s)
{
mainFrame = new JFrame(s+" - Notepad");
menuBar = new JMenuBar();
file = new JMenu("File");
edit = new JMenu("Edit");
format = new JMenu("Format");
view = new JMenu("View");
help = new JMenu("Help");
finew = new JMenuItem("New");
open = new JMenuItem("Open...");
save = new JMenuItem("Save");
saveAs = new JMenuItem("Save As...");
pageSetup = new JMenuItem("Page Setup...");
print = new JMenuItem("Print...");
exit = new JMenuItem("Exit");
undo = new JMenuItem("Undo");
cut = new JMenuItem("Cut");
copy = new JMenuItem("Copy");
paste = new JMenuItem("Paste");
delete = new JMenuItem("Delete");
find = new JMenuItem("Find...");
findNext = new JMenuItem("Find Next");
replace = new JMenuItem("Replace...");
goTo = new JMenuItem("Go To...");
selectAll = new JMenuItem("Select All");
timeDate = new JMenuItem("Time//Date");
wordRap = new JMenuItem("Word Wrap");
font = new JMenuItem("Font...");
statusBar = new JMenuItem("Status Bar");
helpTopics = new JMenuItem("Help Topics");
aboutSandeepsNotepad = new JMenuItem("About Sandeeps Notepad");
textArea = new JTextArea();
scrollPane = new JScrollPane(textArea);
f = new File("C://Program Files//Java//jdk1.6.0//bin//");
fileChooser = new JFileChooser(f);
file.add(finew);
file.add(open);
file.add(save);
file.add(saveAs);
file.addSeparator();
file.add(pageSetup);
file.add(print);
file.addSeparator();
file.add(exit);
edit.add(undo);
edit.addSeparator();
edit.add(cut);
edit.add(copy);
edit.add(paste);
edit.add(delete);
edit.addSeparator();
edit.add(find);
edit.add(findNext);
edit.add(replace);
edit.add(goTo);
edit.addSeparator();
edit.add(selectAll);
edit.add(timeDate);
menuBar.add(file);
menuBar.add(edit);
menuBar.add(format);
menuBar.add(view);
menuBar.add(help);
format.add(wordRap);
format.add(font);
view.add(statusBar);
help.add(helpTopics);
help.addSeparator();
help.add(aboutSandeepsNotepad);
mainFrame.add(menuBar,BorderLayout.NORTH);
mainFrame.add(scrollPane, BorderLayout.CENTER);
mainFrame.setSize(760,540);
mainFrame.setVisible(true);
Open op = new Open(this);
open.addActionListener(op);
Save sa = new Save(this);
save.addActionListener(sa);
SaveAs saas = new SaveAs(this);
saveAs.addActionListener(saas);
Exit ex = new Exit(this);
exit.addActionListener(ex);
}
public static void main(String[] args)
{
new NotePad("Untitled");
}
}

class Open implements ActionListener
{
NotePad op;
Open(NotePad op)
{
this.op = op;
}
public void actionPerformed(ActionEvent e)
{
int returnVal = op.fileChooser.showOpenDialog(op.mainFrame);
try
{
File file = op.fileChooser.getSelectedFile();
FileInputStream fin = new FileInputStream(file);
DataInputStream din = new DataInputStream(fin);
String s = "";
if (returnVal == op.fileChooser.APPROVE_OPTION)
{
while(s != null)
{
s = din.readLine();
System.out.println(s);
op.textArea.append(s+"\n");
//ba.textArea.setText(s);
}
}
else if(returnVal != op.fileChooser.APPROVE_OPTION)
{
System.out.println("Saving Canceled");
}
System.out.println("returnVal = "+returnVal+" and ba.fileChooser.APPROVE_OPTION = "+op.fileChooser.APPROVE_OPTION);
fin.close();
}
catch (Exception ex)
{
}
}
}

class Save implements ActionListener
{
NotePad sa;
Save(NotePad sa)
{
this.sa = sa;
}
public void actionPerformed(ActionEvent e)
{
int returnVal = sa.fileChooser.showSaveDialog(sa.mainFrame);
try
{
File file = sa.fileChooser.getSelectedFile();
String name = file.toString();
FileOutputStream fout = new FileOutputStream(name, false);
if (returnVal == sa.fileChooser.APPROVE_OPTION)
{
fout.write(("________________________________________HEADER______________________________________________\n").getBytes());
fout.write(("\""+sa.f.getPath()+"\" is "+String.valueOf((sa.f.isFile())?"":"not")+" a file, ").getBytes());
fout.write(("but is "+String.valueOf((sa.f.isDirectory())?"":"not")+" a directory. ").getBytes());
fout.write(("And is last modified at: "+String.valueOf(sa.f.lastModified())).getBytes());
fout.write(("\n______________________________________ CONTENT ______________________________________________\n").getBytes());
fout.write(("\n"+sa.textArea.getText()).getBytes());
}
else if(returnVal != sa.fileChooser.APPROVE_OPTION)
{
System.out.println("Saving Canceled");
}
System.out.println("returnVal = "+returnVal+" and ba.fileChooser.APPROVE_OPTION = "+sa.fileChooser.APPROVE_OPTION);
fout.close();
}
catch (Exception ex)
{
}
}
}
class SaveAs implements ActionListener
{
NotePad saas;
SaveAs(NotePad saas)
{
this.saas = saas;
}
public void actionPerformed(ActionEvent e)
{
int returnVal = saas.fileChooser.showDialog(saas.mainFrame, "Save As...");
try
{
File file = saas.fileChooser.getSelectedFile();
String name = file.toString();
FileOutputStream fout = new FileOutputStream(name, true);
if (returnVal == saas.fileChooser.APPROVE_OPTION)
{
fout.write(("________________________________________HEADER______________________________________________\n").getBytes());
fout.write(("\""+saas.f.getPath()+"\" is "+String.valueOf((saas.f.isFile())?"":"not")+" a file, ").getBytes());
fout.write(("but is "+String.valueOf((saas.f.isDirectory())?"":"not")+" a directory. ").getBytes());
fout.write(("And is last modified at: "+String.valueOf(saas.f.lastModified())).getBytes());
fout.write(("\n______________________________________ CONTENT ______________________________________________\n").getBytes());
fout.write(("\n"+saas.textArea.getText()).getBytes());
}
else if(returnVal != saas.fileChooser.APPROVE_OPTION)
{
System.out.println("Saving Canceled");
}
System.out.println("returnVal = "+returnVal+" and ba.fileChooser.APPROVE_OPTION = "+saas.fileChooser.APPROVE_OPTION);
fout.close();
}
catch (Exception ex)
{
}
}
}
class Exit implements ActionListener
{
NotePad ex;
Exit(NotePad ex)
{
this.ex = ex;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == ex.exit)
{
System.exit(0);
}
}
}
Gopu Akraju
Ranch Hand

Joined: Jan 13, 2008
Posts: 242
THANKS. It is just for the display. I don't want the user to edit the file. Infact I just want to display a the contents of a text file in a non-editable way, in a new window. After viewing, the user can close the window.
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42274
    
  64
You can use the setEditable method to make a text field/area read-only.

catch (Exception ex)
{
}

This is bad practice, by the way. If you aren't handling an exception, at least print it to a log file or the console, so that users and developers have a chance of knowing that something's wrong.


Ping & DNS - my free Android networking tools app
Gopu Akraju
Ranch Hand

Joined: Jan 13, 2008
Posts: 242
Thanks. My objective is when I click on a button in my main frame/window, I want to open a new window and display the user a text file in the non editable way. Do I have to do with JTable or JTextfield? How do I proceed to achieve this?
[ April 18, 2008: Message edited by: Gopu Akraju ]
Brian Cole
Author
Ranch Hand

Joined: Sep 20, 2005
Posts: 862
Originally posted by Gopu Akraju:
My objective is when I click on a button in my main frame/window, I want to open a new window and display the user a text file in the non editable way.


You can do this in just a few lines of code.



bitguru blog
Gopu Akraju
Ranch Hand

Joined: Jan 13, 2008
Posts: 242
Thanks Brian, Is there anyway to make sure that the contents of the file are displayed completely inside JOption.showMessageDialog(yourButton, new JScrollPane(ta));

Right now the size of ta cuts the visiblity of the contents as I am setting the size of text area. Thanks.
Willy Ray
Greenhorn

Joined: May 04, 2008
Posts: 11
I'm having the same problem. I have a long piece of text in a textArea in a ScrollPane, and the whole deal is getting sized larger than the frame. No scroll bar, and I'm missing content out the bottom.

/w
Brian Cole
Author
Ranch Hand

Joined: Sep 20, 2005
Posts: 862
Originally posted by Gopu Akraju:
Thanks Brian, Is there anyway to make sure that the contents of the file are displayed completely inside JOption.showMessageDialog(yourButton, new JScrollPane(ta));

Right now the size of ta cuts the visiblity of the contents as I am setting the size of text area. Thanks.


The reason I threw the 20, 60 in there was to prevent the JTextArea
showing up too big. If you want you can omit (or change the values)
for a larger text area within the scroll pane.

But in general, there is no way to "make sure that the contents of the
file are displayed completely." If the file contains the entire text of
Huckleberry Finn, for example, how could we expect it all to show?


Originally posted by Willy Ray:
I'm having the same problem. I have a long piece of text in a textArea in a ScrollPane, and the whole deal is getting sized larger than the frame. No scroll bar, and I'm missing content out the bottom.


This sounds like the opposite problem, unless I'm reading things wrong.

I can see how text would be pushed off past the right and bottom borders
of the dialog, but I don't see how the scroll bars wouldn't show. Can you
show some code?
[ May 05, 2008: Message edited by: Brian Cole ]
Gopu Akraju
Ranch Hand

Joined: Jan 13, 2008
Posts: 242
I get the horizontal bar but visibility is complete (i.e) I don't see the entire line. I can go for setLineWrap but as I am viewing a log file, it doesn't look nice. And gain as this is a log file, it grows and my textarea should be able to handle the situation.

The code is as below:


The size of the file is around 35kb. IS this method ok to display the contents or any other method recommended. When I try to open this file, I am able to see only the last line of the text file. How to rectify this problem? Thanks.

[ May 06, 2008: Message edited by: Gopu Akraju ]
[ May 06, 2008: Message edited by: Gopu Akraju ]
Gopu Akraju
Ranch Hand

Joined: Jan 13, 2008
Posts: 242
If I increase the size of textarea to I am ble to see the file contents but not getting the horizontal and vertical bar. Why does it behave like this?
Gopu Akraju
Ranch Hand

Joined: Jan 13, 2008
Posts: 242
Hi I managed to fix this problem, by fixing the size of textarea as I am not sure whether this is the correct way to deal this problem. I get both horizontal and vertical bar now.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19718
    
  20

Unless you specify different scrollbar policies, the scrollbars will only appear if needed. If the component is small enough there is no need for the scrollbars and hence they will not show.

Look at the JScrollPane constructors about setting the policies.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Gopu Akraju
Ranch Hand

Joined: Jan 13, 2008
Posts: 242
Is this the only way to display the contents of a file in a new window? What ever the file size is, will this method display?
[ May 06, 2008: Message edited by: Gopu Akraju ]
Brian Cole
Author
Ranch Hand

Joined: Sep 20, 2005
Posts: 862
Originally posted by Gopu Akraju:
And gain as this is a log file, it grows and my textarea should be able to handle the situation.


The code we have been discussing simply displays the "snapshot" contents of a file
on screen. If you want the display on the screen to then update when the contents
of the file changes, that's a separate issue.


JScrollPane jsp = ...

jsp.getViewport().add(ta);


I originally thought this was suspect but, on further review, I guess it's ok. Still, the
normal way to do this is jsp.setViewportView(ta) or jsp.getViewport().setView(ta).

When I try to open this file, I am able to see only the last line of the text file. How to rectify this problem?


I don't understand why this would be. Some methods of reading a file into a text area
do result in the bottom of the file being shown [in which case scrollRectToVisible() can
be handy], but not the method of my code above.

[update: Ah, I see you are calling ta.append() in a loop instead of calling ta.read().
In that case ta.scrollRectToVisible(new Rectangle(0, 0, 1, 1)) may indeed be useful.]
[ May 06, 2008: Message edited by: Brian Cole ]
Willy Ray
Greenhorn

Joined: May 04, 2008
Posts: 11
Originally posted by Brian Cole:


This sounds like the opposite problem, unless I'm reading things wrong.

I can see how text would be pushed off past the right and bottom borders
of the dialog, but I don't see how the scroll bars wouldn't show. Can you
show some code?

[ May 05, 2008: Message edited by: Brian Cole ]


Yeah, my code that's got this issue is too big to post... I'll see if I can abstract out an example of what I'm talking about. Basically, I have two textAreas, one that's got a block of "Original" text in it, and another that's got machine-processed text in it (removing Protected Health Information, names, SSNs, etc.) and I need to scroll the TOGETHER so that they can be visually compared. So, I have 2 JTextFields in a JPanel in a JScrollPane. The JTextFields seem to re-size to the full length of the text content when I load it, and the JPanel and JScrollPane seem to resize right along with, but the outer JFrame does not. So... no scroll bar because the ScrollPane is big enough, but all the content runs out the bottom of the frame. Maybe this issue is different enough from the current topic I should make a new thread once I get a concise-enough working example?

/w
Brian Cole
Author
Ranch Hand

Joined: Sep 20, 2005
Posts: 862
Originally posted by Willy Ray:
I have two textAreas, one that's got a block of "Original" text in it, and another that's got machine-processed text in it (removing Protected Health Information, names, SSNs, etc.) and I need to scroll the TOGETHER so that they can be visually compared.


See this other thread for some information on locked scrolling.

So, I have 2 JTextFields in a JPanel in a JScrollPane. The JTextFields seem to re-size to the full length of the text content when I load it, and the JPanel and JScrollPane seem to resize right along with, but the outer JFrame does not. So... no scroll bar because the ScrollPane is big enough, but all the content runs out the bottom of the frame. Maybe this issue is different enough from the current topic I should make a new thread once I get a concise-enough working example?


It sounds like you need a better layout manager for the frame's content pane.
Willy Ray
Greenhorn

Joined: May 04, 2008
Posts: 11
Originally posted by Brian Cole:

See this other thread for some information on locked scrolling.


That did it! Thank you!

/w
//threadjack
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: display contents of a text file in a new window