Java Custom Table Design

How to Create a Custom Scrollable Table in Java NetBeans with MySQL Database



In this Java Tutorial we will see How To Make a Custom Scrollable Table, plus how to display data from mysql database into this table in Java using NetBeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.
MySQL Database.
- PhpMyAdmin.

What We Will Do In This Project:
- Using a Graphics2D object to draw table headers and rows with alternating row colors.
- Employs a custom JScrollPane with a ModernScrollBarUI to create a modern-looking scrollbar, the scrollbar appearance is customized using the BasicScrollBarUI class.
- Connect Java To MySQL Database, using JDBC, executes a SELECT query on the "product" table, and retrieves the data, which is stored in a list of TableRow objects.






Project Source Code (V1):



/**
 *
 * @author 1BestCsharp
 */
public class CustomTable extends JFrame {
    
    private List<TableRow> tableData;
    private JScrollPane scrollPane;
    private TablePanel tablePanel;

    public CustomTable()
    {
        
        setTitle("Custom Table Example");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 300);
        setLocationRelativeTo(null);

        // Initialize table data
        tableData = new ArrayList<>();
        tableData.add(new TableRow("John", "Doe", "25"));
        tableData.add(new TableRow("Jane", "Smith", "30"));
        tableData.add(new TableRow("Alice", "Johnson", "22"));
        tableData.add(new TableRow("Bob", "Brown", "35"));
        tableData.add(new TableRow("Eve", "Wilson", "28"));
        tableData.add(new TableRow("John", "Doe", "25"));
        tableData.add(new TableRow("Jane", "Smith", "30"));
        tableData.add(new TableRow("Alice", "Johnson", "22"));
        tableData.add(new TableRow("Bob", "Brown", "35"));
        tableData.add(new TableRow("Eve", "Wilson", "28"));
        tableData.add(new TableRow("John", "Doe", "25"));
        tableData.add(new TableRow("Jane", "Smith", "30"));
        tableData.add(new TableRow("Alice", "Johnson", "22"));
        tableData.add(new TableRow("Bob", "Brown", "35"));
        tableData.add(new TableRow("Eve", "Wilson", "28"));
        tableData.add(new TableRow("John", "Doe", "25"));
        tableData.add(new TableRow("Jane", "Smith", "30"));
        tableData.add(new TableRow("Alice", "Johnson", "22"));
        tableData.add(new TableRow("Bob", "Brown", "35"));
        tableData.add(new TableRow("Eve", "Wilson", "28"));
        tableData.add(new TableRow("John", "Doe", "25"));
        tableData.add(new TableRow("Jane", "Smith", "30"));
        tableData.add(new TableRow("Alice", "Johnson", "22"));
        tableData.add(new TableRow("Bob", "Brown", "35"));
        tableData.add(new TableRow("Eve", "Wilson", "28"));
        tableData.add(new TableRow("John", "Doe", "25"));
        tableData.add(new TableRow("Jane", "Smith", "30"));
        tableData.add(new TableRow("Alice", "Johnson", "22"));
        tableData.add(new TableRow("Bob", "Brown", "35"));
        tableData.add(new TableRow("Eve", "Wilson", "28"));

        // Create a table panel to hold the table
        tablePanel = new TablePanel();
        tablePanel.setBackground(Color.white);
        tablePanel.setPreferredSize(new Dimension(380, 200));

        // Create a custom scroll pane
        scrollPane = new CustomScrollPane(tablePanel);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

