I have two syntax error in my login form panel code and here is it :
private void loginActionPerformed(java.awt.event.ActionEvent evt) {
boolean result =false;
try{ Koneksi objKoneksi = new Koneksi();
Connection kon = objKoneksi.bukaKoneksi();
Statement stat = kon.createStatement();
String username = id.getText();
String password = pass.getText();
String query = "select * from userid where id='" +id+ "'and pass='"+pass+"'";
result=stat.executeQuery(query).next();
} catch (SQLException e)
{
System.out.println(e.toString());}
if(result){
JOptionPane.showMessageDialog(null,"LOGIN SUCCESS");
this.setVisible(false);
new Aplikasi().show();
this.parent.setVisible(true);
this.dispose();}
else {
error.setText("ERROR LOGIN");}
}
There is a Strikethrough on Show() method and a red balloon in the line this.parent.setVisible(true) said Parent is not public in Component; cannot be accessed from outside packages.
What could go wrong here?
thanks before
PS: I'm newbie and English is not my Native Language
A strike through most likely means that the method you are calling is deprecated.
The error saying parent is not public means that the field parent in this object cannot be accessed directly. If I'm not wrong you can call getParent() to get access to it.
Related
first of all I know this is duplicated question. But I've search and tried from stackoverflow listed on Google to quora but still cant resolve my Get method still return null.
This is my class loginModel.java under package com.hello.model
public class loginModel {
public String username;
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return this.username;
}
}
This is my loginView.java under package com.hello.view
import com.hello.model.loginModel;
public class loginView extends javax.swing.JFrame {
loginModel login = new loginModel();
public loginView() {
initComponents();
this.setLocationRelativeTo(null);
loginFunction();
}
private void loginFunction(){
String username = usernameText.getText();
String password = passwdText.getText();
String query = "select * from access where username = '" +username+ "' AND password = '" +password+"'";
databaseConnect db = new databaseConnect();
try (Connection con = DriverManager.getConnection(db.url, db.user, db.password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
if(rs.next()) {
if(username.equals(rs.getString("username")) && password.equals(rs.getString("password"))){
JOptionPane.showMessageDialog(null, "login Success");
String name = rs.getString("name");
String privilege = rs.getString("privilege");
login.setUsername(name);
menu = new menuView();
menu.setVisible(true);
this.setVisible(false);
}
} else {
JOptionPane.showMessageDialog(null, "username or password incorrect");
}
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
I want call my username from menuView.java under package com.hello.view after login success
import com.hello.model.loginModel;
import com.hello.view.loginView;
public class menuView extends javax.swing.JFrame {
private String username;
loginModel login = new loginModel();
public menuView() {
initComponents();
this.setLocationRelativeTo(null);
initMenu();
}
private void initMenu(){
username = login.getUsername();
JOptionPane.showMessageDialog(this, username);
}
}
As per my question when I call Get method from loginModel, messagebox return null.
I've tried:
Put system.out.println directly in loginModel.java, value return
and call system.out.println in menuView.java at the same time but value return null. How?
Send string between jframe with menu = menuView(username) in loginView.java and retrieve in menuView.java, value return null
Using no model and create set string in loginView and call it in
menuView, value return null
I need values that I want to use in another class/package/jframe. Am I doing wrong?
I am not well versed in Swing but I can see the problem, just not the exact solution.
Your code creates an instance of loginModel in both the menuView and in loginView. Then in loginView is sets the name in the instance it has, in in menuView it gets the name from its own instance.
You need to create a single instance of the model and share it between the two views.
In a pojo way I would pass the loginModel to both "views" in a constructor.
menu = new menuView(login);
And in menuView
public menuView(loginModel login) {
this.login = login;
}
Your menuView instance isn't using the loginModel class that you instantiate in loginView, it's using the new one you created using new menuView() when you initialized the login variable in the menuView class. You just need to add a setter method for the loginModel attribute in the menuView class like this:
import com.hello.model.loginModel;
import com.hello.view.loginView;
public class menuView extends javax.swing.JFrame {
private String username;
loginModel login = new loginModel();
public menuView() {
initComponents();
this.setLocationRelativeTo(null);
initMenu();
}
private void initMenu(){
username = login.getUsername();
JOptionPane.showMessageDialog(this, username);
}
public void setLogin(loginModel loginModel) {
this.login = loginModel;
}
}
Then call the setter in loginView.loginFunction like this:
... code before
login.setUsername(name);
menu = new menuView();
menu.setLogin(login);
menu.setVisible(true);
this.setVisible(false);
... code after
Notice the only changes to your code are the added setLogin method on the menuView class and the call to menu.setLogin(login) in loginView.loginFunction.
You need to think in stages/steps. Login is a single step, it has one of two outcomes, success or failure.
Your app needs to perform this step and take appropriate action based on the outcome of the result.
You also need to think about "separation of responsibility" - in this case, it's not really the responsibility of the loginView to perform the login operation, it just coordinates the user input.
The responsibility actually falls to the LoginModel
// Just a custom exception to make it easier to determine
// what actually went wrong
public class LoginException extends Exception {
public LoginException(String message) {
super(message);
}
}
// LoginModel ... that "does" stuff
public class LoginModel {
private String username;
DatabaseConnect db;
public LoginModel(DatabaseConnect db) {
this.db = db;
}
// I would consider not doing this. You need to ask what reasons would
// the app need this information and expose it only if there is really a
// reason to do so
public String getUsername() {
return username;
}
public boolean isLogedIn() {
return username != null;
}
public void validate(String username, String password) throws SQLException, LoginException {
String query = "select * from access where username = ? AND password = ?";
try ( Connection con = DriverManager.getConnection(db.url, db.user, db.password); PreparedStatement st = con.prepareStatement(query)) {
st.setString(1, username);
st.setString(2, password);
try ( ResultSet rs = st.executeQuery()) {
if (rs.next()) {
this.username = username;
} else {
throw new LoginException("Invalid user credentials");
}
}
}
}
}
This is an overly simplified example, as the actual responsibility for performing the login should fall to the controller, which would then generate the model, but I'm getting ahead of myself.
Because the flow of the app shouldn't be controlled/determined by the login view, the LoginView should itself be a dialog. This way, it can be shown when you need it, it can perform what ever operations it needs and then go away, leaving the rest of the decision making up to who ever called it
public class LoginView extends javax.swing.JDialog {
private LoginModel model;
public LoginView(LoginModel model) {
initComponents();
setModal(true);
this.model = model;
this.setLocationRelativeTo(null);
}
// This will get executed when the user taps some kind of "perform login button"
private void loginFunction() {
String username = usernameText.getText();
String password = passwdText.getText();
try {
model.validate(username, password);
dispose()
} catch (SQLException ex) {
// This should probably be considered a fatal error
model = null;
dispose();
} catch (LoginException ex) {
JOptionPane.showMessageDialog(this, "Login vaild");
}
}
}
This then means you might put it together something like this...
DatabaseConnect db = new DatabaseConnect();
LoginModel model = new LoginModel(db);
LoginView loginView = new LoginView(model);
// Because we're using a modal dialog, the code execution will wait here
// till the window is disposed/closed
loginView.setVisible(true);
if (loginView.model != null) {
// model is now valid and can continue to be used
// in what ever fashion you need
} else {
JOptionPane.showMessageDialog(null, "Fatal Error");
}
This takes you a step closer to a more decoupled solution, where you feed information to the classes when they need it, rather than the classes making decisions about what they should create/use.
It also moves you a step closer to re-usable classes, as they do their specific job and nothing more.
You might find taking the time to read up on "model-view-controller" will help you better understand this approach
I am trying to create program which will display or hide button depended on role of the user, depend if user is Administrator or someone else.
So in this case i am passing String from "Login" frame to "Menu" frame and if is String equal to my requirement, it show button, if is not, then hide button, on "Menu" frame. Now this is working with string. But how to do same thing but to pull Role from database? I have that field in database but i don't know how exactly to do that. - My fields in database are username, password and role.
Thanks!
Login frame
JButton btnLogin = new JButton("Login !");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String username = textUsername.getText();
String password = passwordField.getText();
String S = "Administrator";
String query = "SELECT * FROM ADMINISTRATION where username=? and password=?;";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet set=stmt.executeQuery();
if (set.next()) {
Menu menu = new Menu();
menu.setVisible(true);
setVisible(false);
menu.Proba(S);
stmt.close();
connection.close();
}
else {
JOptionPane.showMessageDialog(contentPane, "Pogrešno korisničko ime ili lozinka !", "Greška !", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e2) {
// TODO: handle exception
}
}
});
Menu frame
public void Proba(String S) {
if (S.equals("Administrator")) {
btnOption.setVisible(true);
}
else {
btnOption.setVisible(false);
}
}
Ok, I'm assuming this is an academic project.
So, you have a ResultSet and you are iterating over it, when you call the "next" method you move to the next (in this case the first) row.
Now you have a row, you need to call a method that retrieves a String value from a column (in this case role), check the documentation:
https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
You have a "getString" method that needs a column name, and will return the string valuo from that column.
An example could be:
if (set.next()) {
String role = set.getString("role");
Menu menu = new Menu();
menu.setVisible(true);
setVisible(false);
menu.Proba(role);
stmt.close();
connection.close();
}
I'm trying to pass information from a frame using this method;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String regnum = registration.getText();
editStudent s = new editStudent(regnum);
s.setVisible(true);
dispose();
// TODO add your handling code here:
}
The information is passed but then I want to use the information I got to select data from my database which then returns an error.
public editStudent(String regnum) {
initComponents();
registration = regnum;
jLabel4.setText(registration);
}
This receives the data.
Then this part is meant to collect the data but doesnt.
private void jLabel20MouseClicked(java.awt.event.MouseEvent evt) {
try{
String sql = "Select * from students where RegistratioNumber = '"+registration+"'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if(rs.next()){
surname.setText(rs.getString("Surname"));
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
// TODO add your handling code here:
}
first time posting so sorry if my question is slightly strange.
So I have a project in school that requires us to create java classes using netbeans that open up a window with three options, check stock, purchase item and update stock.
We had a class called stockdata that held the details of 5 different items for us to use in our three classes to check, purchase and update items. The latest stage of our coursework requires us to create a derby database and enter the items into a table.
I have done this with no issues but I am having a problem getting the items from the table back into my classes to use. We were given the following code but I can't get it to work, even using the commented hints.
package stock;
// Skeleton version of StockData.java that links to a database.
// NOTE: You should not have to make any changes to the other
// Java GUI classes for this to work, if you complete it correctly.
// Indeed these classes shouldn't even need to be recompiled
import java.sql.*; // DB handling package
import java.io.*;
import org.apache.derby.drda.NetworkServerControl;
public class StockData {
private static Connection connection;
private static Statement stmt;
static {
// standard code to open a connection and statement to an Access database
try {
NetworkServerControl server = new NetworkServerControl();
server.start(null);
// Load JDBC driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//Establish a connection
String sourceURL = "jdbc:derby://localhost:1527/"
+ new File("UserDB").getAbsolutePath() + ";";
connection = DriverManager.getConnection(sourceURL, "use", "use");
stmt = connection.createStatement();
} // The following exceptions must be caught
catch (ClassNotFoundException cnfe) {
System.out.println(cnfe);
} catch (SQLException sqle) {
System.out.println(sqle);
} catch (Exception e) {
System.out.println(e);
}
}
// You could make methods getName, getPrice and getQuantity simpler by using an auxiliary
// private String method getField(String key, int fieldNo) to return the appropriate field as a String
public static String getName(String key) {
try {
// Need single quote marks ' around the key field in SQL. This is easy to get wrong!
// For instance if key was "11" the SELECT statement would be:
// SELECT * FROM Stock WHERE stockKey = '11'
ResultSet res = stmt.executeQuery("SELECT * FROM Stock WHERE stockKey = '" + key + "'");
if (res.next()) { // there is a result
// the name field is the second one in the ResultSet
// Note that with ResultSet we count the fields starting from 1
return res.getString(2);
} else {
return null;
}
} catch (SQLException e) {
System.out.println(e);
return null;
}
}
public static double getPrice(String key) {
// Similar to getName. If no result, return -1.0
return 0;
}
public static int getQuantity(String key) {
// Similar to getName. If no result, return -1
return 0;
}
// update stock levels
// extra is +ve if adding stock
// extra is -ve if selling stock
public static void update(String key, int extra) {
// SQL UPDATE statement required. For instance if extra is 5 and stockKey is "11" then updateStr is
// UPDATE Stock SET stockQuantity = stockQuantity + 5 WHERE stockKey = '11'
String updateStr = "UPDATE Stock SET stockQuantity = stockQuantity + " + extra + " WHERE stockKey = '" + key + "'";
System.out.println(updateStr);
try {
stmt.executeUpdate(updateStr);
} catch (SQLException e) {
System.out.println(e);
}
}
// close the database
public static void close() {
try {
connection.close();
} catch (SQLException e) {
// this shouldn't happen
System.out.println(e);
}
}
}
Sorry if this seems a stupid question but I am fairly new to Java and was making good progress until this roadblock.
Thanks in advance!
Alex
Searching for "java sql" on Google delivers this link: https://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html
From a connection you can create a statement (you can find this in the link and in your code) , then fetch a result set and loop over that with rs.next(). That should get your started.
Of course you have to make sure that the driver and database are there/running, just saying...
Here netbeans has nothing to do with database. This is a Java-based integrated development environment(IDE) that will help you to reduce syntactic error.
public void dataAccess(){
try {
String connectionUrl = "suitable connection url as per your database";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
Class.forName("JDBC driver name as per your database");
con = DriverManager.getConnection(connectionUrl, userName, password);
String SQL = "SQL query as per your criteria";
stmt = con.createStatement();
rs = stmt.executeQuery(query);
while (rs.next()) {
// look into ResultSet api and use method as per your requirement
}
rs.close();
}
catch (Exception e) {
//log error message ;
}
}
Hello i'm trying to build a small application that will allow me to store email addresses in a MySQL database. What i've done is that i've created a Java Class file (ec.java) and a connection that works fine and code for executing this into the database.
In the JFrame (ecframe.java) have i created a textfield and a button. When typing in the email address and pressing the button it will store this information to a string called textFieldValue. But what i can't figure out is how to get this string into my ec.java file.
This is my code from ec.java:
package emailcollector;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class ec {
public static void main(String[] args) {
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost", "admin", "pass");
Statement stmt = (Statement) con.createStatement();
String email = textFieldValue;
String insert = "INSERT INTO emails VALUES ('" + email + ")";
stmt.executeUpdate(insert);
}catch(Exception e) {
}
}
}
And this is my code inside the ecframe.java:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String textFieldValue = jTextField1.getText();
JOptionPane.showMessageDialog(this, "Added: \nEmail: " + textFieldValue);
}
Is this because of the "private". It's confusing for me. Thanks in advance!
make con static variable in ec.java, then on ecframe on button action event call the mysql statement, and create the statement by calling the static connection con variable
package emailcollector;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class ec {
public static Connection con;
public static void main(String[] args) {
try{
con = DriverManager.getConnection("jdbc:mysql://localhost", "admin", "pass");
}catch(Exception e) {
}
}
}
ecframe.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String textFieldValue = jTextField1.getText();
Statement stmt = (Statement) ec.con.createStatement();
String email = textFieldValue;
String insert = "INSERT INTO emails VALUES ('" + email + ")";
stmt.executeUpdate(insert);
}
Instead of making things static, often times I like to make my components independent of one another. In particular, I like the way that JFileChooser and JColorChooser work, so I like to emulate their functionality here by using either a modal JDialog, or a JOptionPane.
For example, here's a simple panel that represents a form that takes an email:
class EmailForm extends JPanel {
private JTextField emailField = new JTextField(20);
public EmailForm() {
add(new JLabel("Email"));
add(emailField);
}
public String getEmail() {
return emailField.getText();
}
}
And in your main method, you'd simply say:
EmailForm form = new EmailForm();
int option = JOptionPane.showConfirmDialog(null, form, "Email", JOptionPane.YES_NO_OPTION);
if (option == JOptionPane.YES_OPTION) {
System.out.println(form.getEmail());
}
Now, if in your case the form can't be made independent, and the class that holds that database connection represents a context without which the UI cannot function properly, then you might want to occasionally pass a dependency like that to the main form's constructor. Other than that, you can fiddle with actions, event listeners, or even the factory pattern as others have suggested.
There are a number of ways you could achieve this, this is just one (and it's a start of a very BASIC example of a possible Factory pattern)
You need to provide some way so that the ec class can expose its functionality...
Something more like...
public class EmailManager {
private Connection con;
protected Connection getConnection() {
if (connection == null) {
con = DriverManager.getConnection("jdbc:mysql://localhost", "admin", "pass");
}
return con;
}
public void close() throws SQLException {
if (con != null) {
con.close();
}
con = null;
}
public void insertEmail(String email) throws SQLException {
Statement stmt = null;
try {
Statement stmt = getConnection().createStatement();
int count = stmt.execute("insert into emails values ('" + email + "')");
if (count != 1) {
throw new SQLException("Failed to insert new email");
}
} finally {
try {
stmt.close();
} catch (Exception exp) {
}
}
}
}
Then in your UI class, you simple create an instance of ec and access it's methods as required...
private EmailManager manager;
/*...*/
protected EmailManager getEMailManager() {
if (manager == null) {
manager = new EmailManager();
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String textFieldValue = jTextField1.getText();
try {
getEMailManager().insertEmail(textFieldValue);
} catch (SQLException exp) {
JOptionPane.showMessageDialog(this, "Failed to insert email into database", "Error", JOptionPane.ERROR_MESSAGE);
exp.printStackTrace();
}
}
No offense, but all of this is basic OO programming. You might like to take a read through Classes and Objects for more details and ideas
You may also like to take a look at Code Conventions for the Java Programming Language