RSS

Kateqoriya Arxivləri: SWİNG

Login Form with database in JAVA Swing

Bugün sizə mysql ile login nümünəsini göstəəcəm.

1.ilk öncə users adinda bir table olmalidı

2.users.java adinda class

3.DBConnection (mysql)

4.LoginPage  (Jframe) login form səhifəmiz.

Table yaradiriq.

create table mydb.users (
id int AUTO_INCREMENT Primary key,
username varchar(30) ,
password varchar(30)
);

table

Users.java classimizi yaradib Construktor və get set  metodlarini yazırıq.

package aqil.isa;

/**
*
* @author AqilI
*/
public class Users {
private int id;
private String username;
private String password;

public Users() {
}

public Users(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

}

Connection classımızı yaradib login methodumuzu yaziriq.

package aqil.isa;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
*
* @author AqilI
*/
public class DBConnection {

private Connection conn = null;
private PreparedStatement ps = null;
private ResultSet rs = null;
private String user = “root”;
private String password = “sizin şıfrəniz“;
private String url = “sizin mysqlDB url“;

public void getConnection() throws SQLException {
try {
Class.forName(“com.mysql.jdbc.Driver”);
conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException cnf) {
cnf.printStackTrace();
System.out.println(“Mysql Db baglanmada xeta: ” + cnf.getMessage());
}
}

public void closedConnection() {
try {
if (conn != null) {
conn.close();
}
if (ps != null) {
ps.close();
}
} catch (Exception e) {
System.out.println(“Connection Baglanmadi! ” + e.getMessage());
e.printStackTrace();
}
}

public boolean usersLogin(String username, String password) {
Boolean b = false;
try {
getConnection();
String sql = “select * from mydb.users where username= ‘” + username + “‘ and password= ‘” + password + “‘”;
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
return rs.next();

} catch (SQLException ex) {
ex.printStackTrace();
System.out.println(“User Login xeta ” + ex.getMessage());
return false;
} finally {
closedConnection();
}

}
public static void main(String[] args) {
DBConnection db= new DBConnection();
System.out.println(db.usersLogin(“aqil“, “1234“));
}

}

//test edek gore bazaya qoşula bilirik.

// DBConnection classımızı run edirik.rsult

True qaytardi demeli metodumuz duzgun çalışır.

artıq login pəncərəmizi hazırlayib login ola bilərikş hazirlayaq.

package aqil.isa;

import java.awt.Color;
import javax.swing.JOptionPane;

/**
*
* @author AqilI
*/
public class LoginPage extends javax.swing.JFrame {
DBConnection dbc = new DBConnection();
public LoginPage() {
initComponents();
setLocationRelativeTo(this);
setTitle(“Login Page Example”);
}
@SuppressWarnings(“unchecked”)
// <editor-fold defaultstate=”collapsed” desc=”Generated Code”>
private void initComponents() {

jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
txtUsername = new javax.swing.JTextField();
txtPassword = new javax.swing.JPasswordField();
btnLogin = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jPanel1.setBackground(new java.awt.Color(91, 113, 135));

jLabel1.setFont(new java.awt.Font(“Times New Roman”, 1, 14)); // NOI18N
jLabel1.setForeground(java.awt.SystemColor.window);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource(“/itmim/images/user.png”))); // NOI18N
jLabel1.setText(“Username”);

jLabel2.setFont(new java.awt.Font(“Times New Roman”, 1, 14)); // NOI18N
jLabel2.setForeground(java.awt.SystemColor.window);
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource(“/itmim/images/password.png”))); // NOI18N
jLabel2.setText(“Password”);

btnLogin.setFont(new java.awt.Font(“Times New Roman”, 1, 14)); // NOI18N
btnLogin.setForeground(java.awt.SystemColor.window);
btnLogin.setIcon(new javax.swing.ImageIcon(getClass().getResource(“/itmim/images/sign.png”))); // NOI18N
btnLogin.setText(“Login”);
btnLogin.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
btnLogin.setContentAreaFilled(false);
btnLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoginActionPerformed(evt);
}
});

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(97, 97, 97)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(38, 38, 38)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
.addComponent(txtPassword))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(174, Short.MAX_VALUE)
.addComponent(btnLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(168, 168, 168))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(58, 58, 58)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtPassword)
.addGap(1, 1, 1)))
.addGap(18, 18, 18)
.addComponent(btnLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(38, Short.MAX_VALUE))
);

jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jLabel1, jLabel2});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);

pack();
}// </editor-fold>

private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
if (dbc.usersLogin(txtUsername.getText().trim(), txtPassword.getText().trim())) {
txtUsername.setForeground(Color.GREEN);
txtPassword.setForeground(Color.GREEN);
JOptionPane.showMessageDialog(rootPane, “Your login successful!”);
} else {
JOptionPane.showMessageDialog(rootPane, “Your login failed!”);
txtUsername.setText(“”);
txtPassword.setText(“”);
}
}