        add(scrollPane);

    }
    
    
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
        
            new CustomTable().setVisible(true);
            
        });
        
    }
    
    
    
    // Inner class for the table panel
    private class TablePanel extends JPanel
    {
        @Override
        protected void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            drawTable(g);
        }
        
    }
    
    
    // Method to draw the custom table
    private void drawTable(Graphics g){

        
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        int x = 10;
        int y = 10;
        int rowHeight = 30;
        int tableWidth = 360;
        
        
        // Draw table header
        g2d.setColor(new Color(255,121,48));
        g2d.fillRect(x, y, tableWidth, rowHeight);
        g2d.setColor(new Color(255,255,255));
        g2d.setFont(new Font("Arial",  Font.BOLD, 14));
        g2d.drawString("First Name", x+20, y+20);
        g2d.drawString("Last Name", x+140, y+20);
        g2d.drawString("Age", x+270, y+20);
        
        g2d.setColor(Color.black);
        g2d.setFont(new Font("Arial",  Font.ITALIC, 14));
        // Draw table rows with data
        for(int i = 0; i < tableData.size(); i++){
            
            TableRow rowData = tableData.get(i);
            y += rowHeight;
            g2d.setColor(Color.white);
            if(i%2 != 0){
                // Alternate row color
                g2d.setColor(new Color(181,242,238));
                g2d.fillRect(x, y, tableWidth, rowHeight);
                g2d.setColor(Color.black);
            }
            else{
                g2d.setColor(new Color(249,241,238));
                g2d.fillRect(x, y, tableWidth, rowHeight);
                g2d.setColor(Color.black);
            }
            
            g2d.drawString(rowData.getFirstName(), x+20, y+20);
            g2d.drawString(rowData.getLastName(), x+140, y+20);
            g2d.drawString(rowData.getAge(), x+270, y+20);
           
        }
        
        // Set the preferred size of the table panel to match the table content
        tablePanel.setPreferredSize(new Dimension(380, y+rowHeight+10));

    }
    
    
    
    // Inner class representing a row in the table
    private static class TableRow
    {
        private String firstName;
        private String lastName;
        private String age;
        
        
        public TableRow(String fname, String lname, String age)
        {
            this.firstName = fname;
            this.lastName = lname;
            this.age = age;
        }

        public String getFirstName() {
            return firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public String getAge() {
            return age;
        }
        
    }
    
    
    // Inner class for the custom scroll pane with a custom scrollbar UI
    private class CustomScrollPane extends JScrollPane{
        
        public CustomScrollPane(Component view){
            super(view);
            initializeScrollBarUI();
        }

        private void initializeScrollBarUI(){

            JScrollBar verticallScrollBar = getVerticalScrollBar();
            verticallScrollBar.setUI(new ModernScrollBarUI());
            verticallScrollBar.addAdjustmentListener((e) -> {
                repaint();
            });

        }
        
    }
    
    
    
    
    // Inner class for the custom scrollbar UI
    private class ModernScrollBarUI extends BasicScrollBarUI{
        
        private final Dimension thumbSize = new Dimension(10,40);
        
        @Override
        protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds){
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setColor(new Color(100,100,100));
            g2d.fillRoundRect(thumbBounds.x, thumbBounds.y, thumbBounds.width, thumbBounds.height, 0, 0); 
        }
        
        
        @Override
        protected void setThumbBounds(int x, int y, int width, int height){
            super.setThumbBounds(x, y, thumbSize.width, height);
        }
        
        
        @Override
        protected JButton createDecreaseButton(int orientation){
            return createEmptyButton();
        }
        
        
        @Override
        protected JButton createIncreaseButton(int orientation){
            return createEmptyButton();
        }
        
        private JButton createEmptyButton(){
            JButton button = new JButton();
            button.setPreferredSize(new Dimension(0,0));
            return button;
        }
        
    }
    
}





  

Project Source Code (V2 - With MySQL Database):


/**
 *
 * @author 1BestCsharp
 */
public class CustomTable_WithMySQL extends JFrame {
    
    private List<TableRow> tableData;
    private JScrollPane scrollPane;
    private TablePanel tablePanel;

    public CustomTable_WithMySQL()
    {
        
        setTitle("Custom Table Example");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 300);
        setLocationRelativeTo(null);

        // Initialize table data
        tableData = fetchTableDataFromDatabase();

        // Create a table panel to hold the table
        tablePanel = new TablePanel();
        tablePanel.setBackground(Color.white);
        tablePanel.setPreferredSize(new Dimension(380, 200));

        // Create a custom scroll pane
        scrollPane = new CustomScrollPane(tablePanel);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

