saving setText after closing JDialog - java

I'm having a JDialog that works as a "Settings Window". I Choose a Save-File-Path and I click a button named Save. It Stores the Path and displays it on a JTextField. My problem is when i close the JDialog called "Settings" and open it again the JTextField doesn't display the newest Path.
I think it has something to do with the JDialog and that it doesn't store the setText variable. How can I store the new text in the JTextField?
This is a fragment of my code:
public class Settings extends JDialog {
textField = new JTextField("C\\:");
textField.setBounds(10, 36, 254, 28);
panel.add(textField);
textField.setEditable(false);
textField.setColumns(10);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
choose= new JFileChooser();
choose.setCurrentDirectory(new java.io.File("."));
choose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int rVal = choose.showSaveDialog(Settings.this);
if (rVal == JFileChooser.APPROVE_OPTION) {
filename.setText(choose.getSelectedFile().getName());
dir.setText(choose.getCurrentDirectory().toString());
File file = choose.getSelectedFile();
string myline = file.getAbsolutePath();
}});
sbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(myline);
}
});
So I wan't to set textfield to myline and even after closing the JDialog, store it and display it next time you open JDialog.

If you intend for the Settings class to store the value of the settings then make sure you are using one instance of Settings and not creating a new Settings object when opening the dialog.

declare the myline object outside of the listener like this way
private string myline = "":
public class Settings extends JDialog {
textField = new JTextField("C\\:");
textField.setBounds(10, 36, 254, 28);
panel.add(textField);
textField.setEditable(false);
textField.setColumns(10);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
choose= new JFileChooser();
choose.setCurrentDirectory(new java.io.File("."));
choose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int rVal = choose.showSaveDialog(Settings.this);
if (rVal == JFileChooser.APPROVE_OPTION) {
filename.setText(choose.getSelectedFile().getName());
dir.setText(choose.getCurrentDirectory().toString());
File file = choose.getSelectedFile();
myline = file.getAbsolutePath();
}});
sbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(myline);
}
});

You can make the JFileChooser instance variable of your main class so that it remembers the last directory location. You can also initialize your text field based on current file in the chooser.

Related

How to update Jlabel Text in Swing

I've a simple GUI file which is here:
I want to update the Label text each time when new file is selected
But when I am selecting any file, it is overlapping on the existing Jlabel text, so, please help me how do I update my JLabel text.
Here is my code:
protected static void excelButtonAction(){
excelReturnVal = fc.showOpenDialog(excelButton);
if(excelReturnVal==JFileChooser.APPROVE_OPTION){
FileValidation.excelFileValidation(fc);
System.out.println(FileValidation.getName() );
if(status==JFileChooser.CANCEL_OPTION){
}else{
fileName=FileValidation.getName();
FileValidation.updatemylabel(fileName);
excelFileName = new JLabel(fileName);
excelFileName.setText(fileName);
excelFileName.setBounds(140, 67, 350, 30);
excelFileName.setFont(new Font("Myriad Pro",Font.PLAIN,10));
panel.add(excelFileName);
panel.revalidate();
panel.repaint();
}
} else{
System.out.println("Open command cancelled by user." + newline);
}
}
public static void updatemylabel(String exfileName){
excelFileName = new JLabel(fileName);
excelFileName.setText(fileName);
JFileChooser chooser = new JFileChooser();
chooser.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(evt.getPropertyName())){
JFileChooser chooser = (JFileChooser) evt.getSource();
File oldFile = (File) evt.getOldValue();
File newFile = (File) evt.getNewValue();
File curFile = chooser.getSelectedFile();
}else if(JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equals(evt.getPropertyName())){
JFileChooser chooser = (JFileChooser)evt.getSource();
File[] oldFiles = (File[])evt.getOldValue();
File[] newFiles = (File[])evt.getNewValue();
File[] files = chooser.getSelectedFiles();
}
}
});
excelFileName = new JLabel(fileName);
excelFileName.setText(fileName);
excelFileName.setBounds(140, 67, 350, 30);
excelFileName.setFont(new Font("Myriad Pro",Font.PLAIN,10));
panel.add(excelFileName);
panel.revalidate();
panel.repaint();
existingText=exfileName;
}
Let me know if any further information is required to resolve my issue.
Thanks in advance for your co-operateion.
Your code creates a new JLabel instance every time. You need to create an instance once, store it in a field of your class, and call setText() whenever you need to update it.
You can have a look at the following for better understanding of labels in java :
How to Use Labels
setText
public void setText(String text)
Defines the single line of text this component will display. If the value of text is null or empty string, nothing is displayed.
The default value of this property is null.
This is a JavaBeans bound property.

