I'm new around here even though I am have been looking at these forums for ages and I finally need a bit of help;
I have tried this;
FileResource file = new FileResource(new File("/a/d/r/e/s/s/file"));
TextArea text = new TextArea();
text.setValue(file);
This;
FileResource file = new FileResource(new File("/a/d/r/e/s/s/file"));
TextArea text = new TextArea();
text.setValue(file.toString());
And;
FileResource file = new FileResource(new File("/a/d/r/e/s/s/file"));
TextArea text = new TextArea();
text.setValue(file.getAbosoluteFile().toString());
And others which are to big to show;
How do I show the file
The easiest way would be to use the TextFileProperty:
TextArea text = new TextArea(new TextFileProperty(new File("/a/d/r/e/s/s/file")));
or the longer form:
TextArea text = new TextArea();
text.setPropertyDataSource(new TextFileProperty(new File("/a/d/r/e/s/s/file")));
What this piece of code does is it binds your Field TextArea to a Property. This is Vaadin's data binding mechanism. Property and Field synchronize each other automatically.
If you just want to display the file without editing it, consider using a Vaadin Label instead of the TextArea.
final TextArea textField = new TextArea();
textField.setSizeFull();
this.addComponent(textField);
try {
final File file = new File("/path/to/file");
final String fileAsString = FileUtils.readFileToString(file);
textField.setValue(fileAsString);
} catch (IOException e) {
e.printStackTrace();
}
You will need to have the IO component from Apache Commons available to be able to import FileUtils
Using the java standard library + java 8 streams
TextArea text = new TextArea();
String value = Files.readAllLines(Paths.get(file)).stream().collect(Collectors.joining())
text.setValue(value);
In Java 7 you can use the readAllLines function iterating over the List generated, in case that the size of the file is really big,follow a different approach, as the one that is explained here http://www.baeldung.com/java-read-lines-large-file
Related
I am working on a Java Swing project and I am trying to understand how to use JTable.
I have a text file with a list of user information which is all separated by a comma without spaces. I am trying to get this information to be displayed in a table, however, when I run the form the table, it remains blank and never shows anything.
Here is my code:
private JTable listUsersTable;
// ...
String[] columnNames = {"USERNAME", "NAME", "SURNAME", "AGE", "SEX", "SITE"};
// Creates a table with the column names and zero rows.
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
try {
BufferedReader reader = new BufferedReader(new FileReader("userArchive.txt"));
// Reads each line in the file "userArchive.txt", separates the data, and puts them into the table.
String line = reader.readLine();
while (line != null) {
String[] lineSplit = line.split(",");
model.addRow(lineSplit);
line = reader.readLine(); // Goes to the next line in the file.
}
reader.close();
listUsersTable = new JTable(model);
} catch (FileNotFoundException e5) {
e5.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
And here is my current JTable layout & settings using intelliJ's GUI designer:
Image of my intelliJ GUI designer setup and the JTable in question.
(The JTable in the image is called verUsuariosTable however in the code this is called listUsersTable. This is because I am writing my code in Spanish but translating everything to ask the question).
I needed to include JScrollPane to the code. This link shows completely what is needed to work with text files and JTables. (How do I read separate parts from a txt File to show in Java GUI?).
I needed to add
listUsersTable.setPreferredScrollableViewportSize(listUsersTable.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(listUsersTable);
and then add the scrollPane to the panel I was working with using
currentPanel.add(scrollPane);
How is it possible to position text in an SWT Shell?
My problem is that I don't know which Layout to use. I've tried Row and Fill-Layout, but this won't work if I do it like text.setLocation(x,y).
Can anyone help me?
Solved it.
If you use no Layout, put the elements you want in a SWT Group, you can position it free inside this group.
Group group = new Group(parent, SWT.NONE);
Text text = new Text(group, SWT.BORDER);
group.setSize(parent.getSize());
text.setLocation(parent.getSize().x/2, parent.getSize().y/2);
Will look like this:
Might be worth taking a look at FormLayout. Would go something like:
Group group = new Group(parent, SWT.NONE);
group.setLayout(new FormLayout());
Text text = new Text(group, SWT.BORDER);
text.setText("Text1");
FormData fd = new FormData();
fd.top = new FormAttachment(50,0);
fd.left = new FormAttachment(50,0);
text.setLayoutData(fd);
The FormAttachment class lets you specify both a percentage of the container width (50% in this case), and also a fixed offset(0).
When you setContentType("text/html") it is applied only for the text that is set via JTextPane.setText(). All other text, that is put to the JTextPane via styles is "immune" to content type.
Here is what I mean:
private final String[] messages = {"first msg", "second msg <img src=\"file:src/test/2.png\"/> yeah", "<img src=\"file:src/test/2.png\"/> third msg"};
public TestGUI() throws BadLocationException {
JTextPane textPane = new JTextPane();
textPane.setEditable(false);
textPane.setContentType("text/html");
//Read all the messages
StringBuilder text = new StringBuilder();
for (String msg : messages) {
textext.append(msg).append("<br/>");
}
textPane.setText(text.toString());
//Add new message
StyledDocument styleDoc = textPane.getStyledDocument();
styleDoc.insertString(styleDoc.getLength(), messages[1], null);
JScrollPane scrollPane = new JScrollPane(textPane, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//add scrollPane to the main window and launch
//...
}
In general, I have a chat that is represented by JTextPane. I receive messages from server, process them - set text color for specific cases, change smile markers to images path etc. everything is made within the bounds of HTML. But as it can be clearly seen from example above, only the setText is the subject of setContentType("text/html") and the second part, where new message added is represented by "text/plain" (if I'm not mistaken).
Is it possible to apply "text/html" content type to all data that is inserted to JTextPane? Without it, it is almost impossible to process messages without implemention of very complex algorithm.
I don't think you should be using the insertString() method to add text. I think you should be using something like:
JTextPane textPane = new JTextPane();
textPane.setContentType( "text/html" );
textPane.setEditable(false);
HTMLDocument doc = (HTMLDocument)textPane.getDocument();
HTMLEditorKit editorKit = (HTMLEditorKit)textPane.getEditorKit();
String text = "hyperlink";
editorKit.insertHTML(doc, doc.getLength(), text, 0, 0, null);
REEDIT
Sorry, I misunderstood the problem: inserting a string as HTML.
For that one needs to resort to the HTMLEditorKit capabilities:
StyledDocument styleDoc = textPane.getStyledDocument();
HTMLDocument doc = (HTMLDocument)styleDoc;
Element last = doc.getParagraphElement(doc.getLength());
try {
doc.insertBeforeEnd(last, messages[1] + "<br>");
} catch (BadLocationException ex) {
} catch (IOException ex) {
}
Here is a much simpler way to do that.
JTextPane pane = new JTextPane();
pane.setContentType("text/html");
pane.setText("<html><h1>My First Heading</h1><p>My first paragraph.</p></body></html>");
I am new to Java and would like to know how to set the font and font color to be used for the next text to be added to a SWT StyledText box.
So for example I have an application that defines "command" and "data" text and each is to be displayed in a different font/color. So let's say I've just added some "command" text. Now how do I set things up so that the next text which will be "data" text is displayed in a different font and color?
I've done a lot of googling, but nothing seems to be helping me.
P.S.: This can't be the most efficient way to do it:
int a = st.getCharCount();
Font font = new Font(shlProtruleModifier.getDisplay(), "Courier", 10, SWT.NORMAL);
StyleRange[] sr = new StyleRange[1];
sr[0] = new StyleRange();
st.append("\r\nWhat the heck?");
sr[0].start = a;
sr[0].length = st.getCharCount() - a;
sr[0].font = font;
sr[0].foreground = SWTResourceManager.getColor(SWT.COLOR_BLACK);
st.replaceStyleRanges(sr[0].start, sr[0].length, sr);
So all I've been able to come up with the following technique that does work,
int a = st.getCharCount();
Font font = new Font(shlProtruleModifier.getDisplay(), "Courier", 10, SWT.NORMAL);
StyleRange[] sr = new StyleRange[1];
sr[0] = new StyleRange();
st.append("\r\nWhat the heck?");
sr[0].start = a;
sr[0].length = st.getCharCount() - a;
sr[0].font = font;
sr[0].foreground = SWTResourceManager.getColor(SWT.COLOR_BLACK);
st.replaceStyleRanges(sr[0].start, sr[0].length, sr);
I am making editor. I am using following code to add html document from a path to texteditor.
try {
filename="filepath";
StringBuffer fileData = new StringBuffer(1000);
BufferedReader reader = new BufferedReader(new FileReader(filename));
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
result = fileData.toString();
jtextpane.setContentType("text/html");
jtextpane.setText(result);
} catch (Exception ex) {
jtextpane.setText(".,1..."+ex.toString());
}
Till the time when i m not using this file to load at first time my editor is working fine. But after adding this code my paste button is not working properly.It is pasting in new line. when i am removing "SETCONTENTTYPE" in that scenario the paste is working well.but i can't remove it.I have to load html file into editor. Please help.
Thank You in advance.
If you want "open" the html document in your text editor, you should use a JEditorPane combined (if it's necessary) which a JScrollPane. Here's an example code (It needs try/catch blocks):
private void visualiserLog() {
JEditorPane docEP = new JEditorPane();
docEP.setEditable(true);
File f = new File(/path/to/file.html);
java.net.URL fileURL = null;
try {
fileURL = f.toURI().toURL(); // Transform path into URL
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
docEP.setPage(fileURL); // Load the file to the editor
}
catch (IOException e) {
e.printStackTrace();
}
// Initialize scroll pane (if you need it)
JScrollPane docSP = new JScrollPane(docEP,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
docSP.setPreferredSize(new Dimension(800,700));
// Set up a frame to layout the editor panel
JFrame frame = new JFrame("HTML File");
frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.setBounds(0,0,800,700);
// If you don't use ScrollPane, you must swap docSP for docEP
frame.getContentPane().add(docSP,BorderLayout.CENTER);
frame.setVisible(true);
}
I think that can works properly to set the file into the editor. After that you should put the copy function and the necessary listeners.
Regards!