        add(scrollPane);

    }
    
    
    // create a function to fetch data from database
    private List<TableRow> fetchTableDataFromDatabase()
    {
        List<TableRow> data = new ArrayList<>();
        
        try
        {
            String jdbc_url = "jdbc:mysql://localhost:3306/data_db";
            String username = "root";
            String password = "";
            
            Connection connection = DriverManager.getConnection(jdbc_url,username,password);
            Statement statement = connection.createStatement();
            String sqlQuery = "SELECT * FROM `product`";
            
            ResultSet result = statement.executeQuery(sqlQuery);
            
            while(result.next())
            {
                String id = result.getString("id");
                String name = result.getString("name");
                String price = result.getString("price");
                data.add(new TableRow(id, name, price));
            }
            
            result.close();
            statement.close();
            connection.close();
            
        }
        catch(SQLException ex){ System.out.println(ex.getMessage()); }

        return data;
    }
    
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
        
            new CustomTable_WithMySQL().setVisible(true);
            
        });
        
    }
    
    
    
    // Inner class for the table panel
    private class TablePanel extends JPanel
    {
        @Override
        protected void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            drawTable(g);
        }
        
    }
    
    
    // Method to draw the custom table
    private void drawTable(Graphics g){

        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            
        int x = 10;
        int y = 10;
        int rowHeight = 30;
        int tableWidth = 360;
        
        // Draw table header
        g2d.setColor(Color.orange);
        g2d.fillRect(x, y, tableWidth, rowHeight);
        g2d.setColor(new Color(255,255,255));
        g2d.setFont(new Font("Arial",  Font.BOLD, 16));
        g2d.drawString("ID", x+20, y+20);
        g2d.drawString("Name", x+140, y+20);
        g2d.drawString("Price", x+270, y+20);
        
        g2d.setColor(Color.black);
        g2d.setFont(new Font("Arial",  Font.PLAIN, 14));
        // Draw table rows with data
        for(int i = 0; i < tableData.size(); i++){
            
            TableRow rowData = tableData.get(i);
            y += rowHeight;
            g2d.setColor(Color.red);
            if(i%2 == 0){
                // Alternate row color
                g2d.setColor(Color.lightGray);
                g2d.fillRect(x, y, tableWidth, rowHeight);
                g2d.setColor(Color.white);
            }
            
            
            g2d.drawString(rowData.getFirstName(), x+20, y+20);
            g2d.drawString(rowData.getLastName(), x+140, y+20);
            g2d.drawString(rowData.getAge(), x+270, y+20);
           
        }
        
        // Set the preferred size of the table panel to match the table content
        tablePanel.setPreferredSize(new Dimension(380, y+rowHeight+10));

    }
    
    
    
    // Inner class representing a row in the table
    private static class TableRow
    {
        private String firstName;
        private String lastName;
        private String age;
        
        
        public TableRow(String fname, String lname, String age)
        {
            this.firstName = fname;
            this.lastName = lname;
            this.age = age;
        }

        public String getFirstName() {
            return firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public String getAge() {
            return age;
        }
        
    }
    
    
    // Inner class for the custom scroll pane with a custom scrollbar UI
    private class CustomScrollPane extends JScrollPane{
        
        public CustomScrollPane(Component view){
            super(view);
            initializeScrollBarUI();
        }

        private void initializeScrollBarUI(){

            JScrollBar verticallScrollBar = getVerticalScrollBar();
            verticallScrollBar.setUI(new ModernScrollBarUI());
            verticallScrollBar.addAdjustmentListener((e) -> {
                repaint();
            });

        }
        
    }
    
    
    
    
    // Inner class for the custom scrollbar UI
    private class ModernScrollBarUI extends BasicScrollBarUI{
        
        private final Dimension thumbSize = new Dimension(10,40);
        
        @Override
        protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds){
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setColor(new Color(100,100,100));
            g2d.fillRoundRect(thumbBounds.x, thumbBounds.y, thumbBounds.width, thumbBounds.height, 0, 0); 
        }
        
        
        @Override
        protected void setThumbBounds(int x, int y, int width, int height){
            super.setThumbBounds(x, y, thumbSize.width, height);
        }
        
        
        @Override
        protected JButton createDecreaseButton(int orientation){
            return createEmptyButton();
        }
        
        
        @Override
        protected JButton createIncreaseButton(int orientation){
            return createEmptyButton();
        }
        
        private JButton createEmptyButton(){
            JButton button = new JButton();
            button.setPreferredSize(new Dimension(0,0));
            return button;
        }
        
    }
    
}







if you want the source code click on the download button below


 





Java To Do List Project

How to Create To Do List Project In Java Netbeans

How to Create To Do List Project In Java Netbeans


In this Java Tutorial we will see How To Create a To Do List Project in Java NetBeans.
This application provides a beautiful interface for managing tasks, allowing users to add, view, and delete tasks.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code:


public class TasksManagementApp {

    private JFrame frame;
    private JPanel titleBar;
    private JLabel titleLabel;
    private JLabel closeLabel;
    private JLabel minimizeLabel;
    private JPanel dashboardPanel;
    private JButton addTaskButton;
    private ArrayList<String> tasks = new ArrayList<>();
    
