JFileChooser component display weird - java

I'm trying to open a file in filechooser dialog, however, when i opened a file or simply close the dialog. The dialog appears again, i have to close it twice. Here is my code, don't know what's wrong with it
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
ObjectInputStream input;
JFileChooser openFileChooser = new JFileChooser();
openFileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
openFileChooser.showOpenDialog(null);
openFileChooser.setCurrentDirectory(new File("."));
if (openFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
input = new ObjectInputStream(new FileInputStream(openFileChooser.getSelectedFile()));
input.close();
}
javax.swing.JFrame openFileFrame = new javax.swing.JFrame();
openFileFrame.setLayout(new BorderLayout());
openFileFrame.setLocationRelativeTo(null);
openFileFrame.add(openFileChooser, BorderLayout.CENTER);
openFileFrame.pack();
openFileFrame.setVisible(true);
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}

this code lines to create first one
JFileChooser openFileChooser = new JFileChooser();
openFileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
openFileChooser.showOpenDialog(null);
openFileChooser.setCurrentDirectory(new File("."));
if (openFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
input = new ObjectInputStream(new FileInputStream(openFileChooser.getSelectedFile()));
input.close();
}
and rest of code lines to embeding second one
javax.swing.JFrame openFileFrame = new javax.swing.JFrame();
openFileFrame.setLayout(new BorderLayout());
openFileFrame.setLocationRelativeTo(null);
openFileFrame.add(openFileChooser, BorderLayout.CENTER);
openFileFrame.pack();
openFileFrame.setVisible(true);

Remove the first occurrence of openFileChooser.showOpenDialog(null);

Related

How To Open File Dialog And Create File On It?

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:

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.

Java program not saving contents of ".txt" file

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.

JFileChooser click programmatically on open

I have following code to open a JFilechooser
chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
chooser.showOpenDialog(null);
String path = chooser.getSelectedFile().getPath();
What I want to do is programmatically close this dialog. I see the open button, but how can I "press" it programmatically?
This will simulate the user selection and opening of a file:
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(YourApplication.class.getName()).log(Level.SEVERE, null, ex);
}
chooser.setSelectedFile(new File("/your/file/path")));
chooser.approveSelection();
}
}).start();
chooser.showOpenDialog(null);
String path = chooser.getSelectedFile().getPath();
The Thread.sleep(100) is ugly, but has to be in there because otherwise, the JFileChooser isn't open yet when approveSelection is called.

How can i save .txt file at desired location using JFileChooser

Using following code i can store program.txt in a working project folder, but how can I use JFileChooser or any other option to save file at a selected location?
b2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
o = new BufferedWriter(new FileWriter("program.txt"));
o.write(t1.getText());
o.write(",");
o.write(t2.getText());
o.write(",");
o.write(t3.getText());
o.write(",");
o.write(t4.getText());
o.write(",");
o.write(t5.getText());
o.write(",");
o.write(t6.getText());
o.write(",");
o.write(t7.getText());
o.write(",");
o.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showSaveDialog(aComponent); //parent component to JFileChooser
if (returnVal == JFileChooser.APPROVE_OPTION) { //OK button pressed by user
File file = fc.getSelectedFile(); //get File selected by user
o = new BufferedWriter(new FileWriter(file)); //use its name
...
//your writing code goes here
}
You can do this way by setting File object in JFileChooser object
File f = new File("filename");
myJFileChooser.setSelectedFile(f);
check this post for more
http://www.coderanch.com/t/561950/GUI/java/Save-JTextArea-JFileChooser-TXT-file

Categories