Store and Restore previous userinput texfield - java

I have two Textfields that can be input by user and will be used for calculation later (Number only), lets say InputX and InputY. And two radio button, Rad1 and Rad2.
When user Choose Rad1, Both TextFiled are Input-able by User and Stored to memory/variable when user input in it. But when user choose Rad2, only InputX is available and InputY is InputY.setText("InputX only"). If User choose the Rad1 back, i want to restore the value that user input to the InputY previously, not showing "InputX Only".
So, My Question is: How to get the previous value from userinput when user choose the Rad1 back, since its has been overridden by Rad2 InputY.setText("InputX Only") ?
Please create a full code example with all possible/alternative code, i'm new in java.
Note: Im using Netbeans v8.0.2 and create form using built in form builder/designer

public class InputValidator extends javax.swing.JFrame {
private static final String INPUT_X_ONLY = "InputX Only";
private String temp = "";
public InputValidator() {
initComponents();
jRadioButton1.setSelected(true);
buttonGroup1.add(jRadioButton1);
buttonGroup1.add(jRadioButton2);
jRadioButton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
jTextField2.setEditable(true);
jTextField2.setText(temp);
}
});
jRadioButton2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
jTextField2.setEditable(false);
temp = jTextField2.getText();
jTextField2.setText(INPUT_X_ONLY);
}
});
}

Related

How can I set up a JFrame button to open another JFrame, and then receive information once the second jframe is closed?