    // Variables for dragging the form
    private boolean isDragging = false;
    private Point mouseOffset;
    
    
    // Constructor
    public TasksManagementApp(){
        // Create the main JFrame
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800,500);
        frame.setLocationRelativeTo(null);
        frame.setUndecorated(true);
        // Set border for the frame
        frame.getRootPane().setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(7, 7, 7, 7, new Color(211,84,0)),
                new EmptyBorder(0, 0, 0, 0)));
        
        // Create the title bar
        titleBar = new JPanel();
        titleBar.setLayout(null);
        titleBar.setBackground(new Color(12,22,30));
        titleBar.setPreferredSize(new Dimension(frame.getWidth(), 30));
        // Mouse listener for window dragging
        titleBar.addMouseListener(new MouseAdapter() {
            
            @Override
            public void mousePressed(MouseEvent e){
                isDragging = true;
                mouseOffset = e.getPoint();
            }
            
            @Override
            public void mouseReleased(MouseEvent e){
                isDragging = false;
            }
            
        });
        
        // Mouse motion listener for window dragging
        titleBar.addMouseMotionListener(new MouseAdapter() {
            
            @Override
            public void mouseDragged(MouseEvent e){
                
                if(isDragging){
                    Point newLocation = e.getLocationOnScreen();
                    newLocation.translate(-mouseOffset.x, -mouseOffset.y);
                    frame.setLocation(newLocation);  
                } 
            }   
        });
        
        frame.add(titleBar, BorderLayout.NORTH);
        
        // Create and configure the title label
        titleLabel = new JLabel("Tasks Manager");
        titleLabel.setForeground(Color.WHITE);
        titleLabel.setFont(new Font("Arial", Font.BOLD, 16));
        titleLabel.setBounds(10, 0, 250, 30);
        titleBar.add(titleLabel);
        
        // Create and configure the close label (exit button)
        closeLabel = new JLabel("x");
        closeLabel.setForeground(Color.WHITE);
        closeLabel.setFont(new Font("Arial", Font.BOLD, 17));
        closeLabel.setHorizontalAlignment(SwingConstants.CENTER);
        closeLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
        closeLabel.setBounds(frame.getWidth() - 50, 0, 30, 30);
        // Add mouse listeners to the close label
        closeLabel.addMouseListener(new MouseAdapter() {
            
            @Override
            public void mouseClicked(MouseEvent e){ System.exit(0); }
            
            @Override
            public void mouseEntered(MouseEvent e){
                closeLabel.setForeground(Color.YELLOW);
            }
            
            @Override
            public void mouseExited(MouseEvent e){ 
                closeLabel.setForeground(Color.WHITE);
            }
            
            
        });
        
        titleBar.add(closeLabel);
        
        // Create and configure the minimize label
        minimizeLabel = new JLabel("-");
        minimizeLabel.setForeground(Color.WHITE);
        minimizeLabel.setFont(new Font("Arial", Font.BOLD, 17));
        minimizeLabel.setHorizontalAlignment(SwingConstants.CENTER);
        minimizeLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
        minimizeLabel.setBounds(frame.getWidth() - 75, 0, 30, 30);
        // Add mouse listeners to the minimize label
        minimizeLabel.addMouseListener(new MouseAdapter() {
            
            @Override
            public void mouseClicked(MouseEvent e){ 
                frame.setState(JFrame.ICONIFIED);
            }
            
            @Override
            public void mouseEntered(MouseEvent e){
                minimizeLabel.setForeground(Color.YELLOW);
            }
            
            @Override
            public void mouseExited(MouseEvent e){ 
                minimizeLabel.setForeground(Color.WHITE);
            }
            
            
        });
        
        titleBar.add(minimizeLabel);
        
        // Create the dashboard panel
        dashboardPanel = new JPanel();
        dashboardPanel.setLayout(new FlowLayout(FlowLayout.CENTER,20,20));
        dashboardPanel.setBackground(new Color(206,214,224));
        
        frame.add(dashboardPanel,BorderLayout.CENTER);
        
        
        // Create and configure the "Add Task" button
        addTaskButton = new JButton("Add Task");
        addTaskButton.setBackground(new Color(16,172,132));
        addTaskButton.setForeground(Color.WHITE);
        addTaskButton.setFont(new Font("Arial", Font.BOLD, 16));
        addTaskButton.setBorderPainted(false);
        addTaskButton.setFocusPainted(false);
        addTaskButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        // Add action listener to the "Add Task" button
        addTaskButton.addActionListener((e) -> {
           
            // only allow 12 task (Limits the number of tasks to 12)
            if(tasks.size() < 12){
                String task = JOptionPane.showInputDialog(frame, "Enter a new task: ", "Add Task", JOptionPane.PLAIN_MESSAGE);
                if(task != null && !task.isEmpty() && !task.trim().equals("")){
                    tasks.add(task);
                    updateTaskPanel();
                }
                //you have nothing to do with your time
                else{
                    JOptionPane.showMessageDialog(frame, "So, you have nothing to do with your time?","Empty Task", JOptionPane.WARNING_MESSAGE);
                }
                
            }
            else{
                JOptionPane.showMessageDialog(frame, "You cannot add more than 12 task, Delete some tasks to add new ones","Tasks Timit Exceeded", JOptionPane.WARNING_MESSAGE);
            }
            
            
        });
        
        frame.add(addTaskButton, BorderLayout.SOUTH);
        
        
        frame.setVisible(true);
    }
    
    
    // Update the task panel with the current list of tasks
    private void updateTaskPanel(){
        
        dashboardPanel.removeAll();
        for(String task : tasks){
            addTaskPanel(task);
        }
        
        dashboardPanel.revalidate();
        dashboardPanel.repaint();
        
    }
    
    
    // Add a task panel with delete button to the dashboard panel
    private void addTaskPanel(String task){
        
        JPanel taskPanel = new JPanel();
        taskPanel.setLayout(new BorderLayout());
        taskPanel.setPreferredSize(new Dimension(240, 80));
        taskPanel.setBackground(Color.WHITE);
        taskPanel.setBorder(new LineBorder(new Color(254,202,87),2));
        
        JLabel taskLabel = new JLabel(task);
        taskLabel.setHorizontalAlignment(SwingConstants.CENTER);
        taskPanel.add(taskLabel,BorderLayout.CENTER);
        
        // Add mouse listener to show full task text on click
        taskPanel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e){
                showTaskDetails(task);
            }
        });
        
        // button remove task
        JButton deleteButton = new JButton("Delete");
        deleteButton.setBackground(new Color(231,76,60));
        deleteButton.setForeground(Color.WHITE);
        deleteButton.setBorderPainted(false);
        deleteButton.setFocusPainted(false);
        deleteButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        // remove task action
        deleteButton.addActionListener((e) -> {
            tasks.remove(task);
            updateTaskPanel();
        });
        
        taskPanel.add(deleteButton, BorderLayout.SOUTH);
        dashboardPanel.add(taskPanel);
        
    }
    
    
    // Show task details in a custom dialog
    private void showTaskDetails(String task){
        CustomDialog customDialog = new CustomDialog(frame, "Task Details", task);
        customDialog.setVisible(true);
    }
    
    
  
    // Create a custom dialog class for displaying task details.
