How to set JavaFX TextField to wrap text inside field - java

I need hlep with figuring out how to wrap the text in the JavaFX TextField object.
So my code gets a file name from the user, opens the file by pasting the contents of the text file into the text field. Then the user can edit the text and save it into the same file.
My code does all of the above so that's not what I need help with. The JavaFX TextField object does not seem to have a way to wrap the text in the text box. It ends up looking like this:
Alt Image Link: https://drive.google.com/open?id=1q2yU5ox6WA5EwS3YSxaKoqUDpCxpbPmu
I want to wrap the text for obvious reasons. Below is my code (minus the import statements)
public class TextEditor extends Application
{
private Button button = new Button();
private TextField text = new TextField();
private Label label = new Label("Enter filename:");
private String filename = "";
String filetext = "";
Scanner file = new Scanner("");
PrintWriter pw = null;
FileOutputStream fos = null;
#Override
public void start(Stage primaryStage) throws Exception
{
GridPane myPane = new GridPane();
myPane.setHgap(10);
myPane.setVgap(10);
Scene myScene = new Scene(myPane, 500, 500);
primaryStage.setScene(myScene);
primaryStage.show();
primaryStage.setTitle("Find File");
myPane.setAlignment(Pos.BASELINE_CENTER);
label.setAlignment(Pos.BASELINE_CENTER);
myPane.add(label, 0, 0, 3, 1);
text.setAlignment(Pos.TOP_LEFT);
text.setPrefWidth(480);
text.setPrefHeight(400);
myPane.add(text, 0, 1);
button = new Button("Submit Filename");
button.setPrefSize(180, 50);
button.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
if(button.getText().equals("Save Changes"))
{
try
{
fos = new FileOutputStream(filename);
pw = new PrintWriter(fos);
System.out.println("Saving changes in " + filename);
pw.println(text.getText());
pw.close();
primaryStage.close();
}
catch (FileNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(button.getText().equals("Submit Filename"))
{
filename = text.getText();
try
{
file = new Scanner(new FileInputStream(new File(filename)));
while(file.hasNextLine())
{
String line = file.nextLine();
System.out.println(line);
filetext += line + "\n";
}
System.out.println("File text: " + filetext);
text.setText(filetext);
button.setText("Save Changes");
}
catch(FileNotFoundException exc)
{
System.out.println("Cannot find file. Program aborted.");
primaryStage.close();
}
}
}
});
myPane.add(button, 0, 2);
}
public static void main(String[] args)
{
Application.launch(args);
}
}
Would love some assistance getting the text to wrap. Do I need to not use a JavaFX TextField? Should I use something else?
Thanks in advance!
EDIT
SOLUTION FOUND
I changed the TextField text to a TextArea, removed the text.setAlignment(Pos.TOP_LEFT) line and added a text.setWrapText(true) (as suggested below) and now the program works great. Thanks Fabian and Zephyr!

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()

Java Swing remember password

