Choosing file path not seen on JTextField in Ubuntu on Eclipse - java

I have this code (this is all code). I want to write file path(choosing file) on JTextField. I run the program and i press button and file chooser open, i choose file but file path not write on JTextField.
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.dyno.visual.swing.layouts.Bilateral;
import org.dyno.visual.swing.layouts.Constraints;
import org.dyno.visual.swing.layouts.GroupLayout;
import org.dyno.visual.swing.layouts.Leading;
//VS4E -- DO NOT REMOVE THIS LINE!
public class xailabsPanel extends JFrame {
private static final long serialVersionUID = 1L;
private JButton jButton0;
public static String path;
private JTextField jTextField0;
private static final String PREFERRED_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";
public xailabsPanel() {
initComponents();
}
private void initComponents() {
setLayout(new GroupLayout());
add(getJText(), new Constraints(new Bilateral(12, 12, 4), new Leading(100, 10, 10)));
add(getJButton0(), new Constraints(new Bilateral(117, 117, 94), new Leading(57, 12, 12)));
setSize(328, 252);
}
private JButton getJButton0() {
if (jButton0 == null) {
jButton0 = new JButton();
jButton0.setText("jButton0");
jButton0.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent event) {
jButton0MouseMouseClicked(event);
}
});
}
return jButton0;
}
private JTextField getJText() {
if (jTextField0 == null) {
jTextField0 = new JTextField();
}
return jTextField0;
}
private static void installLnF() {
try {
String lnfClassname = PREFERRED_LOOK_AND_FEEL;
if (lnfClassname == null)
lnfClassname = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(lnfClassname);
} catch (Exception e) {
System.err.println("Cannot install " + PREFERRED_LOOK_AND_FEEL
+ " on this platform:" + e.getMessage());
}
}
/**
* Main entry of the class.
* Note: This class is only created so that you can easily preview the result at runtime.
* It is not expected to be managed by the designer.
* You can modify it as you like.
*/
private void jButton0MouseMouseClicked(MouseEvent event) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.showOpenDialog(null);
fileChooser.setCurrentDirectory(new File(System.getProperty("home/kerim")));
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
// user selects a file
File selectedFile = fileChooser.getSelectedFile();
path = selectedFile.getAbsolutePath().toString();
jTextField0.setText(path);
}
}
public static void main(String[] args) {
installLnF();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
xailabsPanel frame = new xailabsPanel();
frame.setDefaultCloseOperation(xailabsPanel.EXIT_ON_CLOSE);
frame.setTitle("xailabsPanel");
frame.getContentPane().setPreferredSize(frame.getSize());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

You are creating a new JTextField inside the method (and you are modfying its contents), but it's not added anywhere.
Drop jTextField0 = new JTextField() and it should work (assuming you already created the text field beforehand).

The code works fine, when I do the following
Change layout manager default BorderLayout (why? Because I don't have GroupLayout, it's not a standard Layout Manager - so I don't know if it's a direct cause)
Add the componenst to corresponding BorderLayout positions.
Changed setSize() to pack(). This is the preferred way.
create the text field the the constructor (new JTextField(int columns)). For some weird reason I feel like this is the culprit (as without this, the text field has no preferred size, and maybe you just weren't seeing it. Not 100% sure, hell probably not even 50% sure, as I couldn't test the GroupLayout
Got rid of frame.getContentPane().setPreferredSize(frame.getSize());, another suspected culprit (not really necessary to delete, but not preferred to keep).
Got rid of this unnecessary line, as it's redundant fileChooser.showOpenDialog(null); and causing the file chooser to open twice.
Here's the result
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
//VS4E -- DO NOT REMOVE THIS LINE!
public class xailabsPanel extends JFrame {
private static final long serialVersionUID = 1L;
private JButton jButton0;
public static String path;
private JTextField jTextField0;
private static final String PREFERRED_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";
public xailabsPanel() {
initComponents();
}
private void initComponents() {
//setLayout(new GroupLayout());
add(getJText(), BorderLayout.WEST);
add(getJButton0(), BorderLayout.EAST);
//setSize(328, 252);
pack();
}
private JButton getJButton0() {
if (jButton0 == null) {
jButton0 = new JButton();
jButton0.setText("jButton0");
jButton0.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent event) {
jButton0MouseMouseClicked(event);
}
});
}
return jButton0;
}
private JTextField getJText() {
if (jTextField0 == null) {
jTextField0 = new JTextField(20);
}
return jTextField0;
}
private static void installLnF() {
try {
String lnfClassname = PREFERRED_LOOK_AND_FEEL;
if (lnfClassname == null)
lnfClassname = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(lnfClassname);
} catch (Exception e) {
System.err.println("Cannot install " + PREFERRED_LOOK_AND_FEEL
+ " on this platform:" + e.getMessage());
}
}
/**
* Main entry of the class. Note: This class is only created so that you can
* easily preview the result at runtime. It is not expected to be managed by
* the designer. You can modify it as you like.
*/
private void jButton0MouseMouseClicked(MouseEvent event) {
JFileChooser fileChooser = new JFileChooser();
//fileChooser.showOpenDialog(null);
//fileChooser.setCurrentDirectory(new File(System
//.getProperty("home/kerim")));
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
// user selects a file
File selectedFile = fileChooser.getSelectedFile();
path = selectedFile.getAbsolutePath().toString();
System.out.println(path);
jTextField0.setText(path);
}
}
public static void main(String[] args) {
installLnF();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
xailabsPanel frame = new xailabsPanel();
frame.setDefaultCloseOperation(xailabsPanel.EXIT_ON_CLOSE);
frame.setTitle("xailabsPanel");
//frame.getContentPane().setPreferredSize(frame.getSize());
((JPanel) frame.getContentPane()).setBorder(BorderFactory
.createEmptyBorder(20, 20, 20, 20));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

You never added JTextField to your JFrame (or whatever window you want the text field to be).
Right after your JTextFIeld0 = new JTextField(); add: myWindow.add(jTextField0)
also, you are displaying two open dialogs. i dont think it is your desired behavior, remove the file fileChooser.showOpenDialog(null);
Here is a quick example of what you are trying to accomplish:
public static void main(String[] args)
{
// you should not need this, use the frame you already have, where the button is.
JFrame window = new JFrame();
// This is what you are doing in your code, however, you should add a text field
// whereever you create and populate your jframe, and add the button etc, and simply
// set the jtextfield value here
JTextField tf = new JTextField();
// again in your case you should have this somewhere else, i assume if you are
// displaying a button, you must have a JFrame somewhere
window.setSize(100, 100);
window.add(tf);
window.setLocationRelativeTo(null);
/***** you DO NEED this code **************/
// create file chooser and open the dialog.
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(null);
// get selected file object
File f = fc.getSelectedFile();
// disply file path in the text field
tf.setText(f.getAbsolutePath());
/****** end of the code you need *********/
// display a JFrame with the text field (dont need this obviously you
// already are displaying the frame)
window.setVisible(true);
}

Related

Get boolean value from a class to main method. JAVA

I've been trying for hours to get the boolean value from a class to my main method. I want the variable GeneralFrame.
Also is it correct to use JDialog to ask the user if he is new or returned and then run my JFrame? Here is my code:
package portofoliexpense;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
* #author AlexandrosAndreadis
*/
public class PortofoliExpenseDialog extends JDialog implements ActionListener {
boolean GeneralFrame = false;
//dimiourgia minimatos
JPanel messagePane = new JPanel();
JPanel buttonPanel = new JPanel(); // ftiaxnw button
JButton existinguser = new JButton("Existing User");
JButton newuser = new JButton("New User");
public PortofoliExpenseDialog (JFrame parent, String title) {
super(parent, title);
setLocationRelativeTo(null);
//dimiourgia minimatos
messagePane.add(new JLabel("Hello, click one of the above to continue!"));
getContentPane().add(messagePane);// ypodoxeas gia ola ta //components
buttonPanel.add(existinguser);
buttonPanel.add(newuser);
getContentPane().add(buttonPanel, BorderLayout.PAGE_END); // border //layout sto telos tou dialog
newuser.addActionListener(this);
existinguser.addActionListener(this);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setResizable(false); // den allazei megethos
pack();
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == existinguser) {
GeneralFrame = true;
}
if (source == newuser){
GeneralFrame = false;
}
}
}
I tried lot things. I also used return but couldn't get it.
You can use a JOptionPane for this instead of a JDialog.
Here is an example:
static boolean isNewUser;
public static void main(String[] args) throws InvocationTargetException, InterruptedException {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
isNewUser = isNewUser();
}
});
System.out.println("Is new user: " + isNewUser);
}
public static boolean isNewUser() {
Object[] options = { "Existing User", "New User" };
int resp = JOptionPane.showOptionDialog(null, "Hello, click one of the above to continue!", "User Type", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
return resp == JOptionPane.NO_OPTION;
}
In the main method are you calling the variable GeneralFrame as "instance name".GeneralFrame ?
Main method only takes in a string array:
public static void main(String[] args) {
So, the only data you can send to the main method is, of course, an array. But, you want to pass in a boolean.
You know how to pass a paramater, but here it only takes in a string array. Since we want to pass a boolean, lets just pass that boolean in the array.
After you pass the boolean into the main method through the string array, retrieve it doing the following:
boolean boolean1 = Boolean.parseBoolean(ArrayWhereIPutMyBoolean(0));
Now, boolean1 is the boolean that you passed in from main method!

Why is my output null every time?

Hello I have a class that opens a JFrame and takes in a text. But when I try getting the text it says its null.
Everytime I click the button I want the System.out to print the text I entered in the textArea.
This is my first class :
public class FileReader {
FileBrowser x = new FileBrowser();
private String filePath = x.filePath;
public String getFilePath(){
return this.filePath;
}
public static void main(String[] args) {
FileReader x = new FileReader();
if(x.getFilePath() == null){
System.out.println("String is null.");
}
else
{
System.out.println(x.getFilePath());
}
}
}
This is a JFrame that takes in the input and stores it in a static String.
/*
* This class is used to read the location
* of the file that the user.
*/
import java.awt.*;
import java.awt.event.*;
import java.awt.event.*;
import javax.swing.*;
public class FileBrowser extends JFrame{
private JTextArea textArea;
private JButton button;
public static String filePath;
public FileBrowser(){
super("Enter file path to add");
setLayout(new BorderLayout());
this.textArea = new JTextArea();
this.button = new JButton("Add file");
add(this.textArea, BorderLayout.CENTER);
add(this.button, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 100);
setVisible(true);
this.button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
filePath = new String(textArea.getText());
System.exit(0);
}
});
}
}
But everytime I run these programs I get
String is null.
You are mistaken by the way how JFrames work. A JFrame does not stall the execution of the code until it is closed. So, basically, your code creates a JFrame and then grabs the filePath variable in that object, before the user could have possibly specified a file.
So, to solve this, move the code that outputs the filepath to stdout to the ActionListener you have. Get rid of the System.exit() call, and use dispose() instead.
Update: You should have this code for the ActionListener:
this.button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
filePath = new String(textArea.getText());
if(filePath == null){
System.out.println("String is null.");
}
else
{
System.out.println(filePath);
}
dispose();
}
});
And as main method:
public static void main(String[] args)
{
FileBrowser x = new FileBrowser();
}
Your main does not wait until the user has specified a text in the textArea. You could prevent this behaviour by looping until the text in the textArea is set or you could place the logic of the main function into the ActionListener to handle the event.
Following the second way the main function only creates a new FileBrowser object.

