Make JOptionPane message dialog box dissappear after rendering - java

I am building a simple JFrame GUI requiring user input. If the user clicks the submit button, it checks for input then either renders a JOptionPane message telling the user to completely fill out the form, or it tells the user that the form submitted and closes the program. The problme is that if the user left blank fields, the message dialog box renders and only adds to the loop count if you try to close it and does not allow the user to return to the JFrame to apply input to the form.
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.*;
import java.util.Scanner.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* #author joel.ramsey
*/
public class JRStarPhase5 extends JFrame{
public static void main (String [] args) throws IOException {
JFrame window = new JRStarPhase5();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}//end main method
private boolean validationError;
private final JTextField fNameInput;
private final JTextField miInput;
private final JTextField lNameInput;
private final JTextField productChoiceInput;
private final JTextField licenseQuantityInput;
private final JTextField streetAddressInput;
private final JTextField cityInput;
private final JTextField stateInput;
private final JTextField zipInput;
private final JTextField phoneInput;
//constructor for JFrame
public JRStarPhase5(){
setTitle("JRStar Star Gaze Order Processing");
setSize (800,800);
Container pane = getContentPane();
GridLayout grid = new GridLayout(0,2);
pane.setLayout(grid);
JLabel fNameLabel = new JLabel ("First name:");
JLabel mi = new JLabel ("Middle initial:");
JLabel lNameLabel = new JLabel ("Last name:");
JLabel productChoice = new JLabel ("Star Gaze version:");
JLabel licenseQuantity = new JLabel ("License quantity:");
JLabel streetAddress = new JLabel ("Street address:");
JLabel city = new JLabel ("City:");
JLabel state = new JLabel ("State abbrev:");
JLabel zip = new JLabel ("Zip code:");
JLabel phone = new JLabel ("Phone Number:");
this.fNameInput = new JTextField(15);
this.miInput = new JTextField (1);
this.lNameInput = new JTextField (15);
this.productChoiceInput = new JTextField (1);
this.licenseQuantityInput = new JTextField (2);
this.streetAddressInput = new JTextField (20);
this.cityInput = new JTextField (20);
this.stateInput = new JTextField (2);
this.zipInput = new JTextField (5);
this.phoneInput = new JTextField (10);
//add as last buttons
JButton submit = new JButton("Submit");
SubmitButtonHandler sbh = new SubmitButtonHandler();
submit.addActionListener(sbh);
JButton clear = new JButton("Clear");
ClearButtonHandler cbh = new ClearButtonHandler();
clear.addActionListener(cbh);
pane.add(fNameLabel);
pane.add(fNameInput);
pane.add(mi);
pane.add(miInput);
pane.add(lNameLabel);
pane.add(lNameInput);
pane.add(productChoice);
pane.add(productChoiceInput);
pane.add(licenseQuantity);
pane.add(licenseQuantityInput);
pane.add(streetAddress);
pane.add(streetAddressInput);
pane.add(city);
pane.add(cityInput);
pane.add(state);
pane.add(stateInput);
pane.add(zip);
pane.add(zipInput);
pane.add(phone);
pane.add(phoneInput);
//add last
pane.add(submit);
pane.add(clear);
}//end constructor
private class SubmitButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
validationError = (fNameInput.getText().equals("")||
miInput.getText().equals("")||
lNameInput.getText().equals("")||
streetAddressInput.getText().equals("")||
cityInput.getText().equals("")||
stateInput.getText().equals("")||
zipInput.getText().equals("")||
phoneInput.getText().equals(""));
for (int n=1; n<3; n++){
if (validationError){
if (n == 3){
System.exit(0);
}
JOptionPane.showMessageDialog(null,"Please complete each field within the order form.");
}
else break;
}
if (validationError = false)
JOptionPane.showMessageDialog(null,"Your order has been submitted!");
System.exit(0);
}
}//end submit
private class ClearButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
fNameInput.setText("");
miInput.setText("");
lNameInput.setText("");
productChoiceInput.setText("");
licenseQuantityInput.setText("");
streetAddressInput.setText("");
cityInput.setText("");
stateInput.setText("");
zipInput.setText("");
phoneInput.setText("");
}
}//end clear
}//end main class

