Mouse click event for JFrame change - java

I want to change a JFrame window to another one with MouseEvent. Code is below.
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
String pass;
String user;
user = txtUser.getText();
pass = txtPass.getText();
if(pass.equals("********") && user.equals("**********") )
{
??????????
}
else{
lblDisplay.setText("Please try again.");

If you need to go to another JFrame if the username and password matches, you can do as follows.
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
String pass;
String user;
user = txtUser.getText();
pass = txtPass.getText();
if(pass.equals("********") && user.equals("**********"))
{
// Here you can dispose the current window
this.dispose(); // Or you can use this.setVisible(false);
// Then call your next window to appear
new YourNextWindow().setVisible(true);
// And of course you can create an object for that window,
YourNextWindow yourNextWindow = new YourNextWindow();
yourNextWindow.setVisible(true);
} else {
lblDisplay.setText("Please try again.");
}
}
It's better to use this.dispose(); instead of making the JFrame invisible setVisible(false) as it will be still running without any use.
UPDATE
As camickr said it is best to use ActionListener instead of MouseListener.
public void jButton1ActionPerformed(ActionEvent e) {
// Your code here
}

Related

How to update values of a JFrame main after using a JDialog of Java Swing?

I have a main window called MainFrame which is a jForm to which I update the data depending on a timer, but the problem is that I cannot update the data in the same MainFrame after using the jdialog, since I end up creating another duplicate window, but with the data changed, one with the original timer and the other with the new timer, I know that I can close the first window with dispose() and then keep the second, but I would like to avoid changing windows so much
the code with which I create another window when pressing the jDialog button is the following
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
String textoFieldTimer = jTextField1.getText();
int timeUserConfig = Integer.parseInt(textoFieldTimer);
Timer timeDefault = new Timer(timeUserConfig, null);
TokenAccess token = new TokenAccess();
token.access_code = code;
MainFrame mainFrame = new MainFrame(token);
mainFrame.setVisible(true);
mainFrame.timeDefault.stop();
mainFrame.timeDefault = timeDefault;
mainFrame.setUpdateTime(timeUserConfig);
this.dispose();
}//GEN-LAST:event_jButton1ActionPerformed
Is there any alternative to update the window? something like mainFrame.update(); or maybe send the value of the jTextField from the jDialog to mainFrame? since the previous code creates another MainFrame for me.
Method main setLabel and Timer.start/stop
public void setUpdateTime(int timeUserConfig) {
this.timeUserConfig = timeUserConfig;
if (timeUserConfig == 0) {
timeDefault.start();
timeDefault.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
setLabelText();
String timeUserConfigStr = Integer.toString(timeDefaultInt);
tiempoActualizado.setText("Tiempo de Actualizado: " + timeUserConfigStr+"ms");
}
});
} else {
timeDefault.stop();
timeDefault = new Timer(timeUserConfig, null);
timeDefault.start();
timeDefault.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
setLabelText();
String timeUserConfigStr = Integer.toString(timeUserConfig);
tiempoActualizado.setText("Tiempo de Actualizado: " + timeUserConfigStr+"ms");
}
});
}
}
setLabelText is a method set of label
public void setLabelText() {
String humedadStr = String.valueOf(humedad);
String temperaturaStr = String.valueOf(temperatura);
String presionStr = String.valueOf(co2);
temporalHum.setText(humedadStr);
temporalTemperatura.setText(temperaturaStr);
temporalPresion.setText(presionStr);
}
Any help would be appreciated.
Thanks for the update, and I found another solution without using an OptionPane from this question: programmatically close a JPanel which is displayed in JDialog.
I cannot replicate your codings
Start with the MainFrame, assuming you opened the JDialog by clicking on a button and wants to setText() to label lbSomething:
private void btInputActionPerformed(java.awt.event.ActionEvent evt) {
// Open new JDialog when button is clicked
NewJDialog dialog = new NewJDialog(new javax.swing.JFrame, true);
dialog.setVisible(true);
// Get user input from JDialog
String temp = dialog.getInput();
if (temp != null) {
/*
* Perform jButton1ActionPerformed() content here
* Including timeUserConfig, timeDefault and setUpdateTime() here
* so that you don't have to access mainFrame in the JDialog.
*/
lbSomething.setText(temp);
}
}
Then about the JDialog (with simple input detection):
public class NewJDialog extends javax.swing.JDialog {
// Set the variable as class variable
private String textTOFieldTimer;
public NewJDialog(java.awt.Frame parent, boolean modal) {
// default contents
}
#SupressWarinings("unchecked")
private void initComponents() {
// default contents
}
private void btSaveAction Performed(java.awt.event.ActionEvent evt) {
// Check if input correct and whether to disable JDialog
if (tfInput.getText.length() != 0) {
input = tfInput.getText();
// Connect to the whole JDialog by getWindowAncestor()
Window window = SwingUtilities.getWindowAncestor(NewJDialog.this);
// Just setVisible(false) instead of dispose()
window.setVisible(false);
} else {
JOptionPane.showMessageDialog(this, "Wrong Input");
}
}
public String getInput() {
return textToFieldTimer;
}
// default variables declarations
}
Hope this answer helps you well.
Would be better if you displayed the source code, but a simple solution to update values to an existing JFrame is by using setText() and getText().
For example:
String input = JOptionPane.showInputDialog(this, "Nuevo valor");
lbPresionActual.setText(input);
If you created a self-defined JDialog, it is about to transfer the input value when closing the JDialog, and that could be a different question.