How to save a text file without having to enter file name every time?

Hi all I am creating a simple text editor as a project and I have hit a snag when it comes to saving the content typed as a file. I can save the file using the Save As principle with a dialog box prompting the user to enter a filename.
The problem I am having is implementing the Save so that it saves to the file that is opened without having to go to the dialog box each time, like it would if someone did Ctrl+S. Anyone have any ideas how I would implement this feature?
Here's some of my code:
JMenuItem saveFile = new JMenuItem(new AbstractAction("Save") {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser save = new JFileChooser();
File filename = save.getSelectedFile();
if(opened == false && saved == false) {
save.showSaveDialog(null);
int confirmationResult;
if(filename.exists()) {
confirmationResult = JOptionPane.showConfirmDialog(getParent(), "Replace existing file?");
if(confirmationResult == JOptionPane.YES_OPTION) {
saveFile(filename);
}
} else {
saveFile(filename);
}
} else {
saveFile(filename);
}
}
});
saveFile.setPreferredSize(new Dimension(100, 20));
saveFile.setEnabled(true);
save method:
private void saveFile(File filename) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
writer.write(textArea.getText());
writer.close();
saved = true;
editorWindow.setTitle("JavaText - " + filename.getName());
} catch (IOException err) {
err.printStackTrace();
}
}
If you store the opened File object somewhere in your application you can then just pass that into your saveFile method on a key press using a KeyListener or KeyAdapter. Without seeing more of the application it's hard to tell where would be best to put it, but if you just store it in a variable somewhere you can refer back to it.
Store the file name somewhere
if(nameOfFile != null) then don't show the dialog box and go to save method
else show dialog box and call the save method
That's what I would do
The following program shows the implementation of 'Save' & 'Save as' functionality for text editors. Running it will shows a JFrame with a JTextArea , save JButton & save as JButton.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class MyFrame extends JFrame {
private boolean alreadySaved = false;
private BufferedWriter bw;
private JFileChooser fileChooser;
private JTextArea jta;
private File file;
private JButton save;
private JPanel mainPanel;
private JButton saveAs;
public MyFrame() {
initComponents();
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (!alreadySaved) {
int response = fileChooser.showSaveDialog(getParent());
file = fileChooser.getSelectedFile();
if (response == JFileChooser.APPROVE_OPTION) {
writeFile();
alreadySaved = true;
}
} else
writeFile();
}
});
saveAs.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
int response = fileChooser.showSaveDialog(getParent());
file = fileChooser.getSelectedFile();
if (response == JFileChooser.APPROVE_OPTION) {
writeFile();
alreadySaved = true;
}
}
});
} // END of Constructor
public void writeFile() {
try {
bw = new BufferedWriter(new FileWriter(file));
bw.write(jta.getText());
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void initComponents() {
fileChooser = new JFileChooser();
saveAs = new JButton("Save as");
jta = new JTextArea(10, 40);
mainPanel = new JPanel();
mainPanel.setBackground(Color.red);
save = new JButton("Save");
mainPanel.add(save);
mainPanel.add(saveAs);
this.setLayout(new BorderLayout());
this.add(jta);
this.add(mainPanel, BorderLayout.SOUTH);
this.pack();
this.setLocationRelativeTo(null);
}
public static void main(String[] args) {
new MyFrame().setVisible(true);
}
}

How to delete a file through JFileChooser?

How could i delete a file in JFileChooser? I know that the AWT since being written in native could has an option to delete a file from it using the simple Delete button.
But what if i would like to delete the file in JFileChooser? When i am trying to delete, it i got an exception that the File is being accessed by another program and hence could not be deleted.
Two questions that i would like to ask in this situation are..
Questions
Is there any hack to delete a file through JFileChooser?
Why i am not getting File is being accessed by another program when i am deleting in FileDialog. Is it because it is written in native code?
Any help is appreciated. Thanks in advance.
Yeah! I got it! I even updated the JFileChooser after the file was deleted.
Updated
Added functionality to delete multiple files and modified jf.getUI().rescanCurrentDirectory(jf) to jf.rescanCurrentDirectory() and removed superfluous PropertyChangeListener as per sir Rob Camick's suggestion.
/*
* #see http://stackoverflow.com/a/17622050/2534090
* #author Gowtham Gutha
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
class DeleteThroughJFileChooser extends JFrame
{
JButton jb;
JFileChooser jf;
File[] selectedFiles;
public DeleteThroughJFileChooser()
{
// Create and show GUI
createAndShowGUI();
}
private void createAndShowGUI()
{
// Set frame properties
setTitle("Delete through JFileChooser");
setLayout(new FlowLayout());
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Create JFileChooser
jf=new JFileChooser();
// Allow multiple selection
jf.setMultiSelectionEnabled(true);
// Create JButton
jb=new JButton("Open JFileChooser");
// Add ActionListener to it
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
// Show the file chooser
showFileChooser();
}
});
// Register the delete action
registerDelAction();
// Add JButton jb to JFrame
add(jb);
}
private void showFileChooser()
{
// Show the open dialog
int op=jf.showOpenDialog(this);
}
private void registerDelAction()
{
// Create AbstractAction
// It is an implementation of javax.swing.Action
AbstractAction a=new AbstractAction(){
// Write the handler
public void actionPerformed(ActionEvent ae)
{
JFileChooser jf=(JFileChooser)ae.getSource();
try
{
// Get the selected files
selectedFiles=jf.getSelectedFiles();
// If some file is selected
if(selectedFiles!=null)
{
// If user confirms to delete
if(askConfirm()==JOptionPane.YES_OPTION)
{
// Call Files.delete(), if any problem occurs
// the exception can be printed, it can be
// analysed
for(File f:selectedFiles)
java.nio.file.Files.delete(f.toPath());
// Rescan the directory after deletion
jf.rescanCurrentDirectory();
}
}
}catch(Exception e){
System.out.println(e);
}
}
};
// Get action map and map, "delAction" with a
jf.getActionMap().put("delAction",a);
// Get input map when jf is in focused window and put a keystroke DELETE
// associate the key stroke (DELETE) (here) with "delAction"
jf.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("DELETE"),"delAction");
}
public int askConfirm()
{
// Ask the user whether he/she wants to confirm deleting
// Return the option chosen by the user either YES/NO
return JOptionPane.showConfirmDialog(this,"Are you sure want to delete this file?","Confirm",JOptionPane.YES_NO_OPTION);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
new DeleteThroughJFileChooser();
}
});
}
}
Why would you delete a file from the chooser?
Use the jfilechooser to get the name of the file and location store as a variable. Close the file jfilechooser. Then delete the file.
import java.io.File;
public class DeleteFileExample
{
public static void main(String[] args)
{
try{
File file = new File("c:\\logfile20100131.log");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Also, I found this code that might prove to be usefull if you want the functionality to be in the jfilechooser itself. From Here. To run this you will also need This. Swing file
import darrylbu.util.SwingUtils;
import java.awt.Container;
import java.awt.Point;
import java.awt.event.*;
import javax.swing.*;
public class FileChooserDeleteMenu {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new FileChooserDeleteMenu().makeUI();
}
});
}
public void makeUI() {
final JFileChooser chooser = new JFileChooser();
final JList list = SwingUtils.getDescendantOfType(JList.class, chooser, "Enabled", true);
JPopupMenu popup = list.getComponentPopupMenu();
JMenuItem item = new JMenuItem("Delete");
item.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (chooser.getSelectedFile() != null) {
JOptionPane.showConfirmDialog(chooser,
"Delete " + chooser.getSelectedFile().getAbsolutePath() + "?",
"Confirm delete",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
}
}
});
popup.add(item);
final MouseListener listener = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
if (e.getSource() == list) {
list.setSelectedIndex(list.locationToIndex(p));
} else {
JTable table = (JTable) e.getSource();
if (table.columnAtPoint(p) == 0) {
int row = table.rowAtPoint(p);
table.getSelectionModel().setSelectionInterval(row, row);
}
}
}
};
list.addMouseListener(listener);
final Container filePane = SwingUtilities.getAncestorOfClass(sun.swing.FilePane.class, list);
filePane.addContainerListener(new ContainerAdapter() {
#Override
public void componentAdded(ContainerEvent e) {
JTable table = SwingUtils.getDescendantOfType(JTable.class, chooser, "Enabled", true);
if (table != null) {
for (MouseListener l : table.getMouseListeners()) {
if (l == listener) {
return;
}
}
table.addMouseListener(listener);
}
}
});
chooser.showOpenDialog(null);
System.exit(0);
}
}
This is how to add a delete key listener to your JFileChooser:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.nio.file.Files;
public class JFileChooserUtilities
{
public static void registerDeleteAction(JFileChooser fileChooser)
{
AbstractAction abstractAction = new AbstractAction()
{
public void actionPerformed(ActionEvent actionEvent)
{
JFileChooser jFileChooser = (JFileChooser) actionEvent.getSource();
try
{
File selectedFile = jFileChooser.getSelectedFile();
if (selectedFile != null)
{
int selectedAnswer = JOptionPane.showConfirmDialog(null, "Are you sure want to permanently delete this file?", "Confirm", JOptionPane.YES_NO_OPTION);
if (selectedAnswer == JOptionPane.YES_OPTION)
{
Files.delete(selectedFile.toPath());
jFileChooser.rescanCurrentDirectory();
}
}
} catch (Exception exception)
{
exception.printStackTrace();
}
}
};
fileChooser.getActionMap().put("delAction", abstractAction);
fileChooser.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("DELETE"), "delAction");
}
}
Code adapted from JavaTechnical's answer.

Java JTextField information access from another class

I am using a gui with JTextFields to collect some information and then a JButton that takes that infomration and writes it to a file, sets the gui visibility to false, and then uses Runnable to create an instance of another JFrame from a different class to display a slideshow.
I would like to access some of the information for the JTextFields from the new JFrame slideshow. I have tried creating an object of the previous class with accessor methods, but the values keep coming back null (I know that I have done this correctly).
I'm worried that when the accessor methods go to check what the variables equal the JTextFields appear null to the new JFrame.
Below is the sscce that shows this problem.
package accessmain;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class AccessMain extends JFrame implements ActionListener
{
private static final int FRAMEWIDTH = 800;
private static final int FRAMEHEIGHT = 300;
private JPanel mainPanel;
private PrintWriter outputStream = null;
private JTextField subjectNumberText;
private String subjectNumberString;
public static void main(String[] args)
{
AccessMain gui = new AccessMain();
gui.setVisible(true);
}
public AccessMain()
{
super("Self Paced Slideshow");
setSize(FRAMEWIDTH, FRAMEHEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
//Begin Main Content Panel
mainPanel = new JPanel();
mainPanel.setBorder(new EmptyBorder(0,10,0,10));
mainPanel.setLayout(new GridLayout(7, 2));
mainPanel.setBackground(Color.WHITE);
add(mainPanel, BorderLayout.CENTER);
mainPanel.add(new JLabel("Subject Number: "));
subjectNumberText = new JTextField(30);
mainPanel.add(subjectNumberText);
mainPanel.add(new JLabel(""));
JButton launch = new JButton("Begin Slideshow");
launch.addActionListener(this);
mainPanel.add(launch);
//End Main Content Panel
}
#Override
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Begin Slideshow"))
{
subjectNumberString = subjectNumberText.getText();
if(!(subjectNumberString.equals("")))
{
System.out.println(getSubjectNumber());
this.setVisible(false);
writeFile();
outputStream.println("Subject Number:\t" + subjectNumberString);
outputStream.close();
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
AccessClass testClass = new AccessClass();
testClass.setVisible(true);
}
});
}
else
{
//Add warning dialogue here later
}
}
}
private void writeFile()
{
try
{
outputStream = new PrintWriter(new FileOutputStream(subjectNumberString + ".txt", false));
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find file " + subjectNumberString + ".txt or it could not be opened.");
System.exit(0);
}
}
public String getSubjectNumber()
{
return subjectNumberString;
}
}
And then creating a barebones class to show the loss of data:
package accessmain;
import javax.swing.*;
import java.awt.*;
public class AccessClass extends JFrame
{
AccessMain experiment = new AccessMain();
String subjectNumber = experiment.getSubjectNumber();
public AccessClass()
{
System.out.println(subjectNumber);
}
}
Hardcoding the accessor method with "test" like this:
public String getSubjectNumber()
{
return "test";
}
Running this method as below in the new JFrame:
SelfPaceMain experiment = new SelfPaceMain();
private String subjectNumber = experiment.getSubjectNumber();
System.out.println(subjectNumber);
Does cause the system to print "test". So the accessor methods seem to be working. However, trying to access the values from the JTextFields doesn't seem to work.
I would read the information from the file I create, but without being able to pass the subjectNumber (which is used as the name of the file), I can't tell the new class what file to open.
Is there a good way to pass data from JTextFields to other classes?
pass the argument 'AccessMain' or 'JTextField' to the second class:
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
AccessClass testClass = new AccessClass(AccessMain.this); //fixed this
testClass.setVisible(true);
}
});
Then reading the value of 'subjectNumber'(JTextField value) from the 'AccessMain' or 'JTextField' in the second class:
public class AccessClass extends JFrame
{
final AccessMain experiment;
public AccessClass(AccessMain experiment)
{
this.experiment = experiment;
}
public String getSubjectNumber(){
return experiment.getSubjectNumber();
}
}
Also, you should try Observer pattern.
A simple demo of Observalbe and Observer
Observable and Observer Objects

Categories