// Contains a JTextArea for displaying the content and a "Close" button to close the dialog.
    class CustomDialog extends JDialog{
        
        public CustomDialog(JFrame parent, String title, String content){
            super(parent, title, true);
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            setSize(300, 200);
            setLocationRelativeTo(null);
            
            JPanel panel = new JPanel(new BorderLayout());
            JTextArea textArea = new JTextArea(content);
            textArea.setEditable(false);
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
            textArea.setFont(new Font("Arial", Font.PLAIN, 17));
            JScrollPane scrollPane = new JScrollPane(textArea);
            panel.add(scrollPane, BorderLayout.CENTER);
            
            JButton closeButton = new JButton("Close");
            closeButton.setPreferredSize(new Dimension(120, 40));
            closeButton.setFont(new Font("Arial", Font.PLAIN, 14));
            closeButton.setBackground(new Color(30,144,255));
            closeButton.setForeground(Color.WHITE);
            closeButton.setFocusPainted(false);
            closeButton.setBorderPainted(false);
            
            closeButton.addActionListener((e) -> {
               dispose();
            });
            
            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
            buttonPanel.add(closeButton);
            panel.add(buttonPanel, BorderLayout.SOUTH);
            getContentPane().add(panel);
            
        }
        
    }
    
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        new TasksManagementApp();
        
    }

}


The Final Result:



Java To Do List Project

Java To Do List Project - Add Task

Java To Do List Project - Task Added

Java To Do List Project - View Task

Java To Do List Project - Tasks Limit

Java To Do List Project - Tasks List

Java To Do List Project - Remove Task




if you want the source code click on the download button below