How to wait till one of the buttons is clicked? - java

I am working on a project and have stuck at a point. I am working with Java Swing and this is the Problem:
When the user clicks on readMore button, I am creating an instance of class VerifyFF. Now, this class creates a frame which has an input field and two buttons namely cancel and continue. If the user presses cancel, then the frame disposes and nothing needs to be done. If he enters the correct password in the text field and then presses cont, I need to check whether the password is correct or not. For this I am using a boolean variable named as verified.
When the password entered is correct then the value of verified is set to true else nothing happens. The user gets and prompt of wrong password and again he can enter the correct password or can press cancel.
Now, in the class where I am creating the instance of VerifyFF class, I want to check whether the entered password was correct or not, hence I am checking for the value of variable boolean (which is also static). The trouble is, when the constructor of VerifyFF runs, there is nothing which stops the execution and waits for the user to enter something. Both the checking is done inside the function
JButton.addActionListener(new ActionListener()
{
};
The code in class instantiating the variable is:
VerifyFF vff = new VerifyFF();
if(vff.verified)
readMore();
Whenever I run this code, it doesn't waits to see whether any button is placed or not. I want to know how I can make it to wait till some button is pressed.

You don't have to wait until somebody pressed the button. Just move your
if(vvf.verified) readMode();
into your action listener for 'continue' button.

I am not sure of the problem. But maybe you should reconsider your implementation. In the constructor do just the first display then have a function that provides more whenever user clicks on more and password was correct.
You really do not need to stop constructor from being constructed, this sounds bad.
Good luck, Boro.

Your class should have a validatePassword method, which could be called on the click of the continue button.
class VerifyFF implements ActionListener {
private static final String ACTION_CONTINUE = "CONTINUE";
private JButton continueBtn = null;
private static boolean valid = false;
public VerifyFF() {
this.continueBtn = new JButton("Continue");
this.continueBtn.setActionCommand(VerifyFF.ACTION_CONTINUE);
this.continueBtn.addActionListener(this);
}
public static boolean validatePassword() {
//Validates the password field...
}
void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals(VerifyFF.ACTION_CONTINUE)) {
VerifyFF.valid = VerifyFF.validatePassword();
}
}
}
This way, the validate method is called on the press of the Continue button. and you can then do whatever you need according to the boolean 'valid'

Related

Java multiple message dialogs at the same time with focusLost event

