Android development
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="180dp"
android:background="@drawable/images"
android:fontFamily="cursive"
android:paddingVertical="70dp"
android:text="Login"
android:textAlignment="center"
android:textColor="#090909"
android:textSize="30dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="30dp"
android:layout_marginTop="35dp"
android:text="User name"
android:textColor="@color/colorAccent" />
<EditText
android:id="@+id/etuser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="30dp"
android:layout_marginBottom="30dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="30dp"
android:layout_marginTop="10dp"
android:text="Password"
android:textColor="@color/colorAccent" />
<EditText
android:id="@+id/etpassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="30dp"
android:layout_marginTop="15dp"
android:layout_marginBottom="35dp"
android:inputType="textPassword" />
<Button
android:id="@+id/btnlogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"
android:background="@drawable/button_bg"
android:text="Login" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="No Account Yet? Create an Account"
android:textAlignment="center" />
</LinearLayout>
2nd
File handling
public class Testing {
public static void main(String[] args) {
//File Handling in Java
String text = "This is some content";
Path filePath = Paths.get("myfile.txt");
// //Java 11+
Files.writeString(filePath, text);
try {
Files.write(filePath, text.getBytes());
} catch(IOException e){
e.printStackTrace();
System.out.println("Unable to create file");
}
Path filePath = Paths.get("myfile.txt");
// Java 11
// String content = Files.readString(filePath);
try {
byte[] fileBytes = Files.readAllBytes(filePath);
String content = new String(fileBytes);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Unable to read file");
}
Exceptional handling
public class Testing {
public static void main(String[] args) {
String txt = "abc";
try{
char a = txt.charAt(5);
int x = Integer.parseInt(txt);
System.out.println("Hello");
System.out.println("Hi");
} catch(Exception e){
e.printStackTrace();
if(e instanceof NumberFormatException){
} else if(e instanceof NullPointerException){
} finally {
try {
System.out.println("FInally Block");
} catch (Exception e) {
//TODO: handle exception
}
System.out.println("after try catch in finally");
}
System.out.println("Done");
}
}
Login frame
public class Loginframe extends JFrame {
public Loginframe(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400 , 400);
setResizable(false);
setLayout(null);
setTitle("Login");
JLabel lblu = new JLabel();
lblu.setText("UserName");
lblu.setBounds(80,70,100,30);
add(lblu);
JTextField txtuser =new JTextField();
txtuser.setBounds(80,100,150,20);
add(txtuser);
JLabel lblp = new JLabel();
lblp.setText("Password");
lblp.setBounds(80,120,100,30);
add(lblp);
JPasswordField txtpass = new JPasswordField();
txtpass.setBounds(80,150,150,20);
add(txtpass);
JCheckBox chkshow = new JCheckBox();
chkshow.setText("Show Password");
chkshow.setBounds(80,170,150,30);
add(chkshow);
JButton btnlogin = new JButton();
btnlogin.setText("Login");
btnlogin.setBounds(100,220,120,30);
add(btnlogin);
btnlogin.addActionListener(new java.awt.event.ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
String UserName = txtuser.getText();
String Password =txtpass.getText();
if(UserName.equals("Waqas Rana" ) &&
Password.equals("218222")){
JOptionPane.showMessageDialog(Loginframe.this,
"Welcome");
}
else{
JOptionPane.showMessageDialog(Loginframe.this,
"Invalid");
}
});
chkshow.addActionListener(new java.awt.event.ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if(chkshow.isSelected()){
txtpass.setEchoChar((char)0);
} else
{
txtpass.setEchoChar('*');
}
}});
Db project
Add product frame
public class AddProductFrame extends JFrame {
public AddProductFrame(){
setLayout(null);
setSize(400, 400);
setResizable(false);
setLocationRelativeTo(null);
setAlwaysOnTop(true);
setTitle("Add Product");
JLabel lblName = new JLabel("Name");
lblName.setBounds(100, 50, 100, 30);
add(lblName);
JTextField txtName = new JTextField();
txtName.setBounds(100, 80, 200, 30);
add(txtName);
JLabel lblPrice = new JLabel("Price");
lblPrice.setBounds(100, 110, 100, 30);
add(lblPrice);
JTextField txtPrice = new JTextField();
txtPrice.setBounds(100, 140, 200, 30);
add(txtPrice);
JButton btnSave = new JButton("Save");
btnSave.setBounds(100, 190, 200, 30);
add(btnSave);
btnSave.addActionListener(new java.awt.event.ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
if(txtName.getText().isEmpty()){
} else if(txtPrice.getText().isEmpty()){
} else {
String name = txtName.getText();
float price = Float.parseFloat(txtPrice.getText());
try {
Connection con = DbHelper.connectDb();
String query = "INSERT INTO tbl_products(name,
price) VALUES(?, ?)";
PreparedStatement stmt =
con.prepareStatement(query);
stmt.setString(1, name);
stmt.setFloat(2, price);
int rowsAffected = stmt.executeUpdate();
stmt.close();
con.close();
if(rowsAffected > 0 ){
//product added succesffully
JOptionPane.showMessageDialog(getContentPane(), "Product Added
Successfully");
txtName.setText("");
txtPrice.setText("");
} else {
//failed to add products
JOptionPane.showMessageDialog(getContentPane(), "Unable to add product in
database", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
});
App
public class App {
public static void main(String[] args) throws Exception {
System.out.println("Hello, World!");
LoginFrame frame = new LoginFrame();
//UpdateProductFrame frame = new UpdateProductFrame();
frame.setVisible(true);
}
}
Database helper
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbHelper {
public static Connection connectDb() throws SQLException{
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/shopdb", "root",
"");
return con;
}
Login frame
public class LoginFrame extends JFrame {
public LoginFrame() {
// setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setResizable(false);
setLayout(null);
setLocationRelativeTo(null);
setTitle("Login");
JLabel lblUsername = new JLabel();
lblUsername.setText("Username");
lblUsername.setBounds(100, 50, 100, 30);
add(lblUsername);
JTextField txtUsername = new JTextField();
txtUsername.setBounds(100, 80, 200, 30);
add(txtUsername);
JLabel lblPassword = new JLabel();
lblPassword.setText("Password");
lblPassword.setBounds(100, 110, 200, 30);
add(lblPassword);
JPasswordField txtPassword = new JPasswordField();
txtPassword.setBounds(100, 140, 200, 30);
add(txtPassword);
JCheckBox chkShowPassword = new JCheckBox();
chkShowPassword.setText("Show Password");
chkShowPassword.setBounds(100, 170, 150, 30);
add(chkShowPassword);
JButton btnLogin = new JButton();
btnLogin.setText("Login");
btnLogin.setBounds(125, 220, 150, 30);
add(btnLogin);
btnLogin.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String username = txtUsername.getText();
String password = txtPassword.getText();
try {
Connection con = DbHelper.connectDb();
String query = "SELECT * FROM tbl_users WHERE
username=? AND password=?";
PreparedStatement stmt = con.prepareStatement(query);
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
if(rs.isBeforeFirst()){
//it has rows
JOptionPane.showMessageDialog(getContentPane(),
"Login Successful");
stmt.close();
con.close();
setVisible(false);
MainFrame frame = new MainFrame();
frame.setVisible(true);
} else {
JOptionPane.showMessageDialog(getContentPane(),
"Invalid username/password", "Error", JOptionPane.ERROR_MESSAGE);
stmt.close();
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(getContentPane(),
"Something went wrong with database!", "Error",
JOptionPane.ERROR_MESSAGE);
}
});
chkShowPassword.addActionListener(new
java.awt.event.ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (chkShowPassword.isSelected()) {
txtPassword.setEchoChar((char) 0);
} else {
txtPassword.setEchoChar('*');
}
});
}
private void connectDb() {
try {
// Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/ShopDB", "root",
"");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM tbl_users");
while (rs.next()) {
System.out.println(rs.getInt("id") + " " +
rs.getString("username") + " " + rs.getString("password"));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Mainframe
public class MainFrame extends JFrame {
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setResizable(false);
setLayout(null);
setTitle("Shop POS");
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu productsMenu = new JMenu("poducts");
menuBar.add(productsMenu);
JMenuItem addProductsMenuItem = new JMenuItem("Add Products");
productsMenu.add(addProductsMenuItem);
JMenuItem updateProductsMenuItem = new JMenuItem("Update
Products");
productsMenu.add(updateProductsMenuItem);
addProductsMenuItem.addActionListener(new
java.awt.event.ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
AddProductFrame frame = new AddProductFrame();
frame.setVisible(true);
}
});
updateProductsMenuItem.addActionListener(new
java.awt.event.ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
UpdateProductFrame frame = new UpdateProductFrame();
frame.setVisible(true);
});
Update product frame
public class UpdateProductFrame extends JFrame {
public UpdateProductFrame(){
setLayout(null);
setSize(400, 400);
setResizable(false);
setLocationRelativeTo(null);
setAlwaysOnTop(true);
setTitle("Update Product");
JLabel lblID = new JLabel("Product ID");
lblID.setBounds(100, 50, 100, 30);
add(lblID);
JTextField txtID = new JTextField();
txtID.setBounds(100, 80, 200, 30);
add(txtID);
JLabel lblName = new JLabel("Name");
lblName.setBounds(100, 110, 100, 30);
add(lblName);
JTextField txtName = new JTextField();
txtName.setBounds(100, 140, 200, 30);
txtName.setEnabled(false);
add(txtName);
JLabel lblPrice = new JLabel("Price");
lblPrice.setBounds(100, 170, 100, 30);
add(lblPrice);
JTextField txtPrice = new JTextField();
txtPrice.setBounds(100, 200, 200, 30);
txtPrice.setEnabled(false);
add(txtPrice);
JButton btnSave = new JButton("Save");
btnSave.setBounds(100, 250, 200, 30);
add(btnSave);
txtID.addKeyListener(new java.awt.event.KeyListener(){
@Override
public void keyPressed(KeyEvent e) {
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
if(txtID.getText().isEmpty()){
return;
}
int id = Integer.parseInt(txtID.getText());
try {
Connection con = DbHelper.connectDb();
String query = "SELECT * FROM tbl_products WHERE
id=?";
PreparedStatement stmt =
con.prepareStatement(query);
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
if(rs.isBeforeFirst()){
rs.next();
String name = rs.getString("name");
float price = rs.getFloat("price");
txtName.setText(name);
txtPrice.setText(String.valueOf(price));
txtID.setEnabled(false);
txtName.setEnabled(true);
txtPrice.setEnabled(true);
} else {
JOptionPane.showMessageDialog(getContentPane(), "Product Not Found",
"Error", JOptionPane.ERROR_MESSAGE);
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
});
btnSave.addActionListener(new java.awt.event.ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if(txtName.getText().isEmpty()){
} else if(txtPrice.getText().isEmpty()){
} else {
String name = txtName.getText();
float price = Float.parseFloat(txtPrice.getText());
int id = Integer.parseInt(txtID.getText());
try {
Connection con = DbHelper.connectDb();
String query = "UPDATE tbl_products SET name=?,
price=? WHERE id=?";
PreparedStatement stmt =
con.prepareStatement(query);
stmt.setString(1, name);
stmt.setFloat(2, price);
stmt.setInt(3, id);
int rowsAffected = stmt.executeUpdate();
if(rowsAffected > 0){
JOptionPane.showMessageDialog(getContentPane(), "Product Updated
Successfully");
txtID.setText("");
txtName.setText("");
txtPrice.setText("");
txtID.setEnabled(true);
txtName.setEnabled(false);
txtPrice.setEnabled(false);
} else {
JOptionPane.showMessageDialog(getContentPane(), "Unable to update product
in database", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});