Stop code execution until button is pressed

After choose.setVisible(true) I would like first
to be able to choose and after pressing the ok button
to continue execution.
The below code shows the chooser and continues
without waiting.
static class box extends JFrame {
Checkbox cboxtps = new Checkbox("Grf1", false);
Checkbox cboxrspt = new Checkbox("Grf2", false);
JLabel lblQts = new JLabel("Please select graphs");
JButton btn1 = new JButton("Go");
public box(String str) {
super(str);
setLayout(new GridLayout(4, 1));
add(lblQts);
add(cboxtps);
add(cboxrspt);
add(btn1);
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the button");
}
});
}
}
public static void main(String args[]) {
box choose = new box("Select Graphs");
choose.setSize(300, 150);
choose.pack();
choose.setVisible(true);
List<File> filepaths = fileselect();
list = Splitter(filepaths);
}
Since you are working asynchronously here, you would have to put the code after choose.setVisible(true) into the actionPerformed callback like so:
public void actionPerformed(ActionEvent e)
{
System.out.println("You clicked the button");
List<File> filepaths = fileselect();
list = Splitter(filepaths);
}
In general, when working with a lot of callbacks it is the best to define helper functions to avoid deep nesting.

Java Null Pointer When clicking JButton(Eclipse)

Here is my code. I am trying to make a basic text editor just to try out file writing and reading along with JPanels and such. My current issue is that users are required to input the full file path of the file and that can get quite frustrating. So I made a button that allows the user to have preset file path settings. When you click on the 'File Path Settings' button, there is a window that pops up allowing you to set the settings. (A file browsing button will be implemented later I just wanted to do this for fun first.)
public class EventListeners {
String textAreaValue;
String filePath;
String rememberedPath;
String rememberedPathDirectory;
//Global components
JTextField fileName,saveFilePath,filePathSaveDirectory,savedFilePath;
JButton save,help,savePath;
//JTextArea text;
public EventListeners(){
window();
}
public void window(){
JFrame window = new JFrame();
window.setVisible(true);
window.setSize(650,500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JButton saveFilePath = new JButton("File Path Save Settings");
JTextArea ltext = new JTextArea(10,50);
JLabel filler = new JLabel(" ");
JLabel lfileName = new JLabel("File Path(If error click help)");
JLabel lsaveFilePath = new JLabel("Save Path");
fileName = new JTextField(30);
save = new JButton("Save File");
help = new JButton("Help");
panel.add(lfileName);
panel.add(fileName);
panel.add(save);
panel.add(help);
panel.add(ltext);
panel.add(filler);
window.add(panel);
saveFilePath.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//JOptionPane.showMessageDialog(null,"Hello world!");
JFrame windowB = new JFrame();
int windows = 2;
windowB.setVisible(true);
windowB.setSize(500,500);
windowB.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panelB = new JPanel();
JLabel lFilePathSaveDirectory = new JLabel("Directory where the file path settings will be stored");
filePathSaveDirectory = new JTextField(20);
JLabel lsavedFilePath = new JLabel("The full file path or part you want stored.");
savedFilePath = new JTextField(20);
savePath = new JButton("Save Settings");
panelB.add(lFilePathSaveDirectory);
panelB.add(filePathSaveDirectory);
panelB.add(lsavedFilePath);
panelB.add(savedFilePath);
panelB.add(savePath);
windowB.add(panelB);
}
});
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textAreaValue = ltext.getText();
filePath = fileName.getText();
try {
FileWriter fw = new FileWriter(filePath);
PrintWriter pw = new PrintWriter(fw);
pw.println(textAreaValue);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!","Success!",JOptionPane.PLAIN_MESSAGE);
} catch(IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers","Error",JOptionPane.ERROR_MESSAGE);
}
}
});
help.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(panel, " ***The file name must be the full file path.***\n\n-=-=-=-=-=-=-=-=-=(MAC)=-=-=-=-=-=-=-=-=-\n\n Example: /Users/Cheese/Documents/FileName.txt\n\n\n-=-=-=-=-=-=-=-=(WINDOWS)=-=-=-=-=-=-=-=-\n\n *Note that 2 back slashes must be used* \n\nC:\\user\\docs\\example.txt", "Help",JOptionPane.PLAIN_MESSAGE);
}
});
panel.add(saveFilePath);
window.add(panel);
saveFilePath.setSize(20,100);
savePath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rememberedPathDirectory = filePathSaveDirectory.getText();
rememberedPath = savedFilePath.getText();
try {
FileWriter fw = new FileWriter(rememberedPathDirectory+"filePathSettings.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println(rememberedPath);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!","Success!",JOptionPane.PLAIN_MESSAGE);
} catch(IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers","Error",JOptionPane.ERROR_MESSAGE);
}
JOptionPane.showMessageDialog(panel, "The application will close. Anythings not saved will be deleted", "Alert",JOptionPane.WARNING_MESSAGE);
}
});
}
public static void main(String[] args) {
new EventListeners();
}
}
main problem is you are creating variable with same name inside the constructer, you already define as instance .then your instance variable keep uninitialized/null.
for example
you have declare instance variable
JButton save, help, savePath, saveFilePath;
inside constructor you are creating another local jbutton and initialize it so instance variable is null.
so instead of creating new one you should initialize instance field.
JButton saveFilePath = new JButton("File Path Save Settings"); // problem
saveFilePath = new JButton("File Path Save Settings"); // correct way
but there is a another problem ..you have declare saveFilePath instance field as a jtextfield and you have created a saveFilePath button inside the constructor .i think it may be a button not a textfield.
also you are initializing some variables inside saveFilePath.addActionListener(new ActionListener() { method but you are adding actionlistners to them before saveFilePath action fired .you have to add actionlistners after you initialized a component.
also you should call repaint() at last after you add all the component to a frame..
try to run this code
import javax.swing.*;
import java.awt.event.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class EventListeners {
String textAreaValue;
String filePath;
String rememberedPath;
String rememberedPathDirectory;
//Global components
JTextField fileName, filePathSaveDirectory, savedFilePath;
JButton save, help, savePath, saveFilePath;
//JTextArea text;
public EventListeners() {
window();
}
public void window() {
JFrame window = new JFrame();
window.setSize(650, 500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
saveFilePath = new JButton("File Path Save Settings");
JTextArea ltext = new JTextArea(10, 50);
JLabel filler = new JLabel(" ");
JLabel lfileName = new JLabel("File Path(If error click help)");
JLabel lsaveFilePath = new JLabel("Save Path");
fileName = new JTextField(30);
save = new JButton("Save File");
help = new JButton("Help");
panel.add(lfileName);
panel.add(fileName);
panel.add(save);
panel.add(help);
panel.add(ltext);
panel.add(filler);
window.add(panel);
saveFilePath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//JOptionPane.showMessageDialog(null,"Hello world!");
JFrame windowB = new JFrame();
int windows = 2;
windowB.setVisible(true);
windowB.setSize(500, 500);
windowB.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panelB = new JPanel();
JLabel lFilePathSaveDirectory = new JLabel("Directory where the file path settings will be stored");
filePathSaveDirectory = new JTextField(20);
JLabel lsavedFilePath = new JLabel("The full file path or part you want stored.");
savedFilePath = new JTextField(20);
savePath = new JButton("Save Settings");
panelB.add(lFilePathSaveDirectory);
panelB.add(filePathSaveDirectory);
panelB.add(lsavedFilePath);
panelB.add(savedFilePath);
panelB.add(savePath);
windowB.add(panelB);
System.out.println(savePath);
savePath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rememberedPathDirectory = filePathSaveDirectory.getText();
rememberedPath = savedFilePath.getText();
try {
FileWriter fw = new FileWriter(rememberedPathDirectory + "filePathSettings.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println(rememberedPath);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!", "Success!", JOptionPane.PLAIN_MESSAGE);
} catch (IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers", "Error", JOptionPane.ERROR_MESSAGE);
}
JOptionPane.showMessageDialog(panel, "The application will close. Anythings not saved will be deleted", "Alert", JOptionPane.WARNING_MESSAGE);
}
});
}
});
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textAreaValue = ltext.getText();
filePath = fileName.getText();
try {
FileWriter fw = new FileWriter(filePath);
PrintWriter pw = new PrintWriter(fw);
pw.println(textAreaValue);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!", "Success!", JOptionPane.PLAIN_MESSAGE);
} catch (IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
help.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(panel, " ***The file name must be the full file path.***\n\n-=-=-=-=-=-=-=-=-=(MAC)=-=-=-=-=-=-=-=-=-\n\n Example: /Users/Cheese/Documents/FileName.txt\n\n\n-=-=-=-=-=-=-=-=(WINDOWS)=-=-=-=-=-=-=-=-\n\n *Note that 2 back slashes must be used* \n\nC:\\user\\docs\\example.txt", "Help", JOptionPane.PLAIN_MESSAGE);
}
});
panel.add(saveFilePath);
window.add(panel);
saveFilePath.setSize(20, 100);
window.setVisible(true);
}
public static void main(String[] args) {
new EventListeners();
}
}
You also may want to consider dependency injection. That is becoming the standard way of doing things in the industry. Instead of the constructor doing all the work of creating all the objects your class uses, or calling another method like window() to do all the work, you pass in all the specifications to the constructor. It might look something like
public EventListeners(JButton save, JButton help, JButton saveFilePath) {
this.save = save;
this.help = help;
this.saveFilePath = saveFilePath);
}
Of course, you could also use a dependency injection framework like Spring, but that might be a bit much if your application is small.