This is part of a project for school, and I'm stuck and need someone to bounce ideas off of. I have a game where there is an option to sign up or sign in for a machine-local game so a record can be kept of the person's scores. The game is run from a base GUI JFrame, and I want to make buttons to bring up secondary windows for the person to sign in or sign up, before closing out of them. I need to pass the validated username back to the initial GUI/game class so I can store it for the following game so the game score can be added under that user. I just need to pass the username back and I'm not sure how to go about it. This is the main GUI code up to where I'm having my issue:
public class MathFactsGUI extends JFrame
{
// instance variables
private JTextField problemJTextField, answerJTextField;
private JLabel equalJLabel;
private JButton additionJButton, multiplicationJButton;
private JButton signupJButton, signinJButton;
private JButton submitJButton;
private JLabel scoreJLabel,resultJLabel;
//private JButton reviewButton;
private String username;
private Userbase userbase;
private JLabel introJLabel;
Quiz quiz;
/**
* Constructor for objects of class MathFactsGUI
*/
public MathFactsGUI()
{
super("Math Facts Quiz");
userbase = Userbase.getUserbase();
username = "guest";
/* code here has been removed to be abbreviated */
// Action listener for buttons
additionJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
quiz = new Quiz('+');
problemJTextField.setText(quiz.getCurrentProblem());
additionJButton.setEnabled(false);
multiplicationJButton.setEnabled(false);
signupJButton.setEnabled(false);
signinJButton.setEnabled(false);
}
});
multiplicationJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
quiz = new Quiz('x');
problemJTextField.setText(quiz.getCurrentProblem());
additionJButton.setEnabled(false);
multiplicationJButton.setEnabled(false);
signupJButton.setEnabled(false);
signinJButton.setEnabled(false);
}
});
signinJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JDialo
}
});
signupJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
MathFactsSignUpGUI signUpGUI = new MathFactsSignUpGUI();
gui.setVisible(true);
}
});
}
This is the JFrame I wrote for the sign-up button:
public class MathFactsSignUpGUI extends JDialog {
private JTextField usernameJTextField, userPassJTextField, userFirstNameJTextField;
private JLabel usernameJLabel, userPassJLabel, userFirstNameJLabel;
private JButton submitJButton;
private String username;
private String userPass;
private String userFirstName;
public MathFactsSignUpGUI(){
usernameJLabel = new JLabel("Username:");
usernameJTextField = new JTextField();
userPassJLabel = new JLabel("Password:");
userPassJTextField = new JTextField();
userFirstNameJLabel = new JLabel("Player First Name:");
userFirstNameJTextField = new JTextField();
Box usernameBox = Box.createHorizontalBox();
usernameBox.add(usernameJLabel);
usernameBox.add(usernameJTextField);
Box userPassBox = Box.createHorizontalBox();
userPassBox.add(userPassJLabel);
userPassBox.add(userPassJTextField);
Box userFirstBox = Box.createHorizontalBox();
userFirstBox.add(userFirstNameJLabel);
userFirstBox.add(userFirstNameJTextField);
submitJButton = new JButton("Submit");
submitJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
username = usernameJTextField.getText();
userPass = userPassJTextField.getText();
userFirstName = userFirstNameJTextField.getText();
if (!checkValid(username) || !checkValid(userPass) || !checkValid(userFirstName)){
JOptionPane.showMessageDialog(null, "All fields must have values.");
} else if (Userbase.getUserbase().userExist(username)==true){
JOptionPane.showMessageDialog(null, "Username is taken, please choose another.");
} else {
Userbase.getUserbase().addUser(username, new User(username, userPass, userFirstName));
MathFactsGUI.setUsername(username);
}
}
});
JPanel mfSignUp = new JPanel()
mfSignUp.setLayout(new GridLayout(0,1));
mfSignUp.add(usernameBox);
mfSignUp.add(userPassBox);
mfSignUp.add(userFirstBox);
mfSignUp.add(submitJButton);
}
public String signIn(){
return username;
}
public boolean checkValid(String a){
if (a == null || a.length() == 0){
return false;
} else {
return true;
}
}
}```
I was thinking of implementing a WindowListener action for when the sign-up/sign-in frames close, but I'm not sure that will work. I was also looking into JDialog, but I'm not sure if it has the layout/text verification properties I need.
Use a JOptionPane. It will simplify your layout without the need for creating a separate JFrame and easily pass values back to wherever it was called from. You can then make it check for valid username when you click OK.
Try this site. It gives a good rundown with example images
First you need to understand that this is an object, so you can create some global variables which will contains this information(username,password,Nickname), i recommend to pull info from MathFactsSignUpGUI by using ScheduledExecutorService. It will pull info from this sign up gui in every 100ms, than it will destroy itself, here is an example:
MathFactsSignUpGUI su = new MathFactsSignUpGUI ();
su.setVisible(true);
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule(new Runnable(){
public void run(){
if(!su.username.isEmpty() && !su.userPass.isEmpty() && !su.userFirstName.isEmpty() ){
if(su.isLogin){ //if player is loggining
//do something here
}else{//if user is registered
//do something here
}
System.out.println("Check complete");
service.shutdown();//to destroy this service after recieving the data
}
}
}, 100, TimeUnit.MICROSECONDS);

Opening two new JFrames! Why is this happening?

This code checks the username and password then opens a new JFrame if they are correct. However, two identical JFrames are opened and I am clueless as to the reason.
public void checkLogin(String x, String y){
if (x.equals(loginCredentials[0]) && y.equals(loginCredentials[1])){
dispose();
task1ExampleSC o2 = new task1ExampleSC();
o2.setVisible(true);
o2.setSize(600,650);
o2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}else{
System.exit(0);
}
}
private class loginAC implements ActionListener{
public void actionPerformed(ActionEvent e){
String usernameText,passwordText;
if (e.getSource()==login){
usernameText = username.getText();
passwordText = password.getText();
checkLogin(usernameText,passwordText);
}else if(e.getSource()==cancel){
System.exit(0);
}
}
}
You don't show how you add the listeners to the buttons, but presumably you have something like this:
login.addActionListener(new loginAC());
Does this line appear more than once in your code? Or is it possible that this line runs more than once? If so, more than one listener will be added to the login button, meaning that more than one ActionEvent will be dispatched when the login button is clicked; and if the username and password are both correct, that will result in more than one new window opening.

JButton repeating action depending on how many times pressed

I'm building a simple program in Java which gets a balance (mine is set to $8000). I want to deposit money into that so I have a UI with 0-9 buttons, a textarea and a deposit button, so if the user wanted to deposit $100 he would press 1 once then 0 twice. All that works and it deposits for the first time, but the second time it deposits the double amount of money. If I press my deposit button 10 times and select $1 then press enter it deposits $10. I think the structure of my btn action listener might be wrong.
Any ideas?
Code:
btnDeposit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label1.setText("Deposit: How much would you like to deposit?");
btnWithdraw.setEnabled(false);
btnBalance.setEnabled(false);
btnEnter.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//convert text area into double
double depositNumber = Double.parseDouble(ta.getText());
sav.deposit(depositNumber);
btnWithdraw.setEnabled(true);
btnBalance.setEnabled(true);
}
});
}
});
My deposit function is:
public void deposit(double depositAmount) {
balance += depositAmount;
System.out.println("Your updated balance is: " + balance);
}
I also noticed that it doesn't go back to where it started, if I keep clicking on Enter it keeps adding and adding...
Button that clear my text area:
btnClear.addActionListener(new new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae) {
ta.setText("");
}
});
The problem is called out in the comment section. You are declaring multiple listeners which are calling the respective deposit() or withdraw() method every time you perform an action.
To avoid this. You can set one listener class to all of your buttons like this.
Create an inner class
private class MySpecialListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent ae) {
if(e.getSource == btnDesposit) // do stuff and so on
}
}
and add the listener like this
MySpecialListener myListener = new MySpecialListener();
btnDeposit.addActionListener(myListener);
The above requires you to re-write your code, but it has a better structure then your current one.
To fix your current problem you can remove the last listener like this:
for(ActionListener al : btnEnter.getActionListeners())
btnEnter.removeActionListener(al)
btnEnter.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//convert text area into double
double depositNumber = Double.parseDouble(ta.getText());
sav.deposit(depositNumber);
btnWithdraw.setEnabled(true);
btnBalance.setEnabled(true);
}
});

Check user has entered the correct number of symbols in a text field

I have small Java GUI program (screenshot below). One of the values is "Passport Number".
This field should contain 11 symbols. Once the user has entered a value in this field, I want to check the correct number of symbols are in place and set string "error" in Label item "Label1" if not.
I tried this:
private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {
String error;
if(passportn.length()!=11) {
error="error";
label1.setText(error);
}
}
This works but only when a button is pressed. Instead I want this to happen as the user enters passport number.
1) You can use InputVerifier like next :
final JLabel l = new JLabel(" ");
JTextField field = new JTextField();
field.setInputVerifier(new InputVerifier() {
#Override
public boolean verify(JComponent arg0) {
Boolean b = ((JTextField)arg0).getText().length() == 11;
if(!b){
l.setText("error");
} else {
l.setText("accepted");
}
return b;
}
});
with that before you enter 11 characters you cant to set focus to another component.
2) Use DocumentListener, for example :
final JLabel l = new JLabel(" ");
JTextField field = new JTextField();
field.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent arg0) {
validate(arg0);
}
#Override
public void insertUpdate(DocumentEvent arg0) {
validate(arg0);
}
#Override
public void changedUpdate(DocumentEvent arg0) {
validate(arg0);
}
private void validate(DocumentEvent arg0){
Boolean b = arg0.getDocument().getLength() == 11;
if (!b) {
l.setText("error");
} else {
l.setText("accepted");
}
}
});
In that case DcumentListener will validate each character entered or removed, and then change text in JLabel.
You can do this using a JFormattedText field, there is a full tutorial here:
http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html
and javadoc here:
http://docs.oracle.com/javase/7/docs/api/javax/swing/JFormattedTextField.html
But in brief it is a way of setting up a text field and then specifying what the allowed data within that text field are and also what to do when someone tries to enter invalid data.

Passing input from one frame to another(JAVA)

Here's the thing...
I have 2 GUI programs.
A Menu Program,which is basically a frame with buttons of food items,the buttons when clicked
opens this other program,an Input Quantity Program,which is a frame with a text field,buttons for numbers,buttons for Cancel and Confirm. The quantity that is confirmed by the user will be accessed by the menu program from the Input Quantity Program to be stored in a vector so that every time a user wants to order other food items he will just click another button and repeat the process.
Now I've coded the most part and got everything working except one thing,the value returned by the Input Quantity Program has this delay thing.
This is what I do step by step:
1)Click a food item in Menu,it opens the Input Quantity window.
2)I input the number I want,it displayed in the text box correctly.
3)I pressed confirm which will do 3 things,first it stores the value of the text field to a variable,second it will call the dispose() method and third a print statement showing the value of the variable(for testing purposes).
4)The menu program then checks if the user has already pressed the Confirm button in the Input program,if true it shall call a method in the Input program called getQuantity() which returns the value of the variable 'quantity' and store it in the vector.
5)After which executes another print statement to check if the passed value is correct and then calls the method print() to show the ordered item name and it's recorded quantity.
Here are the screenshots of the GUI and the code will be below it.
ActionPerformed method of the CONFIRM BUTTON in the Input Quantity Program:
private void ConfirmButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
confirmed = true;
q= textField.getText().toString();
quantity =Integer.parseInt(q) ;
System.out.println("getQTY method inside Input Quantity Interface:" +getQuantity());
System.out.println("Quantity from confirmButton in Input Quantity Interface actionPerformed: "+quantity);
//getQuantity();
}
ACTION LISTENER CLASS of the MENU ITEM BUTTONS in MENU PROGRAM which does step 2 above:
class f implements ActionListener {
#Override
public void actionPerformed(ActionEvent e)
{
inputGUI.setVisible(true);
int q =0;
q=inputGUI.getQuantity(); //call method to get value from Input Program
System.out.println("Quantity inside Menu actionperformed from AskQuantity interface: "+q);
orderedQuantity.add(q); //int vector
textArea.append("\n"+e.getActionCommand()+"\t"+ q);
orderedItems.add(e.getActionCommand()); //String vector
print();
/*
System.out.println("Enter QTY: ");
int qty = in.nextInt();
orderedQuantity.add(qty);
print();*/
}
Here are screenshots of the print statements in the console:
Here I first ordered Pumpkin Soup,I entered a quantity of 1
Here I ordered seafood marinara and entered a quantity of 2
Here I ordered the last item,pan fried salmon and entered a quantity of 3
As you can see the first recorded quantity is 0 for the first item I ordered then when I added another item,the quantity of the first item gets recorded but the 2nd item's quantity is not recorded..same goes after the third item... and the quantity of the 3rd item is not recorded even if the program terminates :(
How can I solve this problem?
I think I see your problem, and in fact it stems directly from you're not using a modal dialog to get your input. You are querying the inputGUI before the user has had a chance to interact with it. Hang on while I show you a small example of what I mean...
Edit
Here's my example code that has a modal JDialog and a JFrame, both acting as a dialog to a main JFrame, and both using the very same JPanel for input. The difference being the modal JDialog will freeze the code of the main JFrame at the point that it has been made visible and won't resume until it has been made invisible -- thus the code will wait for the user to deal with the dialog before it progresses, and therein holds all the difference.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DialogExample {
private static void createAndShowGui() {
JFrame frame = new JFrame("Dialog Example");
MainPanel mainPanel = new MainPanel(frame);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MainPanel extends JPanel {
private InputPanel inputPanel = new InputPanel();
private JTextField responseField = new JTextField(10);
private JDialog inputDialog;
private JFrame inputFrame;
public MainPanel(final JFrame mainJFrame) {
responseField.setEditable(false);
responseField.setFocusable(false);
add(responseField);
add(new JButton(new AbstractAction("Open Input Modal Dialog") {
#Override
public void actionPerformed(ActionEvent e) {
if (inputDialog == null) {
inputDialog = new JDialog(mainJFrame, "Input Dialog", true);
}
inputDialog.getContentPane().add(inputPanel);
inputDialog.pack();
inputDialog.setLocationRelativeTo(mainJFrame);
inputDialog.setVisible(true);
// all code is now suspended at this point until the dialog has been
// made invisible
if (inputPanel.isConfirmed()) {
responseField.setText(inputPanel.getInputFieldText());
inputPanel.setConfirmed(false);
}
}
}));
add(new JButton(new AbstractAction("Open Input JFrame") {
#Override
public void actionPerformed(ActionEvent e) {
if (inputFrame == null) {
inputFrame = new JFrame("Input Frame");
}
inputFrame.getContentPane().add(inputPanel);
inputFrame.pack();
inputFrame.setLocationRelativeTo(mainJFrame);
inputFrame.setVisible(true);
// all code continues whether or not the inputFrame has been
// dealt with or not.
if (inputPanel.isConfirmed()) {
responseField.setText(inputPanel.getInputFieldText());
inputPanel.setConfirmed(false);
}
}
}));
}
}
class InputPanel extends JPanel {
private JTextField inputField = new JTextField(10);
private JButton confirmBtn = new JButton("Confirm");
private JButton cancelBtn = new JButton("Cancel");
private boolean confirmed = false;
public InputPanel() {
add(inputField);
add(confirmBtn);
add(cancelBtn);
confirmBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
confirmed = true;
Window win = SwingUtilities.getWindowAncestor(InputPanel.this);
win.setVisible(false);
}
});
cancelBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
confirmed = false;
Window win = SwingUtilities.getWindowAncestor(InputPanel.this);
win.setVisible(false);
}
});
}
public boolean isConfirmed() {
return confirmed;
}
public void setConfirmed(boolean confirmed) {
this.confirmed = confirmed;
}
public String getInputFieldText() {
return inputField.getText();
}
}
So solution: use a modal JDialog.
Suppose i am having two GUI frames f1 and f2. Now by clicking a button on f1 i want to invoke frame f2 and also sending some data from f1(frame class) to f2(frame class).
One possible way is to declare a constructor in f2 which takes the same data as parameters which i wanted to send to it from f1.Now in frame f1's coding just include these statements:
f1.setVisible(false);//f1 gets invisible
f2 newFrame=new f2(uname,pass);//uname and pass have been takenfrom f1's text fields
f2.setVisible(true);
I think this will clear up your problem.

Categories