label name can not be resolved - java

I've created a label loginLabel to show message on wrong authentication. I've kept this logic inside actionPerformed method, but I am getting error as loginLabel can not be resolved. How to remove this error? I've created my GUI using window-builder.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import java.awt.Color;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
public class FirstView {
private JFrame frmFirstProject;
private JTextField txtUsername;
private JPasswordField txtPassword;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FirstView window = new FirstView();
window.frmFirstProject.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public FirstView() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmFirstProject = new JFrame();
frmFirstProject.getContentPane().setBackground(new Color(51, 204, 204));
frmFirstProject.setTitle("first project");
frmFirstProject.setBounds(100, 100, 714, 491);
frmFirstProject.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmFirstProject.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(new Color(0, 0, 0), 3));
panel.setBounds(63, 47, 580, 354);
frmFirstProject.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(24, 25, 69, 22);
panel.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(24, 66, 69, 22);
panel.add(lblPassword);
txtUsername = new JTextField();
txtUsername.setBounds(97, 26, 86, 20);
panel.add(txtUsername);
txtUsername.setColumns(10);
txtPassword = new JPasswordField();
txtPassword.setBounds(97, 67, 86, 20);
panel.add(txtPassword);
JButton btnsubmit = new JButton("submit");
frmFirstProject.getRootPane().setDefaultButton(btnsubmit); //enter key
btnsubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
int val = 0;
Connection sqlCon = DB_con.getSQLConnection();
PreparedStatement ps = sqlCon.prepareStatement("select 1 from tbl_user_info where username = ? and password = ?");
ps.setString(1, txtUsername.getText().toUpperCase());
ps.setString(2, String.valueOf(txtPassword.getPassword()).toUpperCase());
ResultSet rs = ps.executeQuery();
if (rs.next()) {
val = rs.getInt(1);
}
if(val != 1)
{
loginLabel.setVisible(true);
}
System.out.println("the value is: "+val);
sqlCon.close();
System.exit(0);
} catch (Exception e) {
System.out.println(e.toString());
}
}
});
btnsubmit.setBounds(94, 125, 89, 23);
panel.add(btnsubmit);
JPanel panel_display = new JPanel();
panel_display.setBounds(36, 181, 355, 50);
panel.add(panel_display);
panel_display.setLayout(null);
JLabel loginLabel = new JLabel("Login Authentication Mismatched. Please try again.");
loginLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
loginLabel.setBounds(10, 11, 319, 28);
panel_display.add(loginLabel);
loginLabel.setVisible(false);
JLabel lbl_header = new JLabel("LIBRARY MANAGEMENT SYSTEM");
lbl_header.setFont(new Font("Tahoma", Font.BOLD, 14));
lbl_header.setBounds(211, 11, 288, 25);
frmFirstProject.getContentPane().add(lbl_header);
}
}

You are referring to the local variable loginLabel within the anonymous ActionListener class which you previously added to btnSubmit. This will not work as code inside the ActionListener class (or any other class) cannot see variables that are local to a method.
Instead you should declare loginLabel as a field, up at the top of the class:
private JPasswordField txtPassword;
private JLabel loginLabel;
This is visible to all methods inside the class and also any non-static classes defined inside your class (such as the aforementioned ActionListener).
Then simply change the line which creates your label inside your initialize() method from:
JLabel loginLabel = new JLabel("Login Authentication Mismatched. Please try again.");
to
loginLabel = new JLabel("Login Authentication Mismatched. Please try again.");
Defining the loginLabel before the ActionListener will be adequate in java 8, as java 8 implicitly marks local fields that are defined but never changed as final. If you are targetting java 7 or earlier you would need to explicitly make that variable final.

To avoid problems like "LabelX can not be resolved" or "ButtonY can not be resolved", I learned to do this:
On Eclipse, go to "Window" module...
Choose item "Preferences"...
Choose "WindowBuilder"...
Choose "Swing" or "SWT"...
In "Code Generation", choose "Field" in variable generation...
Inside "Event handlers", choose "Implement listener interface in parent class"...
It works using Java 1.7 or 1.8. Say bye bye to errors in ActionListner Class and GUI components Swing or SWT. And sure, i'm using WindowBuilder plugin to build the GUI application.

Related

Issues with ActionListener

