DATAONLINE.IO.VN

https://365.io.vn

Gradle Java Desktop Application và SQLite

Gradle Java Desktop Application và SQLITE.

Gradle Java Desktop Application và SQLite

settings.gradle

rootProject.name = 'javadbsqlite'
include('app')
project(":app").name = "GradleJavaSQLLITEDB"

build.gradle

plugins {
    // Apply the application plugin to add support for building a CLI application in Java.
    id 'application'
}

java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(8)) //Yêu cầu từ Java 8 trở lên
        vendor = JvmVendorSpec.ADOPTOPENJDK
    }
}

compileJava {options.encoding = "UTF-8"}   
compileTestJava {options.encoding = "UTF-8"}
tasks.withType(JavaCompile) {
    options.encoding = "UTF-8"
}

repositories {
    // Use Maven Central for resolving dependencies.
    mavenCentral()
}

dependencies {
    // Use JUnit Jupiter for testing.
    // testImplementation 'org.junit.jupiter:junit-jupiter:5.7.2'

    // This dependency is used by the application.
    // implementation 'com.google.guava:guava:30.1.1-jre'
    runtimeOnly 'org.xerial:sqlite-jdbc:3.36.0.3'
}
mainClassName = 'javadbsqlite.frmMain'
application {
    // Define the main class for the application.
    mainClass = mainClassName
}

jar {     
    manifest {      
        attributes( 'Main-Class': mainClassName)                   
    }
    from {
        duplicatesStrategy = DuplicatesStrategy.INCLUDE
        configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
    }
}

tasks.named('test') {
    // Use JUnit Platform for unit tests.
    useJUnitPlatform()
}

frmMain.java

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package javadbsqlite;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.io.File;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.table.JTableHeader;
import javax.swing.text.JTextComponent;

/**
 *
 * @author admin
 */
public class frmMain extends javax.swing.JFrame {