Java Game: How to store a name entered in textfield and display in a label upon button press

I'm trying to display a name in a textlabel after it is entered in a textfield and pressed a 'Play' button.
The text field and button
private JTextField nameEnter = new JTextField("Enter name here");
private JButton saveName = new JButton("Play");
private JLabel namelabel = new JLabel("Player 1");
To add to board and position
getContentPane().add(nameEnter);
getContentPane().add(saveName);
getContentPane().add(namelabel);
nameEnter.setBounds(80,80+gize*bsize,200,50);
saveName.setBounds(100,100+gsize*bsize,200,50);
namelabel.setBounds(40,40+gsize*bsize,200,50);
This displays fine.
public void UpdateName() {
JButton saveName = new JButton("Play");
saveName.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
final String pName = nameEnter.getText();
namelabel.setText(pName);
}
});
}
I tried to create the above method to store it but this doesn't seem to do anything at all.
Any help appreciated.
Your UpdateName() method is creating its own local JButton saveName button and adding ActionListener to it. Problem is that this button is not the same as button you added to your content pane.
I am not sure why you even need this method. Simplest solution would be placing code responsible for adding this listener
saveName.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
namelabel.setText(nameEnter.getText());
}
});
in initializing method (somewhere after getContentPane().add(saveName);)
The method does:
Create a new button
Attach a listener
On action (click), update the name
To reuse the existing saveName button you already added to your layout,
drop the line that creates a new button, that is:
public void UpdateName() {
saveName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
final String pName = nameEnter.getText();
namelabel.setText(pName);
}
});
}

GUI... Why isnt my button responding to the first if and always heading to the next option

After the password is entered i want the window to disappear and pop a new window.
JButton btnEnter = new JButton("Enter");
btnEnter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
if(passwordField.equals("test"))
{
frame.setVisible(false);
}
else if(!passwordField.equals("test"))
{
JOptionPane.showMessageDialog(null,"Access Denied!!");
}
}
});
btnEnter.setBounds(149, 184, 117, 29);
frame.getContentPane().add(btnEnter);
I'm assuming passwordField is a JTextField, if so, you need to get the text from it, just .getText() I think and store that in a string. Then test the string. At the moment you are testing if your JTextField equals the string.
Create 2 JFrames and make a reference for each one:
JFrame oldFrame = new JFrame();
// ...
JFrame newFrame = new JFrame();
// ...
// ...
if(passwordField.equals("test"))
{
oldFrame.setVisible(false);
newFrame.setVisible(true);
}

Categories