How to Create Login and Register and Dashboard Form in Java NetBeans with MySQL Database
In this Java Long Tutorial we will go step by step on How To Make a Design a Login Form And a Register Form And a Dashboard Form, plus how to connect those two form with mysql database so the user can signup and signin.
we will design these forms without using any library.
What We Are Gonna Use In This Project:
- Java Programming Language.- NetBeans Editor.
- MySQL Database.
- PhpMyAdmin.
What We Will Do In This Project:
- Design Three Forms For The Login, Signup snd Dashboard Using JPanels, Graphics and Borders.
- Create Two Icons Using JLabels To Minimize and Close The Form.
- Make the Forms Draggable Using JPanels.
- Connect Java To MySQL Database.
- Connect Java To MySQL Database.
- Add The Registred User Data From The Signup Form to the mysql database.
- Check If The Username Already Exist Before Adding a New User.
- Check If The User Exist In The Login Form.
- Browse and Select Image From Your Computer and Set The File Path In a JLabel + Save The Image as a Blob in The Database.
- Check If The User Leave Some Fields Empty.
- Check If The User Enter a Wrong Password In The Confirmation Field.
- Browse and Select Image From Your Computer and Set The File Path In a JLabel + Save The Image as a Blob in The Database.
- Check If The User Leave Some Fields Empty.
- Check If The User Enter a Wrong Password In The Confirmation Field.
- Draw Some Analytics data In the Dashboard Form Using Jpanels
- Create a Bar Chart Using JPanel and Graphics.
More Java Projects:
Project Source Code:
Let's First Start With The Connection.
We Will Create a Class and Let's Call it "DatabaseConnection" To Connect Or Java Program With MySQL Database.
/****************** DatabaseConnection Class Start ******************/
// download the mysql connector - https://dev.mysql.com/downloads/connector/j/
// add the jar file to the libraries
// open xampp
// and start apache and mysql
// create the database using phpmyadmin
public class DatabaseConnection {
private static final String DB_NAME = "java_login_register_db";
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/"+DB_NAME;
private static final String JDBC_USER = "root";
private static final String JDBC_PASSWORD = "";
private Connection connection;
public DatabaseConnection(){
try
{
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// create a connection to the database
connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
if(connection != null)
{
System.out.println("Connected");
}
}catch(ClassNotFoundException ex){
System.out.println("JDBC Driver Not Found");
}catch(SQLException ex){
System.err.println("Failed to Connect - " + ex.getMessage());
}
}
// method to get the connection
public Connection getConnection()
{
return connection;
}
}
/****************** DatabaseConnection Class End ******************/
Now Let's Go To The Register Form and See What We Will Do.
/****************** Register Form Start ******************/
public class RegisterForm {
private JFrame frame;
private JPanel titleBar;
private JLabel titleLabel;
private JLabel closeLabel;
private JLabel minimizeLabel;
private JPanel contentPanel;
private JTextField fullnameField;
private JTextField usernameField;
private JTextField phoneField;
private JPasswordField passwordField;
private JPasswordField confirmPasswordField;
private JRadioButton maleRadioButton;
private JRadioButton femaleRadioButton;
private ButtonGroup genderGroup;
private JLabel profilePictureImage;
private JButton browseButton;
private JButton buttonRegister;
private JButton buttonLogin;
private String selectedImage;
private BufferedImage profileImage;
// dragging the form
private boolean isDragging = false;
private Point mouseOffset;
// the database variable
private DatabaseConnection dbConnection;
public RegisterForm() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(450, 500);
frame.setLocationRelativeTo(null);
frame.setUndecorated(true);
titleBar = new JPanel();
titleBar.setLayout(null);
titleBar.setBackground(new Color(255, 204, 0));
titleBar.setPreferredSize(new Dimension(frame.getWidth(), 30));
frame.add(titleBar, BorderLayout.NORTH);
titleLabel = new JLabel("Register Form");
titleLabel.setForeground(Color.BLACK);
titleLabel.setFont(new Font("Arial", Font.BOLD, 16));
titleLabel.setBounds(10, 0, 200, 30);
titleBar.add(titleLabel);
closeLabel = new JLabel("X");
closeLabel.setForeground(Color.BLACK);
closeLabel.setFont(new Font("Arial", Font.BOLD, 16));
closeLabel.setHorizontalAlignment(SwingConstants.CENTER);
closeLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
closeLabel.setBounds(frame.getWidth() - 30, 0, 30, 30);
closeLabel.addMouseListener(new MouseAdapter() {
// close the register form
@Override
public void mouseClicked(MouseEvent e) {
System.exit(0);
}
// mouse hover effect
@Override
public void mouseEntered(MouseEvent e) {
closeLabel.setForeground(new Color(60, 179, 113));
}
@Override
public void mouseExited(MouseEvent e) {
closeLabel.setForeground(Color.BLACK);
}
});
titleBar.add(closeLabel);
minimizeLabel = new JLabel("-");
minimizeLabel.setForeground(Color.BLACK);
minimizeLabel.setFont(new Font("Arial", Font.BOLD, 16));
minimizeLabel.setHorizontalAlignment(SwingConstants.CENTER);
minimizeLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
minimizeLabel.setBounds(frame.getWidth() - 60, 0, 30, 30);
minimizeLabel.addMouseListener(new MouseAdapter() {
// iconify (minimize) the login form
@Override
public void mouseClicked(MouseEvent e) {
frame.setState(JFrame.ICONIFIED);
}
// mouse hover effect
@Override
public void mouseEntered(MouseEvent e) {
minimizeLabel.setForeground(new Color(60, 179, 113));
}
@Override
public void mouseExited(MouseEvent e) {
minimizeLabel.setForeground(Color.BLACK);
}
});
titleBar.add(minimizeLabel);
contentPanel = new JPanel();
contentPanel.setLayout(null);
contentPanel.setBackground(new Color(236, 240, 241));
contentPanel.setBorder(new LineBorder(new Color(255, 204, 0), 2));
contentPanel.setBounds(10, 30, frame.getWidth() - 20, frame.getHeight() - 40);
frame.add(contentPanel);
// labels and textfields
JLabel fullnameLabel = new JLabel("Full Name:");
fullnameLabel.setBounds(30, 20, 120, 25);
contentPanel.add(fullnameLabel);
fullnameField = new JTextField();
fullnameField.setBounds(150, 20, 250, 25);
contentPanel.add(fullnameField);
JLabel usernameLabel = new JLabel("Username:");
usernameLabel.setBounds(30, 50, 80, 25);
contentPanel.add(usernameLabel);
usernameField = new JTextField();
usernameField.setBounds(150, 50, 250, 25);
contentPanel.add(usernameField);
JLabel passwordLabel = new JLabel("Password:");
passwordLabel.setBounds(30, 80, 80, 25);
contentPanel.add(passwordLabel);
passwordField = new JPasswordField();
passwordField.setBounds(150, 80, 250, 25);
contentPanel.add(passwordField);
JLabel confirmPasswordLabel = new JLabel("Confirm Password:");
confirmPasswordLabel.setBounds(30, 110, 120, 25);
contentPanel.add(confirmPasswordLabel);
confirmPasswordField = new JPasswordField();
confirmPasswordField.setBounds(150, 110, 250, 25);
contentPanel.add(confirmPasswordField);
JLabel phoneLabel = new JLabel("Phone:");
phoneLabel.setBounds(30, 140, 80, 25);
contentPanel.add(phoneLabel);
phoneField = new JTextField();
phoneField.setBounds(150, 140, 250, 25);
contentPanel.add(phoneField);
JLabel genderLabel = new JLabel("Gender:");
genderLabel.setBounds(30, 170, 80, 25);
contentPanel.add(genderLabel);
maleRadioButton = new JRadioButton("Male");
maleRadioButton.setBounds(150, 170, 100, 25);
maleRadioButton.setFocusPainted(false);
maleRadioButton.setBorderPainted(false);
maleRadioButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
maleRadioButton.setSelected(true);
contentPanel.add(maleRadioButton);
femaleRadioButton = new JRadioButton("Female");
femaleRadioButton.setBounds(260, 170, 100, 25);
femaleRadioButton.setFocusPainted(false);
femaleRadioButton.setBorderPainted(false);
femaleRadioButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
contentPanel.add(femaleRadioButton);
genderGroup = new ButtonGroup();
genderGroup.add(maleRadioButton);
genderGroup.add(femaleRadioButton);
JLabel profilePictureLabel = new JLabel("Profile Picture:");
profilePictureLabel.setBounds(30, 200, 120, 25);
contentPanel.add(profilePictureLabel);
// browse image button
browseButton = new JButton("Browse");
browseButton.setBounds(150, 200, 100, 25);
browseButton.setFont(new Font("Arial", Font.PLAIN, 12));
browseButton.setBackground(new Color(255, 102, 0));
browseButton.setForeground(Color.WHITE);
browseButton.setFocusPainted(false);
browseButton.setBorderPainted(false);
browseButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
// browse button hover effect
browseButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
browseButton.setBackground(new Color(255, 51, 0));
}
@Override
public void mouseExited(MouseEvent e) {
browseButton.setBackground(new Color(255, 102, 0));
}
});
// browse and display image
browseButton.addActionListener((e) -> {
// Create a file chooser
JFileChooser fileChooser = new JFileChooser();
// Create a file filter for image files
FileNameExtensionFilter fileFilter = new FileNameExtensionFilter("Image Files", "jpg","jpeg","png","gif");
fileChooser.setFileFilter(fileFilter);
int returnValue = fileChooser.showOpenDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION)
{
File selectedFile = fileChooser.getSelectedFile();
selectedImage = selectedFile.getAbsolutePath();
try
{
// Read the selected image file
profileImage = ImageIO.read(selectedFile);
// Scale the image to fit the profilePictureImage component (JLabel)
Image scaledImage = profileImage.getScaledInstance(profilePictureImage.getWidth(), profilePictureImage.getHeight(), Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(scaledImage);
// Set the scaled image as the profile picture
profilePictureImage.setIcon(imageIcon);
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
});
contentPanel.add(browseButton);
profilePictureImage = new JLabel();
profilePictureImage.setBounds(270, 200, 130, 130);
profilePictureImage.setBorder(new LineBorder(Color.GRAY, 1));
contentPanel.add(profilePictureImage);
// button register
buttonRegister = new JButton("Register");
buttonRegister.setBounds(225, 380, 170, 35);
buttonRegister.setFont(new Font("Arial", Font.BOLD, 14));
buttonRegister.setBackground(new Color(60, 179, 113));
buttonRegister.setForeground(Color.WHITE);
buttonRegister.setFocusPainted(false);
buttonRegister.setBorderPainted(false);
buttonRegister.setCursor(new Cursor(Cursor.HAND_CURSOR));
buttonRegister.addActionListener((e) -> {
registerUser();
});
buttonRegister.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
buttonRegister.setBackground(new Color(46, 139, 87));
}
@Override
public void mouseExited(MouseEvent e) {
buttonRegister.setBackground(new Color(60, 179, 113));
}
});
contentPanel.add(buttonRegister);
// login button
buttonLogin = new JButton("Back to Login");
buttonLogin.setBounds(40, 380, 170, 35);
buttonLogin.setFont(new Font("Arial", Font.BOLD, 14));
buttonLogin.setBackground(new Color(70, 130, 180));
buttonLogin.setForeground(Color.WHITE);
buttonLogin.setFocusPainted(false);
buttonLogin.setBorderPainted(false);
buttonLogin.setCursor(new Cursor(Cursor.HAND_CURSOR));
// open login form
buttonLogin.addActionListener((e) -> {
frame.dispose();
new LoginForm();
});
buttonLogin.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
buttonLogin.setBackground(new Color(0, 102, 204));
}
@Override
public void mouseExited(MouseEvent e) {
buttonLogin.setBackground(new Color(70, 130, 180));
}
});
contentPanel.add(buttonLogin);
// 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) {
// When the mouse is dragged, this event is triggered
// Get the current location of the mouse on the screen
Point newLocation = e.getLocationOnScreen();
// Calculate the new window location by adjusting for the initial mouse offset
newLocation.translate(-mouseOffset.x, -mouseOffset.y);
// Set the new location of the main window to achieve dragging effect
frame.setLocation(newLocation);
}
}
});
dbConnection = new DatabaseConnection();
frame.setVisible(true);
}
// show error message method
private void showErrorMessage(String message)
{
JOptionPane.showMessageDialog(frame, message, "Registration Error", JOptionPane.ERROR_MESSAGE);
}
// show success message method
private void showSuccessMessage(String message)
{
JOptionPane.showMessageDialog(frame, message, "Success", JOptionPane.INFORMATION_MESSAGE);
}
// close the registration form method
private void closeRegisterForm()
{
frame.dispose();
}
// open login form method
private void openLoginForm()
{
new LoginForm();
}
// create a function to check if a username already exists
private boolean doesUsernameExists(String username)
{
try{
Connection connection = dbConnection.getConnection();
String query = "SELECT * FROM `users` WHERE `username` = ?";
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, username);
ResultSet rs = ps.executeQuery();
if(rs.next()) { return true; }
}
catch(SQLException ex){ ex.printStackTrace(); }
return false;
}
// create a method to register a new user
private void registerUser()
{
String fullname = fullnameField.getText();
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
String confirmPassword = new String(confirmPasswordField.getPassword());
String phone = phoneField.getText();
String gender = maleRadioButton.isSelected() ? "Male" : "Female";
// check for empty fields
if(fullname.trim().isEmpty() || username.trim().isEmpty() ||
password.trim().isEmpty() || confirmPassword.trim().isEmpty() ||
phone.trim().isEmpty())
{
showErrorMessage("All Field must be filled");
}
else if(!password.equals(confirmPassword))
{
showErrorMessage("Passwords do not match");
}
else if(doesUsernameExists(username))
{
showErrorMessage("This username already exists");
}
else
{
try
{
Connection connection = dbConnection.getConnection();
String query = "INSERT INTO `users`(`fullname`, `username`, `password`, `phone`, `gender`, `picture`) VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement prepareStatement = connection.prepareStatement(query);
prepareStatement.setString(1, fullname);
prepareStatement.setString(2, username);
prepareStatement.setString(3, password);
prepareStatement.setString(4, phone);
prepareStatement.setString(5, gender);
// get the profile picture
if(selectedImage != null)
{
File profilePictureFile = new File(selectedImage);
FileInputStream fileStream = new FileInputStream(profilePictureFile);
prepareStatement.setBinaryStream(6, fileStream, profilePictureFile.length());
int rowsAffected = prepareStatement.executeUpdate();
if(rowsAffected > 0)
{
showSuccessMessage("Registration Successful");
}
else{ showErrorMessage("Registration Failed"); }
}
else{ showErrorMessage("Please Select a Profile Picture"); }
}
catch(SQLException ex)
{
showErrorMessage("Error: " + ex.getMessage());
}
catch(FileNotFoundException ex)
{
showErrorMessage("Error Loading Profile Picture: " + ex.getMessage());
}
}
}
public static void main(String[] args) {
new RegisterForm();
}
}
/****************** Register Form End ******************/
Now We Will Make The Login Form To Allow The User Enter To The Application
/****************** Login Form Start ******************/
public class LoginForm {
private JFrame frame;
private JPanel titleBar;
private JLabel titleLabel;
private JLabel closeLabel;
private JLabel minimizeLabel;
private JPanel contentPanel;
private JTextField usernameField;
private JPasswordField passwordField;
private JButton buttonLogin;
private JButton buttonRegister;
// dragging the form
private boolean isDragging = false;
private Point mouseOffset;
// database connection
private DatabaseConnection dbConnection;
public LoginForm()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,250);
frame.setLocationRelativeTo(null);
frame.setUndecorated(true);
titleBar = new JPanel();
titleBar.setLayout(null);
titleBar.setBackground(new Color(255,204,0));
titleBar.setPreferredSize(new Dimension(frame.getWidth(), 30));
frame.add(titleBar,BorderLayout.NORTH);
titleLabel = new JLabel("Login Form");
titleLabel.setForeground(Color.BLACK);
titleLabel.setFont(new Font("Arial", Font.BOLD, 16));
titleLabel.setBounds(10,0,200,30);
titleBar.add(titleLabel);
closeLabel = new JLabel("X");
closeLabel.setForeground(Color.BLACK);
closeLabel.setFont(new Font("Arial", Font.BOLD, 16));
closeLabel.setHorizontalAlignment(SwingConstants.CENTER);
closeLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
closeLabel.setBounds(frame.getWidth()-30,0,30,30);
closeLabel.addMouseListener(new MouseAdapter(){
// close the login form
@Override
public void mouseClicked(MouseEvent e){
System.exit(0);
}
// mouse hover effect
@Override
public void mouseEntered(MouseEvent e)
{
closeLabel.setForeground(new Color(60,179,113));
}
@Override
public void mouseExited(MouseEvent e)
{
closeLabel.setForeground(Color.BLACK);
}
});
titleBar.add(closeLabel);
minimizeLabel = new JLabel("-");
minimizeLabel.setForeground(Color.BLACK);
minimizeLabel.setFont(new Font("Arial", Font.BOLD, 16));
minimizeLabel.setHorizontalAlignment(SwingConstants.CENTER);
minimizeLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
minimizeLabel.setBounds(frame.getWidth()-60,0,30,30);
minimizeLabel.addMouseListener(new MouseAdapter(){
// iconify (minimize) the login form
@Override
public void mouseClicked(MouseEvent e){
frame.setState(JFrame.ICONIFIED);
}
// mouse hover effect
@Override
public void mouseEntered(MouseEvent e)
{
minimizeLabel.setForeground(new Color(60,179,113));
}
@Override
public void mouseExited(MouseEvent e)
{
minimizeLabel.setForeground(Color.BLACK);
}
});
titleBar.add(minimizeLabel);
contentPanel = new JPanel();
contentPanel.setLayout(null);
contentPanel.setBackground(new Color(236,240,241));
contentPanel.setBorder(new LineBorder(new Color(255,204,0),5));
contentPanel.setBounds(10,30,frame.getWidth()-20, frame.getHeight()-40);
frame.add(contentPanel);
// Username label and input field
JLabel usernameLabel = new JLabel("Username:");
usernameLabel.setBounds(30,40,80,25);
contentPanel.add(usernameLabel);
usernameField = new JTextField();
usernameField.setBounds(120,40,200,25);
contentPanel.add(usernameField);
JLabel passwordLabel = new JLabel("Password:");
passwordLabel.setBounds(30,80,80,25);
contentPanel.add(passwordLabel);
passwordField = new JPasswordField();
passwordField.setBounds(120,80,200,25);
contentPanel.add(passwordField);
// login button
buttonLogin = new JButton("Login");
buttonLogin.setBounds(100,120,100,35);
buttonLogin.setFont(new Font("Arial", Font.BOLD, 14));
buttonLogin.setBackground(new Color(255,102,0));
buttonLogin.setForeground(Color.WHITE);
buttonLogin.setFocusPainted(false);
buttonLogin.setBorderPainted(false);
buttonLogin.setCursor(new Cursor(Cursor.HAND_CURSOR));
// open dashboard form
buttonLogin.addActionListener((e) -> {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
boolean loginState = checkLogin(username, password);
if(loginState){
frame.dispose();
new DashboardForm();
}
else
{
JOptionPane.showMessageDialog(frame, "Invalid Username OR Password","Invalid Data",JOptionPane.ERROR_MESSAGE);
}
});
buttonLogin.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e)
{
buttonLogin.setBackground(new Color(255,51,0));
}
@Override
public void mouseExited(MouseEvent e)
{
buttonLogin.setBackground(new Color(255,102,0));
}
});
contentPanel.add(buttonLogin);
// register button
buttonRegister = new JButton("Register");
buttonRegister.setBounds(220,120,100,35);
buttonRegister.setFont(new Font("Arial", Font.BOLD, 14));
buttonRegister.setBackground(new Color(0,102,255));
buttonRegister.setForeground(Color.WHITE);
buttonRegister.setFocusPainted(false);
buttonRegister.setBorderPainted(false);
buttonRegister.setCursor(new Cursor(Cursor.HAND_CURSOR));
// open register form
buttonRegister.addActionListener((e) -> {
frame.dispose();
new RegisterForm();
});
buttonRegister.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e)
{
buttonRegister.setBackground(new Color(0,51,204));
}
@Override
public void mouseExited(MouseEvent e)
{
buttonRegister.setBackground(new Color(0,102,255));
}
});
contentPanel.add(buttonRegister);
// 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)
{
// When the mouse is dragged, this event is triggered
// Get the current location of the mouse on the screen
Point newLocation = e.getLocationOnScreen();
// Calculate the new window location by adjusting for the initial mouse offset
newLocation.translate(-mouseOffset.x, -mouseOffset.y);
// Set the new location of the main window to achieve dragging effect
frame.setLocation(newLocation);
}
}
});
dbConnection = new DatabaseConnection();
// make the form visible
frame.setVisible(true);
}
// create a function to check the username and password
private boolean checkLogin(String username, String password)
{
Connection connection = dbConnection.getConnection();
if(connection != null)
{
try{
String query = "SELECT * FROM `users` WHERE `username` = ?";
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, username);
ResultSet rs = ps.executeQuery();
if(rs.next())
{
String storedPassword = rs.getString("password");
return password.equals(storedPassword);
}
}
catch(SQLException ex){ ex.printStackTrace(); }
}
return false;
}
public static void main(String[] args)
{
new LoginForm();
}
}
/****************** Login Form End ******************/
Now We Will Design The Dashboard Form Using JPanels And Graphics
/****************** Dashboard Form Start ******************/
public class DashboardForm {
private JFrame frame;
private JPanel titleBar;
private JLabel titleLabel;
private JLabel closeLabel;
private JLabel minimizeLabel;
private JPanel dashboardPanel;
// dragging the form
private boolean isDragging = false;
private Point mouseOffset;
public DashboardForm()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 500);
frame.setLocationRelativeTo(null);
frame.setUndecorated(true);
// Set the custom rounded border to the form
frame.getRootPane().setBorder(BorderFactory.createCompoundBorder(
new RoundedBorder(10, new Color(255,204,0)),
new EmptyBorder(0, 0, 0, 0)
));
titleBar = new JPanel();
titleBar.setLayout(null);
titleBar.setBackground(Color.DARK_GRAY);
titleBar.setPreferredSize(new Dimension(frame.getWidth(), 30));
frame.add(titleBar, BorderLayout.NORTH);
titleLabel = new JLabel("Dashboard");
titleLabel.setForeground(Color.WHITE);
titleLabel.setFont(new Font("Arial", Font.BOLD, 16));
titleLabel.setBounds(10, 0, 200, 30);
titleBar.add(titleLabel);
closeLabel = new JLabel("X");
closeLabel.setForeground(Color.WHITE);
closeLabel.setFont(new Font("Arial", Font.BOLD, 16));
closeLabel.setHorizontalAlignment(SwingConstants.CENTER);
closeLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
closeLabel.setBounds(frame.getWidth() - 50, 0, 30, 30);
closeLabel.addMouseListener(new MouseAdapter() {
// close the login form
@Override
public void mouseClicked(MouseEvent e) {
System.exit(0);
}
// mouse hover effect
@Override
public void mouseEntered(MouseEvent e) {
closeLabel.setForeground(Color.ORANGE);
}
@Override
public void mouseExited(MouseEvent e) {
closeLabel.setForeground(Color.WHITE);
}
});
titleBar.add(closeLabel);
minimizeLabel = new JLabel("-");
minimizeLabel.setForeground(Color.WHITE);
minimizeLabel.setFont(new Font("Arial", Font.BOLD, 16));
minimizeLabel.setHorizontalAlignment(SwingConstants.CENTER);
minimizeLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
minimizeLabel.setBounds(frame.getWidth() - 80, 0, 30, 30);
minimizeLabel.addMouseListener(new MouseAdapter() {
// iconify (minimize) the login form
@Override
public void mouseClicked(MouseEvent e) {
frame.setState(JFrame.ICONIFIED);
}
// mouse hover effect
@Override
public void mouseEntered(MouseEvent e) {
minimizeLabel.setForeground(Color.ORANGE);
}
@Override
public void mouseExited(MouseEvent e) {
minimizeLabel.setForeground(Color.WHITE);
}
});
titleBar.add(minimizeLabel);
dashboardPanel = new JPanel();
dashboardPanel.setLayout(new FlowLayout(FlowLayout.CENTER,20,20));
dashboardPanel.setBackground(new Color(240,240,240));
frame.add(dashboardPanel,BorderLayout.CENTER);
// add data
addDatePanel("Sales", "$500k");
addDatePanel("Expenses", "$350k");
addDatePanel("Profit", "$150k");
addDatePanel("Customers", "1,000");
// draw chart
JPanel chartPanel = new JPanel(){
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
// draw chart
drawChart(g, getHeight());
}
};
chartPanel.setLayout(new BorderLayout());
chartPanel.setPreferredSize(new Dimension(740,300));
chartPanel.setBackground(Color.WHITE);
chartPanel.setBorder(new LineBorder(Color.GRAY, 1));
// the chart title
JLabel chartTitleLabel = new JLabel("Orders");
chartTitleLabel.setFont(new Font("Arial", Font.BOLD, 16));
chartTitleLabel.setHorizontalAlignment(SwingConstants.CENTER);
chartTitleLabel.setOpaque(true);
chartTitleLabel.setBackground(new Color(150,50,50));
chartTitleLabel.setForeground(Color.WHITE);
chartPanel.add(chartTitleLabel,BorderLayout.NORTH);
dashboardPanel.add(chartPanel);
// 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) {
// When the mouse is dragged, this event is triggered
// Get the current location of the mouse on the screen
Point newLocation = e.getLocationOnScreen();
// Calculate the new window location by adjusting for the initial mouse offset
newLocation.translate(-mouseOffset.x, -mouseOffset.y);
// Set the new location of the main window to achieve dragging effect
frame.setLocation(newLocation);
}
}
});
frame.setVisible(true);
}
// create a method to add data to the panel
private void addDatePanel(String title, String value)
{
JPanel dataPanel = new JPanel(){
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
// draw the data panel
drawDataPanel(g, title, value, getWidth(), getHeight());
}
};
dataPanel.setLayout(new GridLayout(2, 1));
dataPanel.setPreferredSize(new Dimension(170,100));
dataPanel.setBackground(new Color(255,255,255));
dataPanel.setBorder(new LineBorder(new Color(255,204,0), 5));
dashboardPanel.add(dataPanel);
}
// Create a Custom method to draw a data panel
private void drawDataPanel(Graphics g, String title, String value, int width, int height){
Graphics2D g2d = (Graphics2D) g;
// Customize the data panel appearance here
g2d.setColor(new Color(255,255,255));
g2d.fillRoundRect(0, 0, width, height, 20, 20);
// Stylish background color for Data Panel Title
g2d.setColor(new Color(150,50,50));
g2d.fillRect(0, 0, width, 40);
g2d.setColor(Color.WHITE);
g2d.setFont(new Font("Arial",Font.BOLD,20));
g2d.drawString(title, 20, 30);
// value
g2d.setColor(Color.BLACK);
g2d.setFont(new Font("Arial",Font.BOLD,16));
g2d.drawString(value, 20, 75);
}
// Create a Custom method to draw a chart
private void drawChart(Graphics g, int height)
{
Graphics2D g2d = (Graphics2D) g;
// Customize the chart appearance here
int barWidth = 60;
int barSpacing = 55;
int startX = 50;
int starY = height - 80;
// Sample data values
int[] data = {100,200,150,300,250,350};
// Calculate maximum data value for scaling
int maxDataValue = 0;
for(int value : data)
{
if(value > maxDataValue)
{
maxDataValue = value;
}
}
// Set colors for bars and labels
Color barColor = new Color(76, 175, 80);
Color labelColor = Color.BLACK;
// Draw the bars and labels
for(int i = 0; i < data.length; i++)
{
int barHeight = (int)((double)data[i]/maxDataValue*(starY-60));
int x = startX + (barWidth + barSpacing) * i;
int y = starY - barHeight;
g2d.setColor(barColor);
g2d.fillRect(x, y, barWidth, barHeight);
// Draw data labels
g2d.setColor(labelColor);
g2d.setFont(new Font("Arial", Font.BOLD, 14));
g2d.drawString(String.valueOf(data[i]), x + 10, y - 10);
// Draw product labels (e.g., "Product 1", "Product 2", etc.)
g2d.setFont(new Font("Arial", Font.PLAIN, 12));
g2d.drawString("Product " + (i + 1), x + 5, starY + 20);
}
}
public static void main(String[] args) {
new DashboardForm();
}
}
// Create a Custom Border class for rounded corners
class RoundedBorder implements Border
{
private int radius;
private Color color;
public RoundedBorder(int radius, Color color){
this.color = color;
this.radius = radius;
}
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(color);
g2d.drawRoundRect(x, y, width-1, height-1, radius, radius);
}
@Override
public Insets getBorderInsets(Component c) {
return new Insets(radius, radius, radius, radius);
}
@Override
public boolean isBorderOpaque() {
return true;
}
}
/****************** Dashboard Form End ******************/
The Final Result:
if you want the source code click on the download button below
More Java Projects:
Download Projects Source Code