    private final String javaversion;
    private int id = -1;
    private JLabel lbldbname = new JLabel("Tên cơ sở dữ liệu:", JLabel.LEFT);
    private JComboBox cbodbname = new JComboBox();
    private JButton btnOpenDatabase = new JButton("Open Database");
    private JButton btnDeleteDatabase = new JButton("Delete Database");
    private JButton btnCloseDatabase = new JButton("Close Database");
    private JButton btnAdd = new JButton("Add");
    private JButton btnSave = new JButton("Save");
    private JButton btnDelete = new JButton("Delete");
    private JButton btnClose = new JButton("Close");
    private JScrollPane scrollPane = new JScrollPane();
    private DefaultTableModel dm = new javax.swing.table.DefaultTableModel() {
        @Override
        public Class<?> getColumnClass(int column) {
            switch (column) {
                case 0:
                    return Integer.class;
                case 1:
                    return String.class;
                case 2:
                    return Float.class;
                default:
                    return String.class;
            }
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            if (column == 0) {
                return false;
            } else {
                return false;
            }
        }
    };
    private JTable table = new JTable(dm) {
        @Override
        public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            Component component = super.prepareRenderer(renderer, row, column);
            int rendererWidth = component.getPreferredSize().width;
            TableColumn tableColumn = getColumnModel().getColumn(column);
            tableColumn.setPreferredWidth(Math.max(rendererWidth + getIntercellSpacing().width, tableColumn.getPreferredWidth()));
            return component;
        }
    };

    private final JLabel lblname = new JLabel("Name:", JLabel.LEFT);
    private final JTextField txtname = new JTextField();
    private final JLabel lblmoney = new JLabel("Money:", JLabel.LEFT);
    private final JTextField txtmoney = new JTextField();
    private final String fileseparator = System.getProperty("file.separator");
    private final File fileFolder = new File("Databases");
    private final String filedbType = ".db";
    private Connection conn = null;
    private int dbindex = -1;
    private boolean dbmoney = false;
    private String valuedbname = "";

    private void SUM(JTable table, int column) {
        if (table.getRowCount() < 1) {
            return;
        }
        NumberFormat format = DecimalFormat.getInstance();
        format.setGroupingUsed(true);
        format.setMinimumFractionDigits(0);
        float sum = 0;
        int row = 0, rowcout = table.getRowCount();
        try {

            for (row = 0; row < rowcout; row++) {
                sum = sum + format.parse(table.getValueAt(row, column).toString()).floatValue();
            }
            dm.insertRow(row, new Object[]{" ", "Cộng:", sum});
        } catch (ParseException e) {

        }
    }

    private String getFileName(String S) {
        int index = S.lastIndexOf(".");
        if (index > -1) {
            S = S.substring(0, index);
        }
        return S;
    }

    private void loaddbname() {
        if (!fileFolder.exists()) {
            fileFolder.mkdir();
        }
        File[] listOfFiles = fileFolder.listFiles();
        if (listOfFiles.length > 0) {
            String files = null, name = "";
            for (int i = 0; i < listOfFiles.length; i++) {
                if (listOfFiles[i].isFile()) {
                    files = listOfFiles[i].getName();
                    if (files.endsWith(filedbType) || files.endsWith(filedbType.toUpperCase())) {
                        name = getFileName(files);
                        if (((DefaultComboBoxModel) cbodbname.getModel()).getIndexOf(name) == -1) {
                            cbodbname.addItem(name);
                        }
                        if (name.toLowerCase().equals("money")) {
                            dbmoney = true;
                        }
                    }
                }
            }
        } else {
            cbodbname.removeAllItems();
            cbodbname.addItem("money");
        }
    }

    private void OpenDatabase() {
        try {
            String value = this.valuedbname;
            Class.forName("org.sqlite.JDBC");
            File filecurent = new File(fileFolder.getCanonicalPath().concat(fileseparator).concat(cbodbname.getSelectedItem().toString().concat(filedbType)));
            String dbURL = "jdbc:sqlite:".concat(filecurent.getCanonicalPath());
            if (!filecurent.getParentFile().exists()) {
                filecurent.mkdir();
            }
            conn = DriverManager.getConnection(dbURL);
            if (conn != null) {
                btnOpenDatabase.setEnabled(false);
                btnCloseDatabase.setEnabled(true);
                btnDeleteDatabase.setEnabled(false);
                btnAdd.setEnabled(true);
                btnSave.setEnabled(false);
                btnDelete.setEnabled(false);
                btnClose.setEnabled(true);
                txtname.setEnabled(false);
                txtmoney.setEnabled(false);
                if (!dbmoney) {
                    cbodbname.removeItem("money");
                }
                if (value.toLowerCase().equals("money")) {
                    dbmoney = true;
                }
                if (((DefaultComboBoxModel) cbodbname.getModel()).getIndexOf(value) == -1) {
                    cbodbname.addItem(value);
                }
                DatabaseMetaData dm = (DatabaseMetaData) conn.getMetaData();
                StringBuilder sb = new StringBuilder();
                sb.append(value).append("; ").append(dm.getDriverName()).append("; ").append(dm.getDatabaseProductName()).append("; ")
                        .append(dm.getDatabaseProductVersion());
                this.setTitle(sb.toString());
            }
        } catch (IOException | ClassNotFoundException | SQLException ex) {
        }
    }

    private void CloseDatabase() {
        try {
            if (conn != null) {
                conn.close();
                conn = null;
            }
            this.setTitle("");
            cbodbname.setSelectedIndex(-1);
            dm.setRowCount(0);
            btnOpenDatabase.setEnabled(true);
            btnCloseDatabase.setEnabled(false);
            btnDeleteDatabase.setEnabled(true);
            btnAdd.setEnabled(false);
            btnSave.setEnabled(false);
            btnDelete.setEnabled(false);
            btnClose.setEnabled(true);
            txtname.setText("");
            txtmoney.setText("");
            txtname.setEnabled(false);
            txtmoney.setEnabled(false);
        } catch (SQLException ex) {
        }
    }

    private void DeleteDatabase() {
        try {
            File filecurent = new File(fileFolder.getCanonicalPath().concat(fileseparator).concat(cbodbname.getSelectedItem().toString().concat(filedbType)));
            if (filecurent.delete()) {
                if (conn != null) {
                    conn.close();
                    conn = null;
                }
                this.setTitle("");
                cbodbname.removeItemAt(dbindex);
                cbodbname.setSelectedIndex(-1);
                dm.setRowCount(0);
                btnOpenDatabase.setEnabled(true);
                btnCloseDatabase.setEnabled(false);
                btnDeleteDatabase.setEnabled(true);
                btnAdd.setEnabled(false);
                btnSave.setEnabled(false);
                btnDelete.setEnabled(false);
                btnClose.setEnabled(true);
                txtname.setText("");
                txtmoney.setText("");
                txtname.setEnabled(false);
                txtmoney.setEnabled(false);
                cbodbname.requestFocusInWindow();
            }
        } catch (IOException | SQLException ex) {
            JOptionPane.showInternalMessageDialog(this, "Lỗi xóa cơ sở dữ liệu " + ex.getMessage(), "Xóa Database", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void createtbldmLop(Connection conn) {
        String sql = "CREATE TABLE IF NOT EXISTS tbldmLop(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR(50) NOT NULL, money REAL NOT NULL);";
        try {
            if (conn != null) {
                Statement stmt = conn.createStatement();
                stmt.execute(sql);
            }
        } catch (SQLException e) {

        }
    }

    private int inserttbldmLop(Connection conn) {
        int kq = 0;
        String name = txtname.getText();
        float money = Float.valueOf(txtmoney.getText());
        String sql = "INSERT INTO tbldmLop (name, money) VALUES ('" + name + "'," + money + ")";
        try {
            if (conn != null) {
                Statement stmt = conn.createStatement();
                kq = stmt.executeUpdate(sql);
            }
        } catch (SQLException e) {

        }
        return kq;
    }

    private int updatetbldmLop(Connection conn) {
        int kq = 0;
        NumberFormat format = DecimalFormat.getInstance();
        format.setGroupingUsed(true);
        format.setMinimumFractionDigits(0);
        String name = txtname.getText();
        try {
            float money = format.parse(txtmoney.getText()).floatValue();
            String sql = "UPDATE tbldmLop SET name = '" + name + "', money = " + money + " WHERE id = " + this.id;
            if (conn != null) {
                Statement stmt = conn.createStatement();
                kq = stmt.executeUpdate(sql);
            }
        } catch (SQLException | ParseException e) {

        }
        return kq;
    }

    private int deletetbldmLop(Connection conn) {
        int kq = 0;
        try {
            String sql = "DELETE FROM tbldmLop WHERE id = " + this.id;
            if (conn != null) {
                Statement stmt = conn.createStatement();
                kq = stmt.executeUpdate(sql);
            }
        } catch (SQLException e) {

        }
        return kq;
    }

    private int selecttbldmLop(Connection conn) {
        int kq = 0;
        String sql = "SELECT * FROM tbldmLop";
        try {
            if (conn != null) {
                Statement stmt = conn.createStatement();
                try ( ResultSet rs = stmt.executeQuery(sql)) {
                    int row = -1;
                    dm.setRowCount(0);
                    while (rs.next()) {
                        kq++;
                        row++;
                        dm.insertRow(row, new Object[]{rs.getInt(1),
                            rs.getString(2), rs.getFloat(3)});
                    }
                }
            }

        } catch (SQLException e) {

        }
        return kq;
    }

    private void GUI() {
        lbldbname.setBounds(5, 5, 150, 30);
        getContentPane().add(this.lbldbname);
        cbodbname.setEditable(true);
        cbodbname.setBounds(155, 5, 150, 30);
        getContentPane().add(this.cbodbname);
        btnOpenDatabase.setBounds(310, 5, 150, 30);
        btnOpenDatabase.setMnemonic(KeyEvent.VK_O);
        getContentPane().add(this.btnOpenDatabase);
        btnCloseDatabase.setBounds(465, 5, 150, 30);
        btnCloseDatabase.setMnemonic(KeyEvent.VK_C);
        getContentPane().add(this.btnCloseDatabase);
        btnDeleteDatabase.setBounds(615, 5, 150, 30);
        btnDeleteDatabase.setMnemonic(KeyEvent.VK_D);
        getContentPane().add(this.btnDeleteDatabase);
        scrollPane.setBounds(5, 50, 600, 400);
        scrollPane.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.red));
        getContentPane().add(this.scrollPane);
        scrollPane.setViewportView(table);
        scrollPane.repaint();
        table.setFont(new Font("Times New Roman", Font.PLAIN, 16));
        JTableHeader th = table.getTableHeader();
        th.setPreferredSize(new Dimension(30, 30));
        th.setFont(new Font("Times New Roman", Font.BOLD, 16));

        lblname.setBounds(610, 50, 100, 30);
        lblname.setDisplayedMnemonic(KeyEvent.VK_N);
        lblname.setLabelFor(txtname);
        getContentPane().add(this.lblname);
        txtname.setBounds(715, 50, 400, 30);
        getContentPane().add(this.txtname);

        lblmoney.setBounds(610, 85, 100, 30);
        lblmoney.setDisplayedMnemonic(KeyEvent.VK_M);
        lblmoney.setLabelFor(txtmoney);
        getContentPane().add(this.lblmoney);
        txtmoney.setBounds(715, 85, 200, 30);
        getContentPane().add(this.txtmoney);

        btnAdd.setBounds(715, 120, 100, 30);
        btnAdd.setMnemonic(KeyEvent.VK_A);
        getContentPane().add(this.btnAdd);
        btnSave.setBounds(820, 120, 100, 30);
        btnSave.setMnemonic(KeyEvent.VK_S);
        getContentPane().add(this.btnSave);
        btnDelete.setBounds(925, 120, 100, 30);
        btnDelete.setMnemonic(KeyEvent.VK_L);
        getContentPane().add(this.btnDelete);
        btnClose.setBounds(1030, 120, 100, 30);
        btnClose.setMnemonic(KeyEvent.VK_E);
        getContentPane().add(this.btnClose);
        cbodbname.addActionListener((ActionEvent e) -> {
            this.dbindex = cbodbname.getSelectedIndex();
        });

        cbodbname.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {

            }

            @Override
            public void keyReleased(KeyEvent e) {
                if (e.getKeyChar() == KeyEvent.VK_ENTER) {
                    if (((JTextComponent) ((JComboBox) ((Component) e
                            .getSource()).getParent()).getEditor()
                            .getEditorComponent()).getText().trim().isEmpty()) {
                        valuedbname = "";
                        cbodbname.requestFocusInWindow();
                    } else {
                        btnOpenDatabase.requestFocusInWindow();
                    }
                }
            }

            @Override
            public void keyTyped(KeyEvent e) {
                char c = e.getKeyChar();
                if (!(Character.isAlphabetic(c)
                        || Character.isDigit(c)
                        || (c == KeyEvent.VK_BACK_SPACE)
                        || (c == KeyEvent.VK_DELETE))) {
                    e.consume();
                }
            }
        });

        txtname.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyChar() == KeyEvent.VK_ENTER) {
                    if (txtname.getText().trim().isEmpty()) {
                        txtname.requestFocusInWindow();
                    } else {
                        txtmoney.requestFocusInWindow();
                    }
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {

            }

            @Override
            public void keyTyped(KeyEvent e) {

            }
        });
        txtmoney.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyChar() == KeyEvent.VK_ENTER) {
                    if (txtmoney.getText().trim().isEmpty()) {
                        txtmoney.requestFocusInWindow();
                    } else {
                        btnSave.requestFocusInWindow();
                    }
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {

            }

            @Override
            public void keyTyped(KeyEvent e) {
                DecimalFormatSymbols symbols = new DecimalFormatSymbols();
                char c = e.getKeyChar();
                char decimalSeparator = symbols.getDecimalSeparator();
                long count = txtmoney.getText().chars().filter(ch -> ch == decimalSeparator).count();
                if (count == 0) {
                    if (!(Character.isDigit(c)
                            || (c == KeyEvent.VK_BACK_SPACE)
                            || (c == KeyEvent.VK_DELETE) || (c == decimalSeparator))) {
                        e.consume();
                    }
                } else {
                    if (!(Character.isDigit(c)
                            || (c == KeyEvent.VK_BACK_SPACE)
                            || (c == KeyEvent.VK_DELETE))) {
                        e.consume();
                    }
                }
            }
        });

        dm.addColumn("id");
        dm.addColumn("Name");
        dm.addColumn("Money");
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setRowHeight(30);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
        table.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);

        cbodbname.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {

            }

            @Override
            public void focusLost(FocusEvent e) {

            }
        });
        btnOpenDatabase.addActionListener((ActionEvent e) -> {
            setOpenDatabase();
        });
        btnDeleteDatabase.addActionListener((ActionEvent e) -> {
            setDeleteDatabases();
        });
        btnCloseDatabase.addActionListener((ActionEvent e) -> {
            setCloseDatabases();
        });
        btnAdd.addActionListener((ActionEvent e) -> {
            setAdd();
        });
        btnSave.addActionListener((ActionEvent e) -> {
            setSave();
        });
        btnDelete.addActionListener((ActionEvent e) -> {
            setDelete();
        });
        btnClose.addActionListener((ActionEvent e) -> {
            setClose();
        });
        btnOpenDatabase.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyChar() == KeyEvent.VK_ENTER) {
                    if (btnOpenDatabase.isFocusable()) {
                        setOpenDatabase();
                    }
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {

            }

            @Override
            public void keyTyped(KeyEvent e) {

            }
        });
        btnDeleteDatabase.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyChar() == KeyEvent.VK_ENTER) {
                    if (btnDeleteDatabase.isFocusable()) {
                        setDeleteDatabases();
                    }
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {

            }

            @Override
            public void keyTyped(KeyEvent e) {

            }
        });
        btnCloseDatabase.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyChar() == KeyEvent.VK_ENTER) {
                    if (btnCloseDatabase.isFocusable()) {
                        setCloseDatabases();
                    }
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {

            }

            @Override
            public void keyTyped(KeyEvent e) {

            }
        });
        btnAdd.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyChar() == KeyEvent.VK_ENTER) {
                    if (btnAdd.isFocusable()) {
                        setAdd();
                    }
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {

            }

            @Override
            public void keyTyped(KeyEvent e) {

            }
        });
        btnSave.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyChar() == KeyEvent.VK_ENTER) {
                    if (btnSave.isFocusable()) {
                        setSave();
                    }
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {

            }

            @Override
            public void keyTyped(KeyEvent e) {

            }
        });
        btnDelete.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyChar() == KeyEvent.VK_ENTER) {
                    if (btnDelete.isFocusable()) {
                        setDelete();
                    }
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {

            }

            @Override
            public void keyTyped(KeyEvent e) {

            }
        });
        btnClose.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyChar() == KeyEvent.VK_ENTER) {
                    if (btnClose.isFocusable()) {
                        setClose();
                    }
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {

            }

            @Override
            public void keyTyped(KeyEvent e) {

            }
        });
        table.addMouseListener(new MouseListener() {

            @Override
            public void mouseReleased(MouseEvent e) {

            }

            @Override
            public void mousePressed(MouseEvent e) {
                int row;
                int rowcount = dm.getRowCount();
                if (rowcount > 0) {
                    row = table.getSelectedRow();
                    if (row < rowcount - 1) {
                        Object value = table.getValueAt(row, 0);
                        id = Integer.valueOf(value.toString());
                        value = table.getValueAt(row, 1);
                        txtname.setText(value.toString());
                        value = table.getValueAt(row, 2);
                        NumberFormat format = DecimalFormat.getInstance();
                        format.setGroupingUsed(true);
                        format.setMinimumFractionDigits(0);
                        txtmoney.setText(format.format(value));
                        btnAdd.setEnabled(true);
                        btnSave.setEnabled(true);
                        btnDelete.setEnabled(true);
                        btnClose.setEnabled(true);
                        txtname.setEnabled(true);
                        txtmoney.setEnabled(true);
                    } else {
                        id = -1;
                        txtname.setText("");
                        txtmoney.setText("");
                        btnAdd.setEnabled(true);
                        btnSave.setEnabled(false);
                        btnDelete.setEnabled(false);
                        btnClose.setEnabled(true);
                        txtname.setEnabled(false);
                        txtmoney.setEnabled(false);
                    }
                }
            }

            @Override
            public void mouseExited(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseClicked(MouseEvent e) {

            }
        });

        table.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                int rowcount = dm.getRowCount();
                if (rowcount > 0) {
                    int row = table.getSelectedRow();
                    if (e.getKeyCode() == KeyEvent.VK_UP) {
                        if (row > 0) {
                            getDataTableSelectRows(row - 1, rowcount);
                        }
                    }
                    if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                        getDataTableSelectRows(row + 1, rowcount);
                    }
                    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                        if (row == rowcount - 1) {
                            row = 0;
                            id = -1;
                            txtname.setText("");
                            txtmoney.setText("");
                        } else {
                            row++;
                        }
                        System.out.println("row: " + row);
                        getDataTableSelectRows(row, rowcount);
                    }
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {

            }

            @Override
            public void keyTyped(KeyEvent e) {

            }
        });
    }

    private void getDataTableSelectRows(int row, int rowcount) {
        try {
            if (row < rowcount - 1) {
                Object value = table.getValueAt(row, 0);
                id = Integer.valueOf(value.toString());
                value = table.getValueAt(row, 1);
                txtname.setText(value.toString());
                value = table.getValueAt(row, 2);
                NumberFormat format = DecimalFormat.getInstance();
                format.setGroupingUsed(true);
                format.setMinimumFractionDigits(0);
                txtmoney.setText(format.format(value));
                btnAdd.setEnabled(true);
                btnSave.setEnabled(true);
                btnDelete.setEnabled(true);
                btnClose.setEnabled(true);
                txtname.setEnabled(true);
                txtmoney.setEnabled(true);
            } else {
                id = -1;
                txtname.setText("");
                txtmoney.setText("");
                btnAdd.setEnabled(true);
                btnSave.setEnabled(false);
                btnDelete.setEnabled(false);
                btnClose.setEnabled(true);
                txtname.setEnabled(false);
                txtmoney.setEnabled(false);
            }
        } catch (NumberFormatException e) {

        }
    }

    private void setCloseDatabases() throws HeadlessException {
        int kq = JOptionPane.showConfirmDialog(this, "Bạn có chắc chắn đóng cơ sở dữ liệu không?", "Cơ sở dữ liệu", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (kq == JOptionPane.YES_OPTION) {
            CloseDatabase();
             this.setTitle("java.version: " + javaversion);
        }
    }

    private void setDeleteDatabases() throws HeadlessException {
        valuedbname = ((JTextField) cbodbname.getEditor().getEditorComponent()).getText().trim();
        if (valuedbname.length() > 0) {
            int kq = JOptionPane.showConfirmDialog(this, "Bạn có chắc chắn xóa cơ sở dữ liệu " + cbodbname.getSelectedItem() + " không?", "Xóa Database", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (kq == JOptionPane.YES_OPTION) {
                DeleteDatabase();
               this.setTitle("java.version: " + javaversion);
            }
        } else {
            cbodbname.requestFocusInWindow();
        }
    }

    private void setClose() throws HeadlessException {
        try {
            int kq = JOptionPane.showConfirmDialog(this, "Bạn có chắc chắn đóng cơ sở dữ liệu và thoát không?", "Thoát", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (kq == JOptionPane.YES_OPTION) {
                if (conn != null) {
                    conn.close();
                    conn = null;
                }
                System.exit(0);
            }
        } catch (SQLException ex) {

        }
    }

    private void setDelete() {
        try {
            int kq = JOptionPane.showConfirmDialog(this, "Bạn có chắc chắn xóa dữ liệu có id = " + this.id + " không?", "Xóa dữ liệu", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (kq == JOptionPane.YES_OPTION) {
                if (this.id != -1) {
                    deletetbldmLop(this.conn);
                    this.id = -1;
                    txtname.setText("");
                    txtmoney.setText("");
                    selecttbldmLop(this.conn);
                    SUM(table, 2);
                    btnAdd.setEnabled(true);
                    btnSave.setEnabled(false);
                    btnDelete.setEnabled(false);
                    btnClose.setEnabled(true);
                    txtname.setEnabled(false);
                    txtmoney.setEnabled(false);
                    table.requestFocusInWindow();
                }
            }
        } catch (HeadlessException ex) {

        }
    }

    private void setSave() {
        try {
            if (txtname.getText().trim().length() == 0) {
                txtname.requestFocusInWindow();
            } else if (txtmoney.getText().trim().length() == 0) {
                txtmoney.requestFocusInWindow();
            } else {
                if (this.id == -1) {
                    inserttbldmLop(this.conn);
                } else {
                    updatetbldmLop(this.conn);
                }
                this.id = -1;
                txtname.setText("");
                txtmoney.setText("");
                selecttbldmLop(this.conn);
                SUM(table, 2);
                btnAdd.setEnabled(true);
                btnSave.setEnabled(false);
                btnDelete.setEnabled(false);
                btnClose.setEnabled(true);
                txtname.setEnabled(false);
                txtmoney.setEnabled(false);
                int kq = JOptionPane.showConfirmDialog(this, "Đã lưu thành công. Tiếp tục thêm mới?", "Lưu dữ liệu", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (kq == JOptionPane.YES_OPTION) {
                    btnAdd.requestFocusInWindow();
                } else {
                    table.requestFocusInWindow();
                }
            }
        } catch (HeadlessException ex) {

        }
    }

    private void setAdd() {
        this.id = -1;
        txtname.setText("");
        txtmoney.setText("");
        btnAdd.setEnabled(false);
        btnSave.setEnabled(true);
        btnDelete.setEnabled(false);
        btnClose.setEnabled(true);
        txtname.setEnabled(true);
        txtmoney.setEnabled(true);
        txtname.requestFocusInWindow();
    }

    private void setOpenDatabase() {
        valuedbname = ((JTextField) cbodbname.getEditor().getEditorComponent()).getText().trim();
        if (valuedbname.length() > 0) {
            OpenDatabase();
            createtbldmLop(this.conn);
            int kq = selecttbldmLop(this.conn);
            SUM(table, 2);
            System.out.println(kq);
            if (kq == 0) {
                btnAdd.requestFocusInWindow();
            } else {
                table.requestFocusInWindow();
            }
        } else {
            cbodbname.requestFocusInWindow();
        }
    }

    public frmMain() {
        this.javaversion = System.getProperty("java.version");
        setLayout(null);
        this.setTitle("java.version: " + javaversion);
        getContentPane().setBackground(Color.white);
        getRootPane().setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.blue));
        this.setExtendedState(JFrame.MAXIMIZED_BOTH);
        this.setResizable(true);
        GUI();
        cbodbname.removeAllItems();
        loaddbname();
        cbodbname.setSelectedIndex(-1);
        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        this.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent evt) {
                setExtendedState(JFrame.MAXIMIZED_BOTH);
            }
        });

        btnOpenDatabase.setEnabled(true);
        btnCloseDatabase.setEnabled(false);
        btnDeleteDatabase.setEnabled(true);
        btnAdd.setEnabled(false);
        btnSave.setEnabled(false);
        btnDelete.setEnabled(false);
        btnClose.setEnabled(true);
        txtname.setEnabled(false);
        txtmoney.setEnabled(false);
    }

    public static void main(String[] args) {
        try {
            java.awt.EventQueue.invokeLater(() -> {
                new frmMain().setVisible(true);
            });
        } catch (Exception ex) {

        }
    }
}


 

Tác giả: Vàng Văn Quyn

Chú ý: Việc đăng lại bài viết trên ở website hoặc các phương tiện truyền thông khác mà không ghi rõ nguồn https://365.io.vn là vi phạm bản quyền
Chúng tôi đang sử dụng cookie để cung cấp cho bạn những trải nghiệm tốt nhất trên trang web này. Bằng cách tiếp tục truy cập, bạn đồng ý với Chính sách thu thập và sử dụng cookie của chúng tôi.
Bạn đã không sử dụng Site, Bấm vào đây để duy trì trạng thái đăng nhập. Thời gian chờ: 60 giây