I want to make a user/pass an a checkButton to keep the user and pass. So, first time when I open the app and put the pass and user and select the rememberBox to save this check and after I will open again to remain check and the pass and user to be written already.
This is the code:
JButton btnLogin = new JButton("Login");
Image ok = new ImageIcon(this.getClass().getResource("/Ok.png")).getImage();
btnLogin.setIcon(new ImageIcon(ok));
btnLogin.addActionListener(new ActionListener() {
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent arg0) {
String user = "marius";
String password = "Amina1";
UPDATE();
if(userName.getText().equals(user) && passwordField.getText().equals(password)){
if(checkBox.isSelected()){
SAVE(); //Save This UserName and his PassWord
}
window.frmUserpass.dispose();
WelcomePage welcomePage = new WelcomePage();
welcomePage.Screen1();
}else {
JOptionPane.showMessageDialog(btnLogin, "Introduceti unuser si o parola valida!", "Error", 0);
passwordField.selectAll();
}
}
private void SAVE() {
try {
if(!file.exists()) file.createNewFile(); //if the file !exist create a new one
BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsolutePath()));
bw.write(userName.getText()); //write the name
bw.newLine(); //leave a new Line
bw.write(passwordField.getPassword()); //write the password
bw.close(); //close the BufferdWriter
} catch (IOException e) { e.printStackTrace(); }
}
private void UPDATE() {
try {
if(file.exists()){ //if this file exists
Scanner scan = new Scanner(file); //Use Scanner to read the File
userName.setText(scan.nextLine()); //append the text to name field
passwordField.setText(scan.nextLine()); //append the text to password field
scan.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
btnLogin.setBounds(231, 112, 89, 23);
frmUserpass.getContentPane().add(btnLogin);

Parse Input from GUI instead of Console in Eclipse

I have a small GUI project with a text-box and submit button. What I want to do is for user to type into the text-box and submit an input that would move them through the program (ex. 1 to go to next menu). The program did not use to have a GUI and used console to enter input (as seen in the first code) and so I want to move the program away from console.
Right now my main is:
public static void main(String[] args) {
//Initialize menu variable
Menu menu = MainMenu.getInstance();
new Console();
while (true){
//Display current menu
menu.displayMenu();
while (menu.moreInputNeeded()){
menu.displayPrompt();
try {
// Process user input.
menu.parseInput(new BufferedReader(new InputStreamReader(System.in)).readLine());
} catch (IOException e) {
// printStackTrace();
System.out.println(Prompt.INVALID_INPUT);
}
}
menu = menu.getNextMenu();
}
}
and I use a text/submit button as followed:
//Create the Text Box
JTextField textField = new JTextField(20);
//Submit Button
JButton submit = new JButton("Submit");
//Submit Function
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
menuinput = textField.getText();
textField.setText("");
//
System.out.println(menuinput);
}
});
So is it possible to process user input from the GUI instead of the console?
I was able to figure out my own question. I implemented:
//Variables
JTextField tfIn;
JLabel lblOut;
private final PipedInputStream inPipe = new PipedInputStream();
private final PipedInputStream outPipe = new PipedInputStream();
PrintWriter inWriter;
String input = null;
Scanner inputReader = new Scanner(System.in);
//Variables
System.setIn(inPipe);
try {
System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));
inWriter = new PrintWriter(new PipedOutputStream(inPipe), true);
}
catch(IOException e) {
System.out.println("Error: " + e);
return;
}
tfIn = new JTextField();
tfIn.addActionListener(this);
frame.add(tfIn, BorderLayout.SOUTH);
With Method:
public synchronized void actionPerformed(ActionEvent evt)
{
textArea.setText("");
String text = tfIn.getText();
tfIn.setText("");
inWriter.println(text);
}
There might be some other little aspects I missed but that's the most important parts.

Why my JTextArea is not displaying properly from the while loop?

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

Append Images to RTF document

I am trying to add images to a rtf document. I am able to add images to the document but I can't append any images. This means that when the 2nd Image is added, the first image is removed. I think that whenever the code is executed a new rtf document is created.
public class InsertToWord {
com.lowagie.text.Document doc = null;
FileOutputStream evidenceDocument;
String fileName = "evidenceDocument.rtf";
settings obj = null;
InsertToWord() {
obj = new settings();
doc = new com.lowagie.text.Document();
}
public void insertImage(File saveLocation) {
try {
evidenceDocument = new FileOutputStream(obj.getFileLocation() + fileName);
RtfWriter2.getInstance(doc, evidenceDocument);
doc.open();
com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(saveLocation.toString());
image.scaleAbsolute(400, 300);
doc.add(image);
doc.close();
} catch (Exception e) {
}
}
}
On your insertImage() method, you are indeed creating a new file and overwriting your old one.
This line is creating the new file:
evidenceDocument = new FileOutputStream(obj.getFileLocation()+fileName);
You can pass the FileOutputStream in as a parameter to the method and then remove the line all together:
public void insertImage( FileOutputStream evidenceDocument , File saveLocation )
This code is the one I´m using to add an image into a RTF format and its working fine :
public void actionPerformed(ActionEvent arg0) {
JFileChooser fileChooser = new JFileChooser();
int option = fileChooser.showOpenDialog(null);
File file = fileChooser.getSelectedFile();
if (option == JFileChooser.APPROVE_OPTION) {
try {
BufferedImage image = ImageIO.read(file);
image = Scalr.resize(image, 200);
document = (StyledDocument) textPane.getDocument();
javax.swing.text.Style style = document.addStyle("StyleName", null);
StyleConstants.setIcon(style, new ImageIcon(image));
document.insertString(document.getLength(), "ignored text", style);
}
catch (Exception e) {
e.printStackTrace();
}
}
if (option == JFileChooser.CANCEL_OPTION) {
fileChooser.setVisible(false);
}
}// End of Method
The textPane variable is a JTextPane.

Categories