I honestly don't know what else you expected (no offense).
Swing is a event driven environment. An event occurs, you react to it...
The loop will execute within the context of the EDT to start with, meaning that there is no way a user could actually close the dialog, correct the error and try to re-submit.
Even if it did, the loop does not allow for any opportunity for the validationError variable to be re-evaluated, meaning it will always be what it was originally set to earlier in the method (lets assume true for now)...
for (int n = 1; n < 3; n++) {
if (validationError) {
if (n == 3) {
System.exit(0);
}
JOptionPane.showMessageDialog(null, "Please complete each field within the order form.");
} else {
break;
}
}
if (validationError = false) {
JOptionPane.showMessageDialog(null, "Your order has been submitted!");
}
System.exit(0);
So basically you have a death trap, there is simply no way to escape...
Let's take another approach. Rather than using a hard-loop, like for or while, we can create a soft loop, whereby, each time the method is executed and the form is invalid, we update a counter, until that counter runs out...
// How many times retries has the user used...
private int retries = 0;
/*...*/
public void actionPerformed(ActionEvent e) {
validationError = (fNameInput.getText().equals("")
|| miInput.getText().equals("")
|| lNameInput.getText().equals("")
|| streetAddressInput.getText().equals("")
|| cityInput.getText().equals("")
|| stateInput.getText().equals("")
|| zipInput.getText().equals("")
|| phoneInput.getText().equals(""));
if (validationError) {
retries++;
if (retries < 3) {
JOptionPane.showMessageDialog(this, "Please complete each field within the order form.");
} else {
JOptionPane.showMessageDialog(this, "You've used up all your tries...");
System.exit(0);
}
} else {
JOptionPane.showMessageDialog(this, "Your order has been submitted!");
System.exit(0);
}
}
You may also like to have a read of Validating Input from the How to use the focus subsystem tutorial...

Related

JPanel doesn't wait for user input before moving on