I'm trying to write a program that asks you to click on a button to generate a random number and then makes the user try to guess what that number is.
Right now I'm working on getting a button click to generate a random number and to tell the user that the random number has been generated through a JTextPane. For whatever reason this part of the code doesn't seem to be executing correctly.
I have already instanced the object in the main class and I've added an actionlistener to the button. I have no idea what's causing this not to work appropriately:
package GUIs;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JToggleButton;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import java.awt.Font;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Principal extends JFrame {
//Elements
private JPanel contentPane;
private JTextField attemptField;
private JTextPane hint;
private JButton btnGenerate;
private JButton btnEnter;
//Events
private GenerateRandomNumber genRanNum;
//Misc variables
int ranNum = 1;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Principal frame = new Principal();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Principal() {
//Generates JPanel
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
//Generates text field where the user will write the number
attemptField = new JTextField();
attemptField.setBounds(130, 59, 130, 26);
contentPane.add(attemptField);
attemptField.setColumns(10);
//Generates the hint
hint = new JTextPane();
hint.setBackground(SystemColor.window);
hint.setText("First, generate a new number!");
hint.setBounds(130, 110, 192, 19);
contentPane.add(hint);
//Generates the button that should call for the creation of the new number
btnGenerate = new JButton("Generate number");
btnGenerate.setFont(new Font("Lucida Grande", Font.PLAIN, 10));
btnGenerate.setBounds(165, 153, 117, 29);
contentPane.add(btnGenerate);
btnGenerate.addActionListener(genRanNum);
//Generates button that will be used to enter the number
btnEnter = new JButton("Enter");
btnEnter.setBounds(269, 59, 58, 29);
contentPane.add(btnEnter);
}
public class GenerateRandomNumber implements ActionListener {
public void actionPerformed(ActionEvent e) {
ranNum = (int) (Math.random() * 101);
hint.setText("The number has been created!");
}
}
}
private GenerateRandomNumber genRanNum;
Your random number generator is null. I don't see where you ever create an instance of it.
btnGenerate.addActionListener(genRanNum);
The above statement does nothing because the variable is null. (ie. no ActionListener has been added to the button)
I don't even know how your GenerateRandomNumber class would compile because it doesn't have access to the "hint" variable of your "Principal" class.
Don't make the GenerateRandomNumber class a public class. Instead make it an inner class of the "Principal" class.
Read the section from the Swing tutorial on How to Use Actions for an example showing how to use inner classes. Note you can even use an Action instead of an ActionListener.

Exception during connection to JDBC MySQL