The problem is that when i click on the surname field when the name field is empty both messages appear because the focus is lost even from surname when the message dialog appears. Is there anything i can do to make the program show the name message and the focus to stay on the name field?
I tried the .requestFocus() but it didn't work.
private void NameFieldFocusLost(java.awt.event.FocusEvent evt) {
if (NameField.getText().equals('smth')) {
JOptionPane.showMessageDialog(null, "Please put a name!","Error!", JOptionPane.INFORMATION_MESSAGE);
}
}
private void SurnameFieldFocusLost(java.awt.event.FocusEvent evt) {
if (SurnameField.getText().equals("smth")) {
JOptionPane.showMessageDialog(null, "Please put a surname!","Error!", JOptionPane.INFORMATION_MESSAGE);
}
}
First off, in the NameFieldFocusLost event: if (NameField.getText().equals('smth')) { doesn't fly. The equals() method requires a String: if (NameField.getText().equals("smth")) { or better yet...since you want to ensure a name is actually provided:
if (NameField.getText().trim().equals("")) {
There must be something we're not being shown. I don't understand why both MessageBoxes would be displaying when focus is taken away from the nameFieldFocusLost event. This shouldn't happen unless you have code somewhere moving focus around especially before your form is actually visible. The requestFocus() method should work as well and should be called directly after you display the MessageBox, for example:
private void nameFieldFocusLost(java.awt.event.FocusEvent evt) {
if (nameField.getText().trim().equals("")) {
JOptionPane.showMessageDialog(this, "Please put a name!","Error!", JOptionPane.INFORMATION_MESSAGE);
nameField.setText(""); // Clear the JTextField in case a white-space was placed there.
nameField.requestFocus(); // Force focus back onto the JTextField.
}
}
If you are moving focus to a JTextField before the parent container is visible (Form / JDialog) then you could possibly experience your particular problem.
EDIT:
Ahhh...I see the problem, thank you for the comment. Here are a few ways you can get around this dilemma:
Add a condition within the focusLost event for the next
JTextField to be in focus which will force an exit of that event
should the validation of the previously focused JTextField fail.
In your case you have a First Name text field and a Last Name text
field. In the focusLost event for the Last Name field you would have
the very first line of code being:
if (nameField.getText().trim().equals("")) { return; }
This way the remaining event code doesn't get run in the Surname
Lost Focus event unless validation for Name field is successful. The
entire Surname event code may look like this:
private void surnameFocusLost(java.awt.event.FocusEvent evt) {
if (nameField.getText().trim().equals("")) { return; }
if (surnameField.getText().trim().equals("")) {
JOptionPane.showMessageDialog(this, "Please put a last name!","Error!", JOptionPane.INFORMATION_MESSAGE);
surnameField.setText(""); // Clear the JTextField in case a white-space was placed there.
surnameField.requestFocus(); // Force focus back onto the JTextField.
}
}
An other way would be to utilize the InputVerifier
Class.
There is good example of its use in this SO
post.
Don't use the JTextField's Focus Events at all. If there is a button
that will be selected to further processing with the inputted data
then check the validation for all your JTextFields there (in the button's actionPerformed event) and force a
focus upon the field that fails (nameField.requestFocus();) for proper input.

Trying to create 3x password checker (using buttons and GUI)

Im having problems creating a GUI. I want to make a program that allows users to enter their password through buttons, and it takes 3 chances before the GUI closes. I have attempted a few different methods but cannot get it to fully work.
JTextField1 is where the instructions are shown.
JTextField2 is where the password is input (correct password should be 1234)
After putting in the wrong password for the 3rd time I want it to shut.
I think the issue is that it is taking the same password 3 times and will automatically end, but I am not sure how to fix or loop properly as I am quite new to java and gui's.
This is what I have so far:
final String PASSWORD = "1234";
int attempts = 3;
String password = "";
while (attempts-- > 0 && !PASSWORD.equals(password))
{
jTextField1.setText("Enter your password");
password = jTextField2.getText();
if (password.equals(PASSWORD))
jTextField1.setText("Welcome ");
else
jTextField1.setText("Incorrect Pin, please try again");
}
Consider these two lines:
jTextField1.setText("Enter your password");
password = jTextField2.getText();
The second line executes immediately after the first line. There is no code here which waits for the user to type anything.
Graphical user interfaces are event-based. A program must respond to events based on user behavior. It is not possible to handle GUI interactions a single sequential function.
You respond to events in Java by adding an event listener to an object which is capable of generating certain kinds of events. A JTextField fires an action event when the user presses Enter while it has focus. JButtons fire an action event when activated (by user doing a mouse press and release inside it, or by the user pressing space while it has focus).
You want to add an ActionListener only once, typically right after you create the component to which it will be added. Since the ActionListener is a separate method, you will need to keep track of your attempts in an instance field:
private static final String PASSWORD = "1234";
private int attempts = 3;
// ...
private void buildWindow() {
// ...
jTextField2 = new JTextField(20);
jTextField2.addActionListener(e -> checkPassword());
// ...
}
private void checkPassword() {
if (password.equals(PASSWORD)) {
jTextField1.setText("Welcome ");
} else if (--attempts > 0) {
jTextField1.setText("Incorrect Pin, please try again");
} else {
System.exit(0);
}
}

Problems with KeyEvent

I have a panel just with a Jtextfield that only accept numbers. So, when I press enter will load a user profile. this is just to see his profile.
What I want: When I press ENTER again all the profile will be cleared, and when I press the numbers and press ENTER again and load the profile again and again...
My problem: I pressed enter and the profile is cleared (Ok all fine), but when I enter the number and press the ENTER, The numbers are cleared and nothing happens, it is like a loop in matriculaTxt.addKeyListener(new KeyAdapter() { ... }
Sorry for my bad English.
private void matriculaTxtActionPerformed(java.awt.event.ActionEvent evt)
{
String matricula = matriculaTxt.getText().trim();
if (!matricula.matches("[0-9]+")) {
matriculaTxt.setText("");
} else {
fc = new FrequenciaController();
matriculaTxt.setEditable(false);
matriculaTxt.requestFocus();
fc.checkinManual(Integer.parseInt(matricula));
}
// the problem is here.
matriculaTxt.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
nomeTxt.setText("");
statusTxt.setText("");
imageLb.setIcon(null);
acessoLabel.setText("");
matriculaTxt.setText("");
observacaoTxt.setText("");
System.err.println("ENTER");
PendenciasTableModel ptm = new PendenciasTableModel();// vazio
pendenciasTabela.setModel(ptm);
matriculaTxt.setEditable(true);
matriculaTxt.requestFocus();
}
}
});
}
What I wanted to do was simple. The user types in the text field their numbers, pressing ENTER: their data are loaded. requestFocus() into the text field and it will not be editable anymore, because when I press Enter again the field will be editable but everything will be deleted, and so on.
First off, you should never use a KeyListener for this sort of thing. Consider instead using either a JFormattedTextField or using a DocumentFilter to prevent non-numeric entry. Next, you should use an ActionLIstener to have the JTextField accept and react to the user's pressing the Enter key.
Edit
You state:
my exact requirements is, when i press ENTER again all data will be cleaned for a new data be inserted.
Why not simply have in your JTextField's ActionLIstener:
#Override
public void actionPerformed(ActionEvent e) {
// get the text
JTextComponent textComp = (JTextComponent) e.getSource();
String text = textComp.getText();
// do what you want with text here
// clear the text
textComp.setText("");
}
Again, you should not use a KeyListener for any of this stuff.
Edit 2
If you want a multi-state action listener, one that reacts differently depending on the state of the program, then give it some if blocks to allow it to react to the state of the JTextField. If the field is empty, do one thing, if it has numbers, do another, if it has text, show a warning and clear it:
#Override
public void actionPerformed(ActionEvent e) {
// get the text
JTextComponent textComp = (JTextComponent) e.getSource();
String text = textComp.getText().trim(); // trim it to rid it of white space
if (text.isEmpty()) {
// code to show a profile
return; // to exit this method
}
// if we're here, the field is not empty
if (!text.matches("[0-9]+")) {
// show a warning message here
} else {
// numeric only data present
// do action for this state
}
// clear the text
textComp.setText("");
}
The key again is to not use a KeyListener, but rather to "listen" for the enter key press with the ActionListener only, but to react differently depending on the state of the program, here likely being depending on what content is present in the JTextField.
I think that your problem that the KeyListener it'll not trigger, it will not execute the code inside it, because whenever you press ENTER it will trigger the matriculaTxtActionPerformed then declared the KeyLister, so the ENTER will effect it.