I'm trying to make a program that will do some fairly simple calculations in a JPanel. One of the requirements is that it will repeat until the user says otherwise. Unfortunately when the JPanel opens it does not wait for any user input, but instead moves right on to the next thing (as I have yet written the part that asks the user if he would like to continue or quit, it's currently in an infinite while loop which means that new JPanels just keep opening continually until I stop the program). My question is: Why isn't the program waiting until the user presses the Okay button to move on?
Here is my main():
public class Driver extends JFrame{
public static void main(String args[]){
do{
new GUI();
while (!GUI.isButtonPressed()){
}
//int choice = JOptionPane.showConfirmDialog(null, "Default tax rate is 7.5%\nDefault discount rate is 10%.\nKeep these default values?", "Choose an Option", JOptionPane.YES_NO_OPTION);
//switch (choice){
//case JOptionPane.YES_OPTION: {
//SaleItem newItem = new SaleItem();
//break;
//}
//case JOptionPane.NO_OPTION: {
//new GUI();
//break;
//}
//}
}while(true);
}
and here is my GUI:
import javax.swing.*;
import java.awt.event.*;
public class GUI extends JFrame {
JPanel panel;
JLabel priceLabel;
JLabel discountLabel;
JLabel taxLabel;
JTextField taxTextField;
JTextField priceTextField;
JTextField discountTextField;
JButton okayButton;
JButton defaultsButton;
final int WINDOW_WIDTH = 300;
final int WINDOW_HEIGHT = 250;
boolean buttonPressed = false;
public boolean isButtonPressed() {
return buttonPressed;
}
public void setButtonPressed(boolean buttonPressed) {
this.buttonPressed = buttonPressed;
}
public GUI(){
super("Item Properties");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
private void buildPanel(){
priceLabel = new JLabel("Enter the item price:");
priceTextField = new JTextField(10);
discountTextField = new JTextField(10);
discountLabel = new JLabel("Enter the discount percent:");
taxLabel = new JLabel("Enter the tax percent:");
taxTextField = new JTextField(10);
okayButton = new JButton("Okay");
okayButton.addActionListener(new ButtonListener());
defaultsButton = new JButton("Use Defaults");
defaultsButton.addActionListener(new ButtonListener());
panel = new JPanel();
panel.add(priceLabel);
panel.add(priceTextField);
panel.add(discountLabel);
panel.add(discountTextField);
panel.add(taxLabel);
panel.add(taxTextField);
panel.add(okayButton);
panel.add(defaultsButton);
}
private class ButtonListener implements ActionListener {
private boolean buttonPressed = false;
public void actionPerformed(ActionEvent event){
GUI.setButtonPressed(true);
SaleItem newItem = new SaleItem(Double.parseDouble(priceTextField.getText()), Double.parseDouble(discountTextField.getText()), Double.parseDouble(taxTextField.getText()));
}
}
The stuff about getButtonPressed() and isButtonPressed() and all that was me trying (unsuccessfully) to solve the problem on my own.
Thanks in advance for any help!
Unfortunately when the JPanel opens it does not wait for any user input,
Panels don't open. You add a panel to a frame or dialog. If you want something to "open" or "popup" then you use a JDialog.
SaleItem newItem = new SaleItem(...);
SaleItem should be a modal JDialog. Then the dialog will not close until the user clicks on button that you create to close the dialog. A dialog is created exactly the same way as you create a JFrame.

Using Enter key to use JButton instead of just mouse click?

How would one bind the "Enter" key on a keyboard to press a JButton? Currently trying to figure this out but have no idea on what to do.
Here is my code for reference. What it's supposed to do is create a guessing game (which it does) but I want to add the ability to press enter to click the "Enter" button (jButtonEnter in this case).
package day21;
import java.awt.*;
import java.awt.event.*;
//import java.applet.*;
import javax.swing.*;
//import javax.swing.border.*;
public class Day21 extends JApplet implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
//All important Variables
JTextArea outTextArea = new JTextArea(10,20);
JScrollPane scroller = new JScrollPane(outTextArea);
static int GuessMe = (int) Math.ceil(Math.random()*1000);//randomizes the number
JPanel jPanelTop = new JPanel();
JPanel jPanelMid = new JPanel();
JPanel jPanelLow = new JPanel();
JLabel jLabelTop = new JLabel("Guess a number between 1 and 1000");
static JTextField jTextFieldInput = new JTextField("Guess Here",25);
JButton jButtonEnter = new JButton("Enter");
JButton jButtonReset = new JButton("Reset");
JButton jButtonClose = new JButton("Close");
public void init(){
this.getContentPane().setBackground(Color.white);
this.setSize(new Dimension(400, 120));
//Top Panel
jPanelTop.setBackground(Color.cyan);
jPanelTop.setBorder(BorderFactory.createRaisedBevelBorder());
jPanelTop.setPreferredSize(new Dimension(14, 40));
jPanelTop.setToolTipText("Top Panel");
this.getContentPane().add(jPanelTop, BorderLayout.NORTH);
jPanelTop.add(jLabelTop);
//Middle Panel
jPanelMid.setBackground(Color.orange);
jPanelMid.setBorder(BorderFactory.createRaisedBevelBorder());
jPanelMid.setPreferredSize(new Dimension(14, 40));
jPanelMid.setToolTipText("Center Panel");
this.getContentPane().add(jPanelMid, BorderLayout.CENTER);
jPanelMid.add(jTextFieldInput);
jPanelMid.add(jButtonEnter);
jButtonEnter.addActionListener(this);
//Lower Panel
jPanelLow.setBackground(Color.black);
jPanelLow.setBorder(BorderFactory.createRaisedBevelBorder());
jPanelLow.setPreferredSize(new Dimension(14, 40));
jPanelLow.setToolTipText("Lower Panel");
this.getContentPane().add(jPanelLow, BorderLayout.SOUTH);
jPanelLow.add(jButtonReset);
jPanelLow.add(jButtonClose);
jButtonClose.addActionListener(this);
jButtonReset.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
double input = 0;
boolean Error = false;
String ErrorMSG = "Error: Please Enter a Number";
try{
input = Double.parseDouble(jTextFieldInput.getText().trim());;
}
catch(NumberFormatException n){
Error = true;
}
if(Error){
JOptionPane.showMessageDialog(rootPane, ErrorMSG); //If variable entered is not a number
}
String correctAnswer = "Hooray! You guessed Correctly! \n Press Reset to play again";
String tooHigh = input + " is too high";
String tooLow = input + " is too low";
if(!Error){
if(e.getSource() == jButtonEnter){
if (input == GuessMe){
jPanelLow.setBackground(Color.green);
JOptionPane.showMessageDialog(rootPane, correctAnswer);
}
if (input > GuessMe){
jPanelLow.setBackground(Color.red);
JOptionPane.showMessageDialog(rootPane, tooHigh);
}
if (input < GuessMe){
jPanelLow.setBackground(Color.red);
JOptionPane.showMessageDialog(rootPane, tooLow);
}
}
}
if(e.getSource() == jButtonReset){
Day21.reset(); //runs the reset() method which resets the window back to it's normal state
}
if(e.getSource() == jButtonClose){
System.exit(1); //exits the program
}
}
public static void reset(){
GuessMe = (int) Math.ceil(Math.random()*1000);//randomizes the number
jTextFieldInput.setText("Guess Here");
}
}
Check out Enter Key and Button for a discussion on this topic and a couple of solutions depending on your exact requirement:
use the root pane to set a default button
use the UIManager to have focus follow the button
use Key Bindings to invoke the default Action
Define a method - processEnterButton() and put all the necessary logic there. Call the method from actionPerformed() if the button was clicked. Also define key binding for the ENTER key and call the processEnterButton() from the binding as well.

Java GUI Variables Problems

I seem to have set up something wrong in the action listener for the Create Button handler. When I tried to get the value of the text field nameTF I get a null pointer error. I tried to imitate your code for the calculator, and the Exit Button Handler works well. I know that pressing the Create button invokes the handler but the statement
inName = nameTF.getText();
gives the error message.
The complete text of the listener is
private class CreateButtonHandler
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String inName, inType; //local variables
int inAge;
Dog arf;
inName = nameTF.getText();
inType = typeTF.getText();
inAge = Integer.parseInt( ageTF.getText() );
//System.out.println("Inside CreateButtonHandler");
System.out.println(inName);
arf = new Dog(inName, inType, inAge);
System.out.println(arf.toString () );
}
}
and the whole program is below. Any help/explanation/suggestion would be very welcome.
import javax.swing.*; // import statement for the GUI components
import java.awt.*; //import statement for container class
import java.awt.event.*;
public class DogGUI //creation of DogGUI clas
{
private JLabel nameL, typeL, ageL, outtputL;
private JTextField nameTF, typeTF, ageTF;
private JButton createB, exitB;
CreateButtonHandler cbHandler;
ExitButtonHandler ebHandler;
public void driver () //creates everything
{
//create the window
JFrame DogInfo = new JFrame ("Dog GUI");
DogInfo.setSize(400,300); //set the pixels for GUI
DogInfo.setVisible(true); // set visibility to true
DogInfo.setDefaultCloseOperation(DogInfo.EXIT_ON_CLOSE); // when closed JFrame will disappear
//layout
Container DogFields = DogInfo.getContentPane();
DogFields.setLayout(new GridLayout(5,2));
// setting labels for GUI
nameL = new JLabel ("Enter name of Dog: ",
SwingConstants.RIGHT);
typeL = new JLabel ("Enter the type of the Dog: ",
SwingConstants.RIGHT);
ageL = new JLabel ("Enter the age of the Dog: ",
SwingConstants.RIGHT);
outtputL = new JLabel ("Dog Information: ",
SwingConstants.RIGHT);
//Buttons
JButton createB, exitB; //creating button for creation of Dog and button to exit
createB = new JButton("Create Dog");
exitB = new JButton("Exit");
//text fields
JTextField nameTF, typeTF, ageTF, outtputTF;
nameTF = new JTextField(10);
typeTF = new JTextField(15);
ageTF = new JTextField(5);
outtputTF = new JTextField(25);
outtputTF.setEditable(false); //this TF is to display this output
//Lables and Textfields
DogInfo.add(nameL);
DogInfo.add(nameTF);
DogInfo.add(typeL);
DogInfo.add(typeTF);
DogInfo.add(ageL);
DogInfo.add(ageTF);
DogInfo.add(outtputL);
DogInfo.add(outtputTF);
//Buttons
DogInfo.add(createB);
DogInfo.add(exitB);
//Instantiate Listeners
cbHandler = new CreateButtonHandler();
ebHandler = new ExitButtonHandler();
//Register Listeners
createB.addActionListener(cbHandler);
exitB.addActionListener(ebHandler);
DogInfo.setVisible(true);
}
//run the program from main, instantiate class, invoke driver() method
public static void main(String[] args)
{
DogGUI d = new DogGUI();
d.driver();
}
// class to actually handle Dog creation
private class CreateButtonHandler
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String inName, inType; //local variables
int inAge;
Dog arf;
inName = nameTF.getText();
inType = typeTF.getText();
inAge = Integer.parseInt( ageTF.getText() );
//System.out.println("Inside CreateButtonHandler");
System.out.println(inName);
arf = new Dog(inName, inType, inAge);
System.out.println(arf.toString () );
}
}
private class ExitButtonHandler
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("inside exit button");
System.exit(0);
} // end method actionPerformed
}
}
You have a local variable in the driver() method called nameTF that is hiding that field (same for some other variables).
JTextField nameTF, typeTF, ageTF, outtputTF;
nameTF = new JTextField(10);
Remove the declaration of those fields since they are already declared as instance fields.
private JTextField nameTF, typeTF, ageTF;
(probably not outtputTF, depending on what you want to do)