Good Afternoon: I'm a chemistry teacher from Spain. I am not an experimented programmer, but I decided to create a small program to help my students with my subject. I am creating this small program in Java where I'm trying to connect with a database in order to receive its information through the Atomic Number. Actually, I also want to do it through the other parameters, but I'm not shure about how to do it. The thing is that it bounces the exception or it doesn't connect properly to the database. I attatch the full code and a screenshot of my database (By the way, when I try to upload data to the database it works.):
package chemInterface;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.awt.event.ActionEvent;
public class Oxidaciones extends JFrame {
private JPanel contentPane;
private JPasswordField pass;
private JTextField smb;
private JTextField elm;
private JTextField ox;
private JTextField nat;
private JTextField mat;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Oxidaciones frame = new Oxidaciones();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Oxidaciones() {
setFont(new Font("Courier Prime", Font.PLAIN, 12));
setTitle("Interface");
setForeground(Color.BLUE);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setForeground(Color.BLUE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblSmbolo = new JLabel("Smb");
lblSmbolo.setFont(new Font("Courier Prime", Font.PLAIN, 11));
lblSmbolo.setBounds(10, 30, 67, 14);
contentPane.add(lblSmbolo);
JLabel lblElemento = new JLabel("Elm");
lblElemento.setFont(new Font("Courier Prime", Font.PLAIN, 11));
lblElemento.setBounds(10, 52, 67, 14);
contentPane.add(lblElemento);
JLabel lblOxidacin = new JLabel("Ox");
lblOxidacin.setFont(new Font("Courier Prime", Font.PLAIN, 11));
lblOxidacin.setBounds(10, 77, 67, 14);
contentPane.add(lblOxidacin);
JLabel lblNAtmico = new JLabel("NAt");
lblNAtmico.setFont(new Font("Courier Prime", Font.PLAIN, 11));
lblNAtmico.setBounds(10, 102, 86, 14);
contentPane.add(lblNAtmico);
JLabel lblMAtmica = new JLabel("MAt");
lblMAtmica.setFont(new Font("Courier Prime", Font.PLAIN, 11));
lblMAtmica.setBounds(10, 127, 86, 14);
contentPane.add(lblMAtmica);
pass = new JPasswordField();
pass.setBounds(90, 166, 67, 20);
contentPane.add(pass);
JLabel lblPass = new JLabel("Pass");
lblPass.setFont(new Font("Courier Prime", Font.PLAIN, 11));
lblPass.setBounds(10, 169, 67, 14);
contentPane.add(lblPass);
smb = new JTextField();
smb.setBounds(67, 25, 86, 20);
contentPane.add(smb);
smb.setColumns(10);
elm = new JTextField();
elm.setColumns(10);
elm.setBounds(67, 47, 86, 20);
contentPane.add(elm);
ox = new JTextField();
ox.setColumns(10);
ox.setBounds(67, 72, 86, 20);
contentPane.add(ox);
nat = new JTextField();
nat.setColumns(10);
nat.setBounds(67, 97, 86, 20);
contentPane.add(nat);
mat = new JTextField();
mat.setColumns(10);
mat.setBounds(67, 127, 86, 20);
contentPane.add(mat);
JLabel lblResultado = new JLabel("");
lblResultado.setBounds(243, 232, 46, 14);
contentPane.add(lblResultado);
JButton compile = new JButton("Compile");
compile.addActionListener(new ActionListener() {
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent arg0) {
//COMPILE Presionado
//INSERT BETWEEN HERE
ox.setText("");
elm.setText("");
mat.setText("");
nat.setText("");
smb.setText("");
try {
Connection conexion=DriverManager.getConnection("jdbc:mysql://localhost/chem","root" ,"");
Statement comando=conexion.createStatement();
ResultSet registro = comando.executeQuery("select elemento,simbolo,oxidacion,matom from form where natom="+nat.getText());
if(registro.next()==true) {
smb.setText(registro.getString("simbolo"));
ox.setText(registro.getString("oxidacion"));
elm.setText(registro.getString("elemento"));
mat.setText(registro.getString("matom"));
} else {lblResultado.setText("No existe");}
conexion.close();
} catch(SQLException ex) {setTitle(ex.toString());}
//AND HERE
}
});
compile.setBounds(7, 194, 89, 23);
contentPane.add(compile);
JButton clear = new JButton("Clear");
clear.setBounds(7, 228, 89, 23);
contentPane.add(clear);
JButton alta = new JButton("Alta");
alta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//BOTON ALTA PRESIONADO
lblResultado.setText("");
try {
Connection conexion=DriverManager.getConnection("jdbc:mysql://localhost/chem","root", "");
Statement comando=conexion.createStatement();
comando.executeUpdate("insert into form(elemento,simbolo,oxidacion,natom,matom) values ('"+elm.getText()+"','"+smb.getText()+"','"+ox.getText()+"',"+nat.getText()+","+mat.getText()+")");
conexion.close();
lblResultado.setText("se registraron los datos");
elm.setText("");
ox.setText("");
nat.setText("");
mat.setText("");
smb.setText("");
} catch(SQLException ex){
setTitle(ex.toString());
}
}
});
alta.setBounds(335, 228, 89, 23);
contentPane.add(alta);
cargarDriver();
}
private void cargarDriver() {
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception ex) {
setTitle(ex.toString());
}
}
}
Here is my database:
database phpmyadmin
And here is the exception when inserting 1 into NAt:
Actual Exception
Taking a look at your code around your select query, you are running
nat.setText("");
and then
ResultSet registro = comando.executeQuery("select elemento,simbolo,oxidacion,matom from form where natom="+nat.getText());
What do you expect nat.getText() to return here?
Of course, it will return "" because that's what you've set the text of nat to. You're then asking your database to run the following invalid query:
select elemento,simbolo,oxidacion,matom from form where natom=
Running this against a MySQL database will generate the error in your screenshot.
I'm guessing that the fix is to delete the line nat.setText("");.
However, instead of building up SQL strings using string concatenation, please use PreparedStatements instead.
Replace the lines
Statement comando=conexion.createStatement();
ResultSet registro = comando.executeQuery("select elemento,simbolo,oxidacion,matom from form where natom="+nat.getText());
with
PreparedStatement comando=conexion.prepareStatement(
"select elemento,simbolo,oxidacion,matom from form where natom=?");
comando.setInt(1, Integer.parseInt(nat.getText()));
ResultSet registro = comando.executeQuery();
and the lines
Statement comando=conexion.createStatement();
comando.executeUpdate("insert into form(elemento,simbolo,oxidacion,natom,matom) values ('"+elm.getText()+"','"+smb.getText()+"','"+ox.getText()+"',"+nat.getText()+","+mat.getText()+")");
with
Statement comando=conexion.prepareStatement(
"insert into form(elemento,simbolo,oxidacion,natom,matom) values (?,?,?,?,?)");
comando.setString(1, elm.getText());
comando.setString(2, smb.getText());
comando.setString(3, ox.getText());
comando.setString(4, Integer.parseInt(nat.getText()));
comando.setString(5, Integer.parseInt(mat.getText()));
comando.executeUpdate();
You will also need to add some error-handling around the calls to Integer.parseInt(...): these will throw NumberFormatException if either nat.getText() or mat.getText() isn't a valid integer.
If you could attach or describe exactly what the sqlException is that might help, but from what I can see your database connection url is malformed. So its probably not connecting to the database
your url is:
Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/chem","root" ,"");
Normally you need to add a port number that the database is running on so changing the:
"jdbc:mysql://localhost/chem"
to:
jdbc:mysql://localhost:3306/chem
or whatever the port your database is running on, from a google it looks like the default port number is 3360 but it depends on how you have setup your database. But i think that should solve your problem
Please try to execute your sql query manually with your DB client.
To do this you can add code like this or use debugging to get the sql string value and test it:
String sqlString = "insert into form(elemento,simbolo,oxidacion,natom,matom) values ('"+elm.getText()+"','"+smb.getText()+"','"+ox.getText()+"',"+nat.getText()+","+mat.getText()+")";
System.out.println(sqlString);
comando.executeUpdate(sqlString);
You need to get the actual SQL string and test it manually if it works.