How to make an on/off button on java?

I need a button that, when pressed, enables all the other buttons, and changes the name of a label from "Off" to "On", and when pressed again, disables all the buttons and turns the switch to "off" back again, like an on/off switch. The thing is, I can "turn it" on, but I can't turn it back off.
If Swing, then perhaps you will want to place the buttons that you wish to control into an array or an ArrayList<AbstractButton>. That way the ActionListener of the control button can simply iterate through the array or the collection with a for loop, calling setEnabled(true) or false on the buttons. Consider making the controlling button be a JCheckBox or a JToggleButton.
Note, if you use a JToggleButton, then add an ItemListener to it. If you do so, there's no need to use booleans. Just check the state of the ItemEvent passed into the ItemListener's itemStateChanged method. If the getStateChanged() returns ItemEvent.SELECTED, then iterate through your JButton collection enabling all buttons. If it returns ItemEvent.DESELECTED, do the opposite.
Also note as per Byron Hawkins's comment:
You may want to consider that the ItemListener will receive events when the button is programmatically toggled, and also when the user toggles the button. The ActionListener only gets fired on input from the human user. I've often had bugs because I picked the wrong one.
If your button is pressed down and won't pop back up, chances are you have overridden a method in JToggleButton without calling super's version of it. Instead of overriding methods, create an ActionListener and use addActionListener() to attach to the button. When your listener is notified of button actions, check whether the toggle button is up or down and setEnabled() on the other buttons accordingly.
try use this simple code, use the variable as the flag
public int status = 0; //0 = on, 1=off
public void button_clicked()
{
//on button clicked
if(status == 0)
{
//logic here
status = 1;
buttonname.setText("Off");
}
//off button clicked
else if(status == 1)
{
//logic here
status = 0;
buttonname.setText("On");
}
}
you'll need a boolean to represent the state of the button.
In other words, when your button is off (your boolean variable is false), from your onClick listener, you'll call a method "turnButtonOn()" or something of that nature.
If your boolean variable is true, then you'll call a method turnButtonOff()
public void onClick() {
if(buttonOn){
turnOff();
}
else {
turnOn();
}
buttonOn = !buttonOn;
}