How do I store information from the textFields?

Right now, I'm just testing the to make sure the button works...but this is my code for an applet that expands a binomial using Pascal's triangle! I have the equations for the actually figuring out part, I just need to know how to store the information from the JTextFields! Thanks!
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.Action;
public class BinomialExpander extends JApplet implements ActionListener
{
JLabel welcome;
JLabel directions;
JLabel example;
JLabel instructions;
JLabel startOfBinomial;
JLabel plusSign;
JLabel forExponent;
JLabel endOfBinomial;
JTextField txtFirst;
JTextField firstVar;
JTextField txtSecond;
JTextField secondVar;
JTextField exp;
JLabel lblExpanded;
JLabel outputExpanded;
double degreesFahrenheit;
FlowLayout layout;
Timer timer;
Button compute;
private int[] pascal1 = {1,1};
private int[] pascal2 = {1,2,1};
private int[] pascal3 = {1,3,3,1};
private int[] pascal4 = {1,4,6,4,1};
private int[] pascal5 = {1,5,10,10,5,1};
private int[] pascal6 = {1,6,15,20,15,6,1};
private int[] pascal7 = {1,7,21,35,35,21,7,1};
private int[] pascal8 = {1,8,28,56,70,56,28,8,1};
private int[] pascal9 = {1,9,36,84,126,84,36,9,1};
private int[] pascal10 = {1,10,45,120,210,120,45,10,1};
public void init()
{
Container c = getContentPane();
c.setBackground(Color.cyan);
layout = new FlowLayout();
layout.setAlignment(FlowLayout.LEFT);
c.setLayout(layout);
setSize(500,175);
welcome = new JLabel("Welcome to the Binomial Expander Applet!");
directions = new JLabel("Enter binomial in the form: '(number)(variable) + (number)(variable)^exponent'.");
example = new JLabel("Example: (4a + 2)^2.");
// instantiate JLabel object for Degrees Fahrenheit
instructions = new JLabel("Enter the first number of your binomial(if there is a variable, add it into the second box):");
// instantiate JTextField object for the degrees fahrenheit
startOfBinomial = new JLabel(" (");
txtFirst = new JTextField(4);
// instantiate JLabel object for Degrees Celesius
firstVar = new JTextField(4);
plusSign = new JLabel(" + ");
txtSecond = new JTextField(4);
secondVar = new JTextField(4);
endOfBinomial = new JLabel(")");
forExponent = new JLabel("^");
forExponent.setFont(new Font("Times New Roman", Font.BOLD, 9));
exp = new JTextField(2);
compute = new Button("Compute!");
compute.addActionListener(this);
lblExpanded = new JLabel("Your expanded binomial is: ");
// JLabel to display the equivalent degrees Celsius
outputExpanded = new JLabel("");
c.add(welcome);
c.add(directions);
c.add(example);
c.add(instructions);
c.add(startOfBinomial);
//CALL the addActionListener() method on the JTextField object
// for the degrees Fahrenheit
txtFirst.addActionListener(this);
// Add the textbox the celsius label and output label
c.add(txtFirst);
c.add(firstVar);
c.add(plusSign);
c.add(txtSecond);
c.add(secondVar);
c.add(endOfBinomial);
c.add(forExponent);
c.add(exp);
c.add(compute);
c.add(lblExpanded);
c.add(outputExpanded);
// timer = new Timer(1, this);
// timer.start();
}
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == compute)
{
outputExpanded.setText(expand());
}
}
public String expand()
{
String x = "callingComputing";
return x;
}
}
yourTextField.getText() returns a String you can use as you would any other String, store it in an array, teach it to sing, fly and enjoy life.
Conversely, you can use yourTextField.setText() to display stuff in your JLabel, textfield etc.
JTextField extends JTextComponent, which has API to deal text manipualtion.
As suggested by other answers use setText to replace the current text with new text.
Also read the official tutorial to understand How to Use Text Fields
JTextField txtName = new JTextField();
JButton btn = new JButton();
in the action performed method add this
String name = txtname.getText();
this statement returns the text that is entered in the text field the second before you click the button
You create a class where you'll store the data, and create an object of that in the Frame class, i.e. the class that'll provide the GUI to the data class, then in the action listener of the submit button of the frame assign the getText() returned string to the object's field
for eg: you want to take input name and age from the text field,
create a Person class
public class Person{
public String name;
public int age;
}
now create a GUI class
public PersonFrame extends JFrame{
public person;
public PersonFrame(){
person = new Person();
JTextField txtName = new JTextField();
JButton btn = new JButton();
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
person.name = txtName.getText();
person.age = Integer.parseInt(txtAge.getText()); //as the textfield returns a String always
}
});
}
}
and avoid using
if (event.getSource() == compute)
{
outputExpanded.setText(expand());
}
If you have 100 button it'll be foolish to write nested if-else statements to check which button generated the event!!
remember that swing is designed for providing the user interface and you need an object of a class for storing the data!
for java tutorial visit here

