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;
}
}
}
More Java Projects:
Download Projects Source Code