How do I output to textField?

I'm making a java program to turn any text into capital capital letters.
It worked fine with system.out.print but now I want to turn it into a GUI.
I tried getting the text from the original textField input, turn it into a double, turn the double into a string then I used addText but I don;t think it works.
Here is how it is supposed to work:
I write a bunch a text into a the input box then when I click the GO button it converts every character into capital letters. The output is supposed to to inside another TextField
here is my code (using Eclipse)
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Frame1 {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame1 window = new Frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Frame1() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 710, 508);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblInputTextTo = new JLabel("Input Text to Capitalise:");
lblInputTextTo.setFont(new Font("Segoe UI", Font.BOLD, 26));
lblInputTextTo.setBounds(210, 0, 289, 54);
frame.getContentPane().add(lblInputTextTo);
textField = new JTextField();
textField.setBounds(34, 77, 624, 150);
frame.getContentPane().add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(34, 354, 613, 90);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
JButton btnGo = new JButton("GO!");
btnGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double TextInput = Double.parseDouble(textField.getText());
String Str = String.valueOf(TextInput);
textField_1.setText(Str.toUpperCase());
textField_1.setEditable(false);
}
});
btnGo.setFont(new Font("Segoe UI", Font.BOLD, 18));
btnGo.setBounds(250, 239, 180, 23);
frame.getContentPane().add(btnGo);
JLabel lblOutput = new JLabel("Output:");
lblOutput.setFont(new Font("Segoe UI", Font.BOLD, 26));
lblOutput.setBounds(304, 300, 95, 43);
frame.getContentPane().add(lblOutput);
}}
I'm not done yet if you have some suggestion it would be nice.
You don't need to convert the input String into double to make it uppercase. I did below change to your program and it works now.
btnGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Remove these 2 lines
//double TextInput = Double.parseDouble(textField.getText());
//String Str = String.valueOf(TextInput);
//Directly take input text, make it uppercase and set it in output field.
textField_1.setText(textField.getText().toUpperCase());
textField_1.setEditable(false);
}
});
Additional tip:
Don't do setLayout(null) and use setBounds() to set components in absolute positions. Instead use layout managers. See https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