Clearing JTextfields to write multiple data to txt file

excuse the probably simple question (and the terrible layout methods). The code I have successfully writes inputted data to a txt file and on clicking "submit" closes the input window, leaving the "menu" open, with options to add a user (this code) or search properties (unrelated). I can enter one set of details to the txt file with no problem, but when reopening the AddUser window, no matter what is typed in to the boxes the same data is inputted into the file as the previous time, unless the program is closed. I think it has something to do with clearing some variable before reopening the window (as tried towards the bottom) however i haven't had any luck.. How do I go about it? Thanks
AddUser.java
package assignment;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.io.*;
import java.lang.*;
public class AddUser extends JFrame {
//Declare the array values
private String[] Name;
private String[] Username;
private String[] Password;
private String[] StaffID;
public String inputStaff;
public String inputUser;
public String inputPass;
public String inputID;
static public String inputData;
//Declare Text Fields
public JTextField Field1;
public JTextField Field2;
public JTextField Field3;
public JTextField Field4;
public JTextField Field5;
//Declare Labels
private JLabel Label;
private JLabel Label1;
private JLabel Label2;
private JLabel Label3;
private JLabel Label4;
private JLabel Label5;
private JLabel Space1;
private JLabel Space2;
public AddUser() {
super("Add New Agent"); //Window Title
setLayout(new FlowLayout(FlowLayout.LEFT)); //Set Layout Type as FlowLayout
Label = new JLabel("Enter the Member of Staff's Details");
Label1 = new JLabel("Staff Name"); //Label Values
Label2 = new JLabel("Username");
Label3 = new JLabel("Password");
Label4 = new JLabel("Confirm Password");
Label5 = new JLabel("Staff ID");
Space1 = new JLabel(" ");
Space2 = new JLabel(" ");
Field1 = new JTextField (10); //Create the Text Fields and Option Blocks & Arguments
Field2 = new JTextField (10);
Field3 = new JTextField (10);
Field4 = new JTextField (10);
Field5 = new JTextField (4);
//Add the labels, textfields and option blocks to the JFrame
add (Label); add(Space1); add (Label1); add (Field1); add (Label2); add (Field2); add (Label3); add (Field3); add (Label4);
add (Field4); add (Label5); add (Field5); add (Space2);
JButton button1 = new JButton("Submit"); //Add "Search" button to JFrame
add (button1);
onClick handler = new onClick();
button1.addActionListener(handler);
}
private class onClick implements ActionListener{
public void actionPerformed(ActionEvent event){
//Action to be performed
//Attempt to clear the fields
inputStaff = ("");
inputUser = ("");
inputPass = ("");
inputID = ("");
inputStaff = Field1.getText();
inputUser = Field2.getText();
inputPass = Field3.getText();
inputID = Field5.getText();
inputData = inputStaff + " " + inputUser + " " + inputPass + " " + inputID;
WriteFile Write = new WriteFile(); //Create instance of write-to-file
setVisible(false);
//Close the window on clicking submit
}
}
}
The write to file code (WriteFile.java) is as follows;
package assignment;
import java.io.*;
public class WriteFile{
static String data = AddUser.inputData;
BufferedWriter out;
public WriteFile(){
try {
out = new BufferedWriter(new FileWriter("AddUser.txt", true));
out.write(data);
out.newLine();
out.close();
}
catch(IOException e)
{
System.out.println("There was a problem:" + e);
}
}
}
This way to achieve that lacks in a few manners, please consider the following:
public static void WriteFile(String data){
try {
out = new BufferedWriter(new FileWriter("AddUser.txt", true));
out.write(data);
out.newLine();
out.close();
}
catch(IOException e)
{
System.out.println("There was a problem:" + e);
}
}
And call it like that:
WriteFile.WriteFile(inputData);
I would also change the name of the method, but I tried to keep it as close as possible to the original code.
Don't access fields of a class in this way SomeClass.someField, and try to avoid static members when they are not needed.
The line
static String data = AddUser.inputData;
is only run once, when the class is loaded. That is the case with all static variables. (You appear to be thinking along the lines of "dataflow programming" or spreadsheets, but Java doesn't work like that. Or you might be thinking that String objects are updateable, but they're not - they're immutable.)
This is a terrible way to implement data passing between classes, and as you can see, it doesn't work. It wouldn't even work once if for some reason that class happened to be loaded earlier than it was.

Categories

Resources