Why is my boolean value preemptively being returned?

I am working on a login validator and have a class that checks username and password validity. After checking, a boolean variable (isValidLoginCredentials) is updated in the LoginProxy class, which can be fetched by a get method and used for another purpose. However, the value that is returned by the get method is always the default value that I assigned to isValidLoginCredentials when the class was created. I think the issue is that I am calling the getter method in main() before I have a chance to update isValidLoginCredentials, but I don't understand what changes I should make to stop this. Here is the relevant part of the class and main program.
public class LoginProxy implements ActionListener
{
private JLabel usernameLabel;
private JTextField usernameText;
private JLabel passwordLabel;
private JPasswordField passwordText;
private JButton loginButton;
private boolean isValidLoginCredentials = false;
public void createLogin()
{
/*Here was code irrelevant to the problem I removed*/
loginButton.addActionListener(new LoginProxy());
loginButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String user = usernameText.getText();//get the username
String pass = passwordText.getText();//get the password
String credentials = user +":"+pass;//creates the string I compare to other valid
//credentials
ConcreteLoginValidator validator = new ConcreteLoginValidator(credentials);
try
{
isValidLoginCredentials = validator.checkLogin();
System.out.println("The credentials are "+isValidLoginCredentials);
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
}
});
}
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
}
public boolean getValidity()
{
return isValidLoginCredentials;
}
And here is the main method
public static void main(String[] args)
{
boolean isValidLogin = false;
LoginProxy proxy = new LoginProxy();
proxy.createLogin();
isValidLogin = proxy.getValidity();
if(isValidLogin == true)
{
JFrame frame = MainUI.getInstance();
frame.setSize(900, 600);
frame.pack();
frame.setVisible(true);
}
}
What should I add so that isValidLogin=proxy.getValidity(); returns a value only after I have already entered and checked whether the login credentials are correct?
Going straight to the point, a quick fix is to put the code below:
if(isValidLoginCredentials) {
JFrame frame = MainUI.getInstance();
frame.setSize(900, 600);
frame.pack();
frame.setVisible(true);
}
After this part:
System.out.println("The credentials are "+isValidLoginCredentials);
The code you call on createLogin() just sets the action listener to the button in the UI, hence the code will be executed just when you click on the button.
On the top of that, when you open a window, it starts a separated thread. I don't know the rest of the code, but assuming that when you instantiate the LoginProxy, it opens the login window. But the way you wrote, it will open the window and check the isValidLogin straight away (it doesn't wait you to click the button).
If you want to prove that, you can simply put a System.out.println before and after the proxy.createLogin(). You will realise that both lines will be reached while the UI is rendered.
Using a modal dialog that blocks until it is closed.
Very simplified example:
public class Dialog { // LoginProxy in questions code
private String value = null;
public void show(Window owner) {
var dialog = new JDialog(owner, JDialog.DEFAULT_MODALITY_TYPE);
var field = new JTextField(40);
var okButton = new JButton("OK");
okButton.addActionListener(ev -> {
value = field.getText();
dialog.dispose();
});
var panel = new JPanel();
panel.add(field);
panel.add(okButton);
dialog.add(panel);
dialog.pack();
dialog.setLocationRelativeTo(owner);
dialog.setVisible(true); // this will be blocked until JDialog is closed
}
public String getValue() {
return value;
}
}
called like
public static void main(String[] args) {
var dialog = new Dialog();
dialog.show(null);
System.out.println(dialog.getValue()); // check if valid and open JFrame in questions code
}
Advantage of this solution IMHO: the dialog class (LoginProxy) does not need to know about the main class and main JFrame. It has a clear single function: ask for user input.
the dialog creation is even easier using JOptionPane
In order to guarantee reading a value written in another thread, you must make the field volatile:
private volatile boolean isValidLoginCredentials;
You must also wait until the other completes before reading it. That aspect I leave to the reader.

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.