How to create a lock with user input on JPanel?

I am a beginner at Java so if there are some simple problems that are in my code please tell me. Thank you in advance!
In Java I have a "login" JPanel which I want the user to enter in a password they like, then have them enter the password on another JPanel (the same password that they created). If it is right and they click the login button again then it would bring them to a screen which says "Welcome" and if they don't, then a screen that says "False. Error". However something on Eclipse is saying that something is wrong and that I can't run it. Please tell me where I went wrong and if you can tell me how to fix it. I would appreciate it!
There are two problems with my code. Both of them are "Syntax error, insert "}" to complete ClassBody" but every time I add one in, it says "Syntax error on token "}", delete this token"
Here is my code:
package Button;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import java.util.Scanner;
#SuppressWarnings("unused")
public class Login {
public static void main(String[] args) {
JFrame frame = new JFrame("Login Page");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
panel.setLayout(null);
JLabel userLabel = new JLabel("Pasword");
userLabel.setBounds(10, 10, 80, 25);
panel.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(100, 10, 160, 25);
panel.add(userText);
JButton loginButton = new JButton("Create");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);
#SuppressWarnings("resource")
Scanner user = new Scanner (System.in);
loginButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
loginButton.setVisible(false);
registerButton.setVisible(false);
userText.setVisible(false);
userLabel.setVisible(false);
JTextField userText1 = new JTextField(20);
userText.setBounds(100, 10, 160, 25);
panel.add(userText1);
JButton loginButton1 = new JButton("Password");
loginButton1.setBounds(10, 80, 80, 25);
panel.add(loginButton1);
});
loginButton1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
String name = userText.getText();
String accept = name;
String good;
if (accept.equals(name)) {
good = "Welcome";
} else {
good = "False. Error";
}
JLabel label1 = new JLabel(good);
label1.setBounds(100, 40, 100, 100);
label1.setVisible(true);
panel.add(label1);
}
});
}
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//...
}
);
Is missing a closing embrace (}) - one thing you will learn to do is count brackets and braces
It should look more like
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//...
}
});
registerButton and loginButton1 are undefined and you seem to be missing closing brace (}) at the end of the file as well
I would also highly recommend that you make use of layout managers, they will make life a lot easier for you. I'd recommend starting with How to use CardLayout as it will allow you to switch between multiple views simply
Thank you for helping me fix the problem. In the end I was able to fix it and it now works. Here it is:
package Button;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import java.util.Scanner;
#SuppressWarnings("unused")
public class AddOnButton {
public static void main(String[] args) {
JFrame frame = new JFrame("Login Page");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
panel.setLayout(null);
JLabel userLabel = new JLabel("Password");
userLabel.setBounds(10, 10, 80, 25);
panel.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(100, 10, 160, 25);
panel.add(userText);
JButton loginButton = new JButton("Create");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);
String name = userText.getText();
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loginButton.setVisible(false);
userText.setVisible(false);
userLabel.setVisible(false);
JTextField userText1 = new JTextField(20);
userText1.setBounds(100, 10, 160, 25);
panel.add(userText1);
JLabel userLabel1 = new JLabel("Password");
userLabel1.setBounds(10, 10, 80, 25);
panel.add(userLabel1);
JButton loginButton1 = new JButton("Enter");
loginButton1.setBounds(10, 80, 80, 25);
panel.add(loginButton1);
String check = userText1.getText();
loginButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
userText1.setVisible(false);
userLabel1.setVisible(false);
loginButton1.setVisible(false);
String good;
if (name.equals(check)) {
good = "Welcome";
} else {
good = "False. Error";
}
JLabel label1 = new JLabel(good);
label1.setBounds(100, 40, 100, 100);
label1.setVisible(true);
panel.add(label1);
}
});
}
});
}
}

calling an instance variable obtained from an actionperformed in another JPanel

