Hi I am new to swing and I need some help. I have build a file processing project where I read an input file and some other existing files in the project, do many checks and parsing and produce a csv and an xlsx file. Until now I used for these inputs
JTextField csvpath = new JTextField();
JTextField csvfile = new JTextField();
JTextField xmlpath = new JTextField();
JTextField xmlfile = new JTextField();
JTextField excpath = new JTextField();
JTextField excfile = new JTextField();
Object[] message = {
"Enter the path of the CSV file to be created:", csvpath,
"Enter the CSV file name:", csvfile,
"Now enter the XML path to be read:", xmlpath,
"Also enter the XML file name:", xmlfile,
"Please enter the Excel file path to be created:", excpath,
"Finally enter the Excel file name:", excfile
};
int option = JOptionPane.showConfirmDialog(null, message, "Convert XML File to CSV File", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
String csvPath = csvpath.getText();
String csvFileName = csvfile.getText();
String xmlPath = xmlpath.getText();
String xmlFileName = xmlfile.getText();
String excPath = excpath.getText();
String excFileName = excfile.getText();
String FullcsvPath = csvPath + "\\" + csvFileName + ".csv";
String FullxmlPath = xmlPath + "\\" + xmlFileName + ".xml";
String excelPath = excPath + "\\" + excFileName + ".xlsx";
.
.
parsing/creating starts...
Because in the future this project will be used by others I wanted to create file chooser and get the file/folder paths as strings in order to read the input and create etc...
I have created a class and public strings for paths and when I call it the program does not stop like before, continues to run while the Frame is open without getting the paths I want. My new class is:
public static void SelectFiles() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
final JFrame window = new JFrame("Parse for manufacturers - Developed by Aris M");
JPanel topPanel = new JPanel();
JPanel midPanel = new JPanel();
JPanel botPanel = new JPanel();
final JButton openFolderChooser = new JButton("Select Folder to save csv - xlsx results");
final JButton openFileChooser = new JButton("Select the File to be parsed");
final JButton closeButton = new JButton("OK");
window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
final JFileChooser fc = new JFileChooser();
openFolderChooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fc.setCurrentDirectory(new java.io.File("user.home"));
fc.setDialogTitle("This is a JFileChooser");
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (fc.showOpenDialog(openFolderChooser) == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(null, fc.getSelectedFile().getAbsolutePath());
System.out.println(fc.getSelectedFile().getAbsolutePath());
csv = fc.getSelectedFile().getAbsolutePath();
xlsx = csv;
System.out.println(csv);
}
}
});
openFileChooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fc.setCurrentDirectory(new java.io.File("user.home"));
fc.setDialogTitle("This is a JFileChooser");
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
if (fc.showOpenDialog(openFileChooser) == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(null, fc.getSelectedFile().getAbsolutePath());
System.out.println(fc.getSelectedFile().getAbsolutePath());
xml = fc.getSelectedFile().getAbsolutePath();
System.out.println(xml);
}
}
});
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
window.dispose();
}
});
window.add(BorderLayout.NORTH, topPanel);
window.add(BorderLayout.CENTER, midPanel);
window.add(BorderLayout.SOUTH, botPanel);
topPanel.add(openFolderChooser);
midPanel.add(openFileChooser);
botPanel.add(closeButton);
window.setSize(500, 150);
window.setVisible(true);
window.setLocationRelativeTo(null);
}
Swing code runs in separate thread known as the event dispatch thread. Just make your main thread busy while frame is visible. Add following code to the end of SelectFiles() method:
while (window.isVisible()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Related
1
I opened File Dialog but I don't create the file on it? How?
JFileChooser fileChooser = new JFileChooser();
File selectedFile = null;
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(this);
if (**result == JFileChooser.APPROVE_OPTION**) {
selectedFile = fileChooser.getSelectedFile();
} else {
confirmExit();
return;
}
To save a file with JFileChooser, you need to use the showSaveDialog() method instead of the showOpenDialog() like in your snippet. For more information check out How to use File Choosers and check out the JFileChooser JavaDoc.
Then the next step if the saving has been approved, is to actually write the file.
For this, you can use a FileWriter.
I put together a small snippet, which opens a JFileChooser on a button click, where you can provide the filename, where some String will be written to this file.
Example:
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> buildGui());
}
private static void buildGui() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton btn = new JButton("Save your File");
// action listener for the button
btn.addActionListener(e -> {
JFileChooser fileChooser = new JFileChooser(); // create filechooser
int retVal = fileChooser.showSaveDialog(frame); // open the save dialog
if (retVal == JFileChooser.APPROVE_OPTION) { // check for approval
// create a bufferedwriter with the specified file
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile()))) {
// write the content to the file
writer.write("Your content that shall be written to the file");
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
panel.add(btn);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
Output:
I am working on a text editor in Java as a fun side project. When I exported the project, I converted to executable JAR file to ".exe" so that I could set the text editor as the default program to open ".txt" files. I can run the ".exe" and write text and then save the file, and the file saves, but the contents of the file are not saved when I try to open the file with the text editor; however, I can open the same file with notepad, and the contents of the file show. The file saves fine in Eclipse. What do I need to fix so that the file contents are shown when I try to open them with my text editor?
Here is my code:
public class Open extends JFrame implements KeyListener {
JPanel panel = new JPanel();
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
JMenuBar menuBar = new JMenuBar();
JMenu menu;
JMenuItem item;
Font systemFont;
public Open() {
systemFont = new Font("Times New Roman", Font.PLAIN, 20);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(false);
textArea.setFont(systemFont);
panel.setLayout(new BorderLayout());
panel.add(scrollPane);
add(panel);
menu = new JMenu("File");
item = new JMenuItem("Save As");
item.setAccelerator(KeyStroke.getKeyStroke('S', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser JFC = new JFileChooser();
File fileName = new File("");
BufferedWriter writer = null;
try {
int rVal = JFC.showSaveDialog(Open.this);
if(rVal == JFileChooser.APPROVE_OPTION) {
writer = new BufferedWriter(new FileWriter(JFC.getSelectedFile()));
writer.write(textArea.getText());
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(writer != null) {
try {
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
});
menu.add(item);
menuBar.add(menu);
menu = new JMenu("Edit");
item = new JMenuItem("Undo");
menu.add(item);
menu.add(item);
menuBar.add(menu);
add("North", menuBar);
setLookAndFeel();
frameDetails("Text Editor");
}
public void frameDetails(String title) {
setSize(700, 500);
setLocationRelativeTo(null);
setTitle(title);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void setLookAndFeel() {
try {
UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Open editor = new Open();
}
}
Here is the bit of code with the save button:
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser JFC = new JFileChooser();
File fileName = new File("");
BufferedWriter writer = null;
try {
int rVal = JFC.showSaveDialog(Open.this);
if(rVal == JFileChooser.APPROVE_OPTION) {
writer = new BufferedWriter(new FileWriter(JFC.getSelectedFile()));
writer.write(textArea.getText());
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(writer != null) {
try {
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
});
You are never reading the text file. In order to do that, Use something like this
public void loadFile(JTextArea area, String path, String file)
{
try
{
area.read(new FileReader(path + file), "Default");
}
catch(IOException e)
{
e.printStackTrace();
}
}
Note: You don't have to have this in a method. You could just use the try - catch code
To act as a default text editor, your program needs to accept a file name as the argument to main (String[] args). It should verify the file exists, then open it, read its contents, and close it.
Also, when you save a file you should rename the former version to "name.bak" or "name~" before overwriting it with the new version, in case something goes wrong during the save.
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 creating a program in Java(GUI) that when you fill out the TextFields and click enter; the name,age,email,nationality and cell number will be saved in a textfile named StoredInfo.txt . The program I created didn't delete the data you entered if you fill out the textfields again.
What I want want to do is to use the Clear Data button I created and it will delete all the data stored in the text file (StoredInfo.txt).
Here's my program:
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SignUp extends JFrame implements ActionListener
{
//Variables
private JButton enter,clear;
private JLabel header,name,age,email,nationality,cellno;
private JTextField nameTF,ageTF,emailTF,nationalityTF,cellnoTF;
private Container container;
private PrintWriter pwriter;
//Constructor
public SignUp()
{
setTitle("Form");
setSize(500,500);
setResizable(false);
setDefaultCloseOperation(this.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(null);
container = this.getContentPane();
container.setBackground(Color.GRAY);
enter = new JButton("Enter");
clear = new JButton("Clear Data");
header = new JLabel("Form");
name = new JLabel("Name: ");
age = new JLabel("Age: ");
email = new JLabel("Email Address: ");
nationality = new JLabel("Nationality: ");
cellno = new JLabel("Cellphone #: ");
nameTF = new JTextField(20);
ageTF = new JTextField(20);
emailTF = new JTextField(20);
nationalityTF = new JTextField(20);
cellnoTF = new JTextField(20);
nameTF.addActionListener(this);
ageTF.addActionListener(this);
emailTF.addActionListener(this);
nationalityTF.addActionListener(this);
cellnoTF.addActionListener(this);
enter.addActionListener(this);
clear.addActionListener(this);
//Add section
this.add(header);
this.add(name);
this.add(age);
this.add(email);
this.add(nationality);
this.add(cellno);
this.add(header);
this.add(nameTF);
this.add(ageTF);
this.add(emailTF);
this.add(nationalityTF);
this.add(cellnoTF);
this.add(clear);
this.add(enter);
//SetBounds
enter.setBounds(180,270,80,40);
clear.setBounds(270,270,100,40);
header.setBounds(230,30,80,50);
header.setFont(new Font("Arial",Font.BOLD,25));
header.setForeground(Color.WHITE);
name.setBounds(80,90,40,40);
age.setBounds(80,120,40,40);
email.setBounds(80,150,110,40);
nationality.setBounds(80,180,100,40);
cellno.setBounds(80,210,100,40);
nameTF.setBounds(180,95,190,25);
ageTF.setBounds(180,125,190,25);
emailTF.setBounds(180,155,190,25);
nationalityTF.setBounds(180,185,190,25);
cellnoTF.setBounds(180,215,190,25);
name.setForeground(Color.WHITE);
age.setForeground(Color.WHITE);
email.setForeground(Color.WHITE);
nationality.setForeground(Color.WHITE);
cellno.setForeground(Color.WHITE);
//Setting Up Text File
try
{
File data = new File("StoredInfo.txt");
pwriter = new PrintWriter(new FileWriter(data,false));
if(data.exists())
{
}else
{
data.createNewFile();
}
}catch(Exception e)
{
e.printStackTrace();
}
setVisible(true);
}
//Actions
public void actionPerformed(ActionEvent e)
{
Object action = e.getSource();
if(action.equals(enter))
{
pwriter.println("Name: " + nameTF.getText());
pwriter.println("Age: " + ageTF.getText());
pwriter.println("Email: " + emailTF.getText());
pwriter.println("Nationality: " + nationalityTF.getText());
pwriter.println("CellNo #: " + cellnoTF.getText());
pwriter.println("---------------------------");
pwriter.flush();
pwriter.close();
}else if(action.equals(clear))
{
}
}
///Main
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new SignUp();
}
});
}
}
Generally speaking new FileWriter(file); will overwrite the file leaving it empty.
In your case,
else if (action.equals(clear)) {
// Need to close this first to avoid resource leak
pw.close();
File data = new File("StoredInfo.txt");
// I believe you will need pw later
pw = new PrintWriter(new FileWriter(data, false));
}
Hope that helped.
I am new to UI design in Java. I am trying to create a GUI to download a file off the Internet and save it on your hard drive. I have got the code working except for one thing which I want to add. I have added a JFileChooser which lets the user select the destination folder. But I am unable to figure out how to change the filename to the one which user enters in the Save As bar on the JFileChooser menu.
Browse Button
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true);
//chooser.showDialog(downloadButton, "Save");
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
System.out.println("The location to save is: " + chooser.getCurrentDirectory());
DESTINATION_FOLDER = chooser.getCurrentDirectory().toString();
}
}
});
Download Button
URLConnection connection = downloadUrl.openConnection();
input = new BufferedInputStream(connection.getInputStream());
output = new FileOutputStream(DESTINATION_FOLDER + "/" + filename);
Here filename should be the one which user enters. Pointers on how to get this done?
Actually you don't need to get the FileName from the Save As Bar in the JFileChooser.
Just do like this:
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
//Don't use the 'FileSelectionMode();'. Let it be Default.
chooser.setAcceptAllFileFilterUsed(true);
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
file = chooser.getSelectedFile();
//file should be declared as a File.
System.out.println("The location to save is: " + chooser.getCurrentDirectory();));
System.out.println("The FileName is: " + file.getName());
}
}
DOWNLOAD BUTTON:
URLConnection connection = downloadUrl.openConnection();
input = new BufferedInputStream(connection.getInputStream());
output = new FileOutputStream(file);
Without seeing more of your code the best I could suggest is to create a Global String in the class you are working in.
public class gui extends JFrame{
public String filePath="";
public static void main(String args[]){
//button code
browseButton.addActionListener(new ActionListener())
saveAsButton.addActionListener(new ActionListener())
URLConnection connection = downloadUrl.openConnection();
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("browseButton"){
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true);
//chooser.showDialog(downloadButton, "Save");
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
System.out.println("The location to save is: "+chooser.getCurrentDirectory());
filePath = chooser.getCurrentDirectory().toString();
}
else{
//save as button selected
input = new BufferedInputStream(connection.getInputStream());
output = new FileOutputStream(filePath);
}
}
}
Add this line:
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
Full code:
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true);
//chooser.showDialog(downloadButton, "Save");
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
System.out.println("The location to save is: " + chooser.getCurrentDirectory());
DESTINATION_FOLDER = chooser.getCurrentDirectory().toString();
}
}