unable to setText in Java Frame

Hey I am creating a java project. In which I have a insert record frame, on insert frame I have a option to enter father ID and if the user did not know the father id, so I have set a button to find the father id.
when the user will click on that button, the new frame will appear and user can search for id, the result will show in a table and when user click on the particular record, the frame will dispose and should set the respective id on the previous frame.
I have written the code for it, and it is passing the value to the previous frame but it is not setting the value to the textfield that I want it to be. Where I am doing wrong? Here is the code.
FamilyInsert.java
public class FamilyInsert extends javax.swing.JFrame {
/**
* Creates new form FamilyInsert
*/
int id = DBManager.genID();
public int fid;
public FamilyInsert() {
initComponents();
txtId.setText(""+id);
txtName.requestFocus();
}
public void setFid(int fid){
txtFid.setText(""+fid);
System.out.println("setFID "+fid);
}
public void reset()
{
txtName.setText("");
txtFather.setText("");
txtFid.setText("");
txtCity.setText("");
txtState.setText("");
txtName.requestFocus();
}
private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {
int id = Integer.parseInt(txtId.getText());
String name = txtName.getText();
String fname = txtFather.getText();
int fid = Integer.parseInt(txtFid.getText());
String city = txtCity.getText();
String state = txtState.getText();
Family family = new Family(id,name,fname,fid, city,state);
boolean flag = false;
flag = DBManager.insertMember(family);
if(flag==true){
JOptionPane.showMessageDialog(this,"Successfully Saved");
id++;
txtId.setText(""+id);
reset();
}
else
{
JOptionPane.showMessageDialog(this,"Error Occured");
}
}
private void txtFidActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
SearchFatherFrame f = new SearchFatherFrame();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
and from the search frame:
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
int id;
if(evt.getClickCount()==2){
if(jTable1.getSelectedRow()!=-1)
{
int index = jTable1.getSelectedRow();
Family s = list.get(index);
id = s.getId();
System.out.println("ID from search frame "+id);
FamilyInsert f = new FamilyInsert();
f.setFid(id);
this.dispose();
//JOptionPane.showMessageDialog(this, s.getId()+"\n"+s.getName());
}
}
Your problem is that you're creating a new FamilyInsert object within the other class, and changing its state, but this leaves the state of the original FamilyInsert object unchanged. What you need to do instead is to pass a reference of the original displayed FamilyInsert into the 2nd object, and then change its state.
Change this:
SearchFatherFrame f = new SearchFatherFrame();
to something more like:
SearchFatherFrame f = new SearchFatherFrame(this);
Pass the reference into the class and use to set a field:
public class SearchFatherFrame {
private FamilyInsert familyInsert;
public SearchFatherFrame(FamilyInsert familyInsert) {
this.familyInsert = familyInsert;
// other code....
}
}
Then use that reference passed in to change the state of the original object.
if(jTable1.getSelectedRow()!=-1) {
int index = jTable1.getSelectedRow();
Family s = list.get(index);
id = s.getId();
System.out.println("ID from search frame "+id);
// FamilyInsert f = new FamilyInsert();
// f.setFid(id);
familyInsert.setFid(id); // **** add
this.dispose();
//JOptionPane.showMessageDialog(this, s.getId()+"\n"+s.getName());
}
Also you want the 2nd window to be a JDialog not a JFrame. Please see: The Use of Multiple JFrames, Good/Bad Practice?
Could you try
public void setFid(int fid){
txtFid.setText(""+fid);
System.out.println("setFID "+fid);
yourJFrame.setVisible(true); //Reloads the frame
}

Categories