I have created a JFrame with cardLayout and the first visible JPanel has a Jbutton that I have added an action Listener to perform an action. The action creates a String variable 'hhhhh' that I want to use in another JPanel. This is what I have problem doing.
Class 1
import java.awt.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class NHome extends JFrame{
JPanel Bucket= new JPanel(), Start= new JPanel(), Cashier = new csView(), Manager = new JPanel();
JButton stbtn= new JButton("Start"), mnbtn= new JButton("Manager"), csbtn= new JButton("Cashier");
CardLayout cl= new CardLayout();
private final JTextField textField = new JTextField();
private JPasswordField passwordField;
public NHome() {
textField.setBounds(322, 141, 158, 31);
textField.setColumns(10);
Bucket.setLayout(cl);
Bucket.add(Start, "1");
Bucket.add(Cashier, "2");
Bucket.add(Manager, "3");
Start.setLayout(null);
stbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cl.show(Bucket, "2");
/*
* I want to use this value of this String in the another class (csView)
*/
String hhhhh=new String("Peter");
System.out.println(hhhhh);
}
});
stbtn.setBounds(353, 245, 76, 23);
Start.add(stbtn);
Start.add(textField);
passwordField = new JPasswordField();
passwordField.setBounds(322, 183, 158, 31);
Start.add(passwordField);
Cashier.setLayout(null);
csbtn.setBounds(197, 139, 116, 23);
Cashier.add(csbtn);
Manager.setBackground(Color.BLUE);
Manager.add(mnbtn);
cl.show(Bucket, "1");
setTitle("NOVA PHARM");
getContentPane().add(Bucket);
setBounds(300, 300, 566, 482);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new CardLayout(5, 5));
setResizable(true);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NHome window = new NHome();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
/*
*this is the second class where I want to use the variable
*/
Class 2
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Font;
public class csView extends JPanel {
/**
* Create the panel.
*/
public csView() {
setLayout(null);
/**
* I want to display the String hhhhh in the JLabel Uniqlbl below
*
*/
JLabel Uniqlbl = new JLabel("Cashier Name:");
Uniqlbl.setFont(new Font("Tahoma", Font.PLAIN, 16));
Uniqlbl.setBounds(227, 62, 253, 46);
add(Uniqlbl);
}
}
Try modify the csView
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Font;
public class csView extends JPanel {
// Declare those variables here
String hhhhh;
JLabel Uniqlbl;
public csView() {
setLayout(null);
Uniqlbl = new JLabel("Cashier Name:");
Uniqlbl.setFont(new Font("Tahoma", Font.PLAIN, 16));
Uniqlbl.setBounds(227, 62, 253, 46);
add(Uniqlbl);
}
// Add a setter here
public void setHhhhh(String hhhhh) {
this.hhhhh = hhhhh;
// Edit: Add this line to update the Uniqlbl text
Uniqlbl.setText(hhhhh);
}
}
And in the ActionListener call the setHhhhh() method
stbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cl.show(Bucket, "2");
String hhhhh=new String("Peter");
// Call the setter here
Cashier.setHhhhh(hhhhh);
System.out.println(hhhhh);
}
});
I suggest you not to use the "hhhhh" variable in the csView constructor or you could stumble in a NullPointerException. Or, if you want to do so, initialize the "hhhhh" variable first like this
String hhhhh = "";
One way you could do this is a create a static variable in your NHome class that acts as a global variable. This would mean than csView would be able to read and write to the variable.
This is an example of how it could be implemented:
JPanel Bucket = new JPanel(), Start = new JPanel(), Cashier = new csView(), Manager = new JPanel();
JButton stbtn = new JButton("Start"), mnbtn = new JButton("Manager"), csbtn = new JButton("Cashier");
CardLayout cl = new CardLayout();
private final JTextField textField = new JTextField();
private JPasswordField passwordField;
static String hhhhh; //create the variable here
public NHome() {
textField.setBounds(322, 141, 158, 31);
textField.setColumns(10);
Bucket.setLayout(cl);
Bucket.add(Start, "1");
Bucket.add(Cashier, "2");
Bucket.add(Manager, "3");
Start.setLayout(null);
stbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cl.show(Bucket, "2");
/*
* I want to use this value of this String in the another class (csView)
*/
hhhhh = new String("Peter"); //set the value here
System.out.println(hhhhh);
}
});
So then you could implement it in your csView by saying:
JLabel Uniqlbl = new JLabel(NHome.hhhhh);

Categories

Resources