How can I enable a text field when a button is clicked?

before I start, I'm a beginner programmer.
How can I enable a text field when a button is clicked.
I have two frames, one that has the JFields and the other for the exception.
When the exception occurs > setEditable(false)
but what statement should I make to enable the JFields once the user click on okay button -that i've made in the exception-?
I've tried to add static boolean to exception frame, and inside the action performed of this class I initialized that boolean to true.
in the other class, I added an if statment, if that boolean is true, then setEditable(true)
-========-
The point of this program, that when the exception occurs the user cannot enter anything in the fields until he closes the exception window.
I wish you'd help me.
With all love, programmers.
The code of action performed for THE EXCEPTION WINDOW FRAME ( having Okay button. )
public void actionPerformed(ActionEvent e){
{
allow=true; //static boolean
Container TheFrame = OKButton.getParent();
do TheFrame = TheFrame.getParent();
while (!(TheFrame instanceof JFrame));
((JFrame) TheFrame).dispose();
}
The code of action performed for THE MAIN PROGRAM (having three fields, an exception will occur once the user enters non digits )
I added some comments to clarify.
public void actionPerformed(ActionEvent event) {
try{
r =Double.parseDouble(RField.getText());
s=Double.parseDouble(SField.getText());
h=Double.parseDouble(HField.getText());
Cone C = new Cone(r,s,h);//class cone
if (event.getSource() instanceof JButton) {
JButton clickedButton = (JButton) event.getSource();
if (clickedButton == VolumeButton) {
Result.append("VOLUME = "+C.volume()+ "\n");
ifV= true;//this's for clearing the fields for new entries.
}
if (clickedButton == AreaButton) {
Result.append("SURFACE AREA = "+C.surfaceArea()+ "\n");
ifA= true;//this's for clearing the fields for new entries.
}
if(ifA&&ifV){ // clearing the fields for new entries.
SField.setText(CLEAR);
HField.setText(CLEAR);
RField.setText(CLEAR);
ifV=false; ifA= false;}
}
SList.addShape(C);
}
catch(NumberFormatException e){
//Object of type "Exception__" already created
Ex.setVisible(true);//class "Exception__" is the one i've made for Exception window
SField.setText(CLEAR);
HField.setText(CLEAR);
RField.setText(CLEAR);
SField.setEditable(false);
HField.setEditable(false);
RField.setEditable(false);
}/*here, if the user clicked on -that okay in Exception window-
and variable allow initialized to "true" those statements should extend. I guess?
- everything worked correctly except for this ?*/
if(Ex.allow){
SField.setEditable(true);
HField.setEditable(true);
RField.setEditable(true); }
}
THANK YOU ALL IT FINALLY WORKED.
I added
Ex.allow(SField,HField,RField);
to the catch.
and added this method in class Exception__:
public void allow(JTextField js,JTextField jh,JTextField jr){
HField =jh;
SField =js;
RField =jr;
}
finally, to the action performed of class Exception__:
SField.setEditable(true);
HField.setEditable(true);
RField.setEditable(true);
WOHOOOO. It feels so awesome lol. Thanks all. should I delete my question or leave it for others who might face the same problem as mine? :P
Your question needs a lot more detail. But if all you want to to show an 'exception window' and allow the user to do anything else only after she dismisses this window, I think all you need is a MessageDialog:
See JOptionPane
If you need more details to be displayed you can create your own modal JDialog.
See How to Make Dialogs
Make the text field hiden by writing:
jTextfield.setVisible(fasle);
in the constructor of your form code. than use the button event " Action -> Action Performed " and write the code:
jTextfield.setVisible(true);
and thus your text field will be visible only after the button will be clicked.

Categories

Resources