public static void main(String args[]) {

java.awt.EventQueue.invokeLater(() -> {
new LoginPage().setVisible(true);
});
}

// Variables declaration – do not modify
private javax.swing.JButton btnLogin;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPasswordField txtPassword;
private javax.swing.JTextField txtUsername;
// End of variables declaration
}

login page görüntü.

txtuser

test edek:

 
3 Şərh

Müəllif Açıq 29 Noyabr 2016 in SWİNG

 

2. java swing insert

Əvvəli dərsimiz üzrə davam edək.
data base insert  edəcəyik.

bunun bir forma hazir edək

insert

öncə Connection classimizda insert metodunu yazaq.

public void insertExample(Example e) {
try {
connection();
String sql;
sql = “Insert into invertar.example (name,birthday,status) Values( ? ,?,?)”;

psate = conn.prepareStatement(sql);
psate.setString(1, e.getName());
psate.setDate(2, (Date) e.getBirthday());
psate.setString(3, e.getStatus());
psate.executeUpdate();
} catch (SQLException sqlex) {
System.out.println(“insert xeta : ” + sqlex.getMessage());
sqlex.printStackTrace();
} finally {
closed();
}
}

jframe insert buttonun actionuna

private void btnInsertActionPerformed(java.awt.event.ActionEvent evt) {

try {
e.setName(txtName.getText());
int day = txtDate.getDate().getDate();
int mounth = txtDate.getDate().getMonth() + 1;
int year = 1900 + txtDate.getDate().getYear();
Date d = Date.valueOf(year + “-” + mounth + “-” + day);
e.setBirthday(d);
e.setStatus(“A”);
con.insertExample(e);
JOptionPane.showMessageDialog(rootPane, “Informasions Insert Data Base!”);

}

 

 

 
Bir şərh yazın

Müəllif Açıq 27 Noyabr 2016 in SWİNG

 
Təsvir

1.Java Swing JTable doldurmaq MySql ilə

1.ctreate table in mysql

create table invertar.Example(
id int auto_increment Primary Key,
name varchar(30),
birthday Date,
status varchar(1)  //sonra bize lazimolar..
)

  1. java  example classimizi yaradırıq.

package az;

import java.util.Date;

/**
*
* @author AqilI
*/

public class Example {
private int id;
private String name;
private Date birthday;
private String status;

public Example() {
}

public Example(int id, String name, Date birthday,String status) {
this.id = id;
this.name = name;
this.birthday = birthday;
this.status=status;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Date getBirthday() {
return birthday;
}

public void setBirthday(Date birthday) {
this.birthday = birthday;
}

public String getStatus() {
return status;
}

public void setStatus(String status) {
this.status = status;
}

}

3.Connection classımızı yaradaq.    // proyektə  mysq jar file əlavə etməyi unutmayin))

import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import logn.Login;

/**
*
* @author AqilI
*/
public class Connection {

private static java.sql.Connection conn = null;
private static PreparedStatement psate = null;
private static ResultSet rs = null;
private static final String user = “root”;
private static final String password = “sizin şifrə“;
private static final String url = “mysql url“;

public static void connection() throws SQLException {
try {
Class.forName(“com.mysql.jdbc.Driver”);
conn = DriverManager.getConnection(url, user, password);

} catch (ClassNotFoundException e) {
System.out.println(“Driver tapilmadi: ” + ” ” + e.getMessage());
e.printStackTrace();
}
}

public static void closed() {
try {
if (conn != null) {
conn.close();
}
if (psate != null) {
psate.close();
}
} catch (Exception e) {
System.out.println(“Connection Baglanmadi! ” + e.getMessage());
e.printStackTrace();
}
}

//listlə doldururuq

public List<Example> allExample() throws Exception {
try {
connection();
List<Example> exmple = new ArrayList<>();
String sql = “select * from invertar.example“;
psate = conn.prepareStatement(sql);
rs = psate.executeQuery();
while (rs.next()) {
Example e = new Example();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setBirthday(rs.getDate(3));

exmple .add(e);

}
return exmple ;
} catch (SQLException sql) {
System.out.println(“Xeta: ” + sql.getMessage());
sql.printStackTrace();
return null;
} finally {
closed();
}
}

//table header

public List<String> headerExample() {
List<String> head = new ArrayList<String>();
head.add(“Id”);
head.add(“Name”);
head.add(“Birthday”);
return head;
}

}

4.Table model classimizi yaradaq.

package az;

import java.util.List;
import javax.swing.table.AbstractTableModel;

/**
*
* @author AqilI
*/
public class ExampleTableModel extends AbstractTableModel {

private List<Example> list;
private List<String> head;

public ExampleTableModel(List<Example> list, List<String> head) {
this.list = list;
this.head = head;
}

@Override
public String getColumnName(int column) {
return head.get(column);
}

@Override
public int getRowCount() {
return list.size();
}

@Override
public int getColumnCount() {
return head.size();
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (columnIndex == 0) {
return list.get(rowIndex).getId();
} else if (columnIndex == 1) {
return list.get(rowIndex).getName();
} else {
return list.get(rowIndex).getBirthday();
}
}
}

  1. jframe Table form

package az;

import java.awt.Color;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ListSelectionModel;

/**
*
* @author AqilI
*/
public class ExampleTable extends javax.swing.JFrame {

final Connection con = new Connection();
final Example e = new Example();

public ExampleTable() {
try {
initComponents();
setLocationRelativeTo(this);
setTitle(“Example Table from“);
refleshTbModel();
tbExample.setShowGrid(true);
tbExample.setSelectionForeground(Color.RED);
tbExample.setSelectionBackground(Color.LIGHT_GRAY);
tbExample.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tbExample.setRowHeight(20);
tbExample.setRowSelectionAllowed(true);
this.pack();

} catch (Exception ex) {
Logger.getLogger(ExampleTable.class.getName()).log(Level.SEVERE, null, ex);
}
}

public void refleshTbModel() throws Exception {
ExampleTableModel table_Model = new ExampleTableModel(con.allExample(), con.headerExample());
tbExample.setModel(table_Model);

}

@SuppressWarnings(“unchecked”)
// <editor-fold defaultstate=”collapsed” desc=”Generated Code”>
private void initComponents() {

jScrollPane1 = new javax.swing.JScrollPane();
tbExample = new javax.swing.JTable();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jScrollPane1.setViewportView(tbExample);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 635, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(14, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);

pack();
}// </editor-fold>

/**
* @param args the command line arguments
/
public static void main(String args[]) {
/
Set the Nimbus look and feel /
//<editor-fold defaultstate=”collapsed” desc=” Look and feel setting code (optional) “>
/
If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if (“Nimbus”.equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ExampleTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ExampleTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ExampleTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ExampleTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ExampleTable().setVisible(true);
}
});
}

// Variables declaration – do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tbExample;
// End of variables declaration
}

 

table

\ davami olaraq insert, delete, update ,search və jogin page hissələrini paylaşmağacçalışaram.

 
Bir şərh yazın

Müəllif Açıq 27 Noyabr 2016 in SWİNG

 

Jframe full screen size açılması

Bəzən Jframe’lərdə elə problem qarşılaşırıq ki, biz öz komputerimizin ölçülərinə uyğun  ölçü veririk ama manitoru fərqli komputerlərdə çalışdırdığımız zamanı  dizayn pozğunluğu yaranır.
bunun həlli aşağıda göstərmişəm ,yəni hər run zamani  həmin komputer manitorunun fullScreen size ölçülərinə uyğun açılır..

 

package itmim.view;

import java.awt.Toolkit;

/**
*
* @author AqilI
*/
public class FullScren extends javax.swing.JFrame {

Toolkit tk = Toolkit.getDefaultToolkit();
public int WindowWidth = (int) tk.getScreenSize().getWidth();
public int WindowHeight = (int) tk.getScreenSize().getHeight();

public FullScren() {
initComponents();
setLocationRelativeTo(this);
this.setSize(WindowWidth, WindowHeight);
this.setLocation(0, 0);
}
@SuppressWarnings(“unchecked”)
// <editor-fold defaultstate=”collapsed” desc=”Generated Code”>
private void initComponents() {

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);

pack();
}// </editor-fold>

public static void main(String args[]) {

java.awt.EventQueue.invokeLater(() -> {
new FullScren().setVisible(true);
});
}

// Variables declaration – do not modify
// End of variables declaration
}

 
Bir şərh yazın

Müəllif Açıq 27 Noyabr 2016 in SWİNG

 

TextField-i numeric formata qoymaq

əgər textField’ə ancaq rəqəm tipinin daxil edliməsini lazim gəlsə

həmin textField’in  üstünə sağ tıklayib   Events>Key>KeyPressed actionuna aşağıdakı kodu yazmaq lazım

2016-11-27_024756

private void txtNumberFormatKeyPressed(java.awt.event.KeyEvent evt) {

{
int key = evt.getKeyCode();
if ((key >= evt.VK_0 && key <= evt.VK_9) || (key >= evt.VK_NUMPAD0 && key <= evt.VK_NUMPAD9) || key == KeyEvent.VK_BACK_SPACE) {
txtNumberFormat.setForeground(Color.GREEN);
} else {
JOptionPane.showMessageDialog(rootPane, “Yalnız rəqəm tipində daxil edin!”);
txtNumberFormat.setText(“”);
}
}

əgər rəqəm  tipindən fərqli tipdaxil edilərsə
}eeee

rəqəm tipi daxil edilərsə:

rrr

Uğurlar:)

 
1 Şərh

Müəllif Açıq 27 Noyabr 2016 in SWİNG

 
 
%d bloqqer bunu bəyənir: