Static or Dynamic Way to Display Image in jFrame in Java Swing

In this post, SKOTechLearn describe the static and dynamic way to Display Image in jFrame in Java Swing with Netbeans through jLabel. Simply we can add image through Properties Settings or using Code which is described bellow.

Why we use jLabel for displaying image? Because, This is the simple way to handle any files like: jpeg, png etc using jLable pallet.

Open jFrame through Another jFrame in Java Swing

If you want to show external image or use it as internal way like add as logo or banner, then here we will describe as dynamic and static way. So lets learn with following two process:


Come to the point by point description.

(1) Display Image in jLabel in Java Swing Static way :

In this process just create an image file or use your existing file and copy that file in your particular package. For this step by step process let's find following.

Suppose if you create a picture file and want to show. Then first copy that particular file and paste it on your project's package, or you can access through external path.
Drag_Image_File_In_Java_Package
Drag Image File In Package

Tips to Auto Resize Control Setting in Java Netbeans

As you can see, I simply copy my particular file and paste on my package. After that simply drag a jLabel from palette and adjust it's height width and location according to desire and after that follow the steps:


1.
Right click on jLabel.

2.
Select 'Properties' option or go to directly on 'Properties' window.

3.
Find “icon” option. And select your particular file.

4.
If it not show any file just click on 'Custom editor' buttonCustom_Editor_Buton_in_Java

5.
And select file from there.


For 'Custom editor' button, you can see that it will contain with icon's option of Properties windows. For easily understanding process follow the image.
Set_Icon_in_jLabel
jLabel icon setting

When you done all this process. It will display picture like shown in above figure.
So, this is the way of showing picture in static way.

How to Design or Change Look of jLabel in Java in Netbeans


(2) Display Image in jLabel in Java Swing Dynamic way:

If you want to show image in dynamic way, you have to write code for it, Suppose you want to show picture during jFrame's open or activate. So write code as we describe bellow.

But first, you have to import some class inside your java Package:
package simple_java; 

  import java.awt.image.BufferedImage;
  import java.io.IOException;
  import javax.imageio.ImageIO;
  import javax.swing.ImageIcon;

Now lets write show picture code on WindowsOpened evets:
private void formWindowOpened(java.awt.event.WindowEvent evt) { 
   try{
       BufferedImage image1 = ImageIO.read(getClass().getResource("skotechlearn.png"));
       jLabel1.setIcon(new ImageIcon(image1));
   }catch(IOException imgl){}

 }   

How to show external image in jLabel?

If you want to show picture from external url or path, then write code like:
String myimgpath; 
myimgpath= "your exteral file path";
Icon myimgicon = new ImageIcon(myimgpath);
jLabel1.setIcon(myimgicon);

When you run application then it will load picture during runtime and display it on jLabel.

Note:- You can also set jLabel as background image by setting the height width of jLabel according to jFrame.

So, this is the way of displaying image on jFrame in java Netbeans with static and dynamic process which is easily described in above given step by step process in SKOTechlearn post.

Simple Tips to Creating Swing GUI Application in Java

For further learning of coding, programming  or simple tips and trick related to OS, follow SKOTechlearn and learn things as simple as possible.

Tips to Use of jList for Showing Data in Java Swing

Show Drives With Folders and Files in TreeView in VB.Net, C#

If you are trying to show Drives, Folders, Sub-Folders and Files without using FolderBrowserDialog or OpenFileDialog through VB.Net Code. Then you can try TreeView control for this process. To use TreeView as File Explorer or Folder Explorer, there are some simple and easy coding and setting tips you have to apply.

So, here we try to Show Drives with Folders and Files in TreeView in VB.Net, C# coding.

(File's Icons in ListView) Show List of Files with Files' Icons in Listview

But, first we understand why we need TreeView as FileExplorer? The answer is very simple, whenever we develop1 an application and want to show files, folders or drives in static way then we use many controls like ListBox, ListView or TreeView as File browser or Folder browser.

Now, Lets proceed with following point:

  1. Show Drives with Folders and File in TreeView in VB.Net (VB, C#)
  2. Get TreeView Selected Node Path in Label VB.Net (VB, C#)

Now, let's start with point wise.

Searching Files from Folders or Sub-Folders through code using VB.Net

(1). Show Drives with Folders and File in TreeView in VB.Net (VB , C#) :

First we have to add some controls like Button, Label, Treeview. Now here we use these controls with following Names.

ExplorerBtn : Button
MytrView1 : Treeview
MyPathLabel : Label

First, we write code inside Button for calling Drives.

Button’s Click Event for Showing Drives in TreeView.

VB.Net :
 Private Sub ExplorerBtn_Click(sender As Object, e As EventArgs)
  'Clear TreeView
  MytrView1.Nodes.Clear()

  'Loop For Get Drives
  For Each myDrives As System.IO.DriveInfo In System.IO.DriveInfo.GetDrives()
     Dim myDrivesNode As TreeNode = MytrView1.Nodes.Add(mydrives.Name)
     'Adding "Expand" string is use for Add Expand "[+]" option on Drives
     myDrivesNode.Nodes.Add("Expand")
  Next

 End Sub

C# :
 private void ExplorerBtn_Click(object sender, EventArgs e)
 {
    //Clear TreeView
    MytrView1.Nodes.Clear();

    //Loop For Get Drives
    foreach (System.IO.DriveInfo myDrives in System.IO.DriveInfo.GetDrives())
    {
       TreeNode myDrivesNode = MytrView1.Nodes.Add(myDrives.Name);
       //Adding "Expand" string is use for Add Expand "[+]" option on Drives
       myDrivesNode.Nodes.Add("Expand");
    }

  }

So, this code will present output in following way:
Show Drives in Treeview VB.Net
After that, we use 'BeforeExpand' event of Treeview for getting Folders and Files List on particular Drives.

VB.Net :
 Private Sub MytrView1_BeforeExpand(sender As Object, e As TreeViewCancelEventArgs)
   Dim MyExistNode As TreeNode = e.Node
   'Clear TreeNode
   MyExistNode.Nodes.Clear()

   Try
     'Loop For Get Folders
     Dim mypath As String = MyExistNode.FullPath

     'Loop For Get Folders
     For Each myFolders As String In System.IO.Directory.GetDirectories(mypath)
        Dim FldrNode As TreeNode = MyExistNode.Nodes.Add(System.IO.Path.GetFileName(myFolders))
        'Here, Expand is use for add Expanding option "[+]" on folder
        FldrNode.Nodes.Add("Expand")
     Next

     'Loop For Get Files
     For Each MyFiles As String In System.IO.Directory.GetFiles(mypath)
        Dim FLNode As TreeNode = MyExistNode.Nodes.Add(System.IO.Path.GetFileName(MyFiles))
     Next

    Catch ex As Exception

    End Try
  
 End Sub

C# :
private void MytrView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
  {
     TreeNode MyExistNode = e.Node;
     //Clear TreeNode
     MyExistNode.Nodes.Clear();

     try
      {
        string mypath = MyExistNode.FullPath;

        //Loop For Get Folders
        foreach (string myFolders in System.IO.Directory.GetDirectories(mypath))
        {
           TreeNode FldrNode = MyExistNode.Nodes.Add(System.IO.Path.GetFileName(myFolders));
           //Here, Expand is use for add Expanding option "[+]" on folder
           FldrNode.Nodes.Add("Expand");
         }

        //Loop For Get Files
        foreach (string MyFiles in System.IO.Directory.GetFiles(mypath))
         {
                
            TreeNode FLNode = MyExistNode.Nodes.Add(System.IO.Path.GetFileName(MyFiles));
               
          }

       }
        catch (Exception FlErr)
       {
          MessageBox.Show(FlErr.ToString());
       }

   }

OK, when you run your application this will show following output:
Show Drives Folders Files in Treeview VB.Net

As you can see, when you click on any drive this will expand with containing Folders and files and when you expand any folder this will show your list of sub-folders and files in Treeview.

Styling ProgressBar in VB.Net

(2). Get Treeview Selected Node Path in Label VB.Net (VB, C#) :

Now, let’s try to get selected Node path in Label from Treeview. So, here we go through code process.

You have to first go to “AfterSelect” event of Treeview and write following code:

VB.Net:
 Private Sub MytrView1_AfterSelect(sender As Object, e As TreeViewEventArgs)
    
  Dim MySelectedNode As TreeNode = e.Node
  'Get Selected Node Path
  MyPathLabel.Text = MySelectedNode.FullPath
    
 End Sub

C# :
private void MytrView1_AfterSelect(object sender, TreeViewEventArgs e)
  {
     TreeNode MySelectedNode = e.Node;
     //Get Selected Node Path
     MyPathLabel.Text = MySelectedNode.FullPath;
    
  }

This will work like following way:
Get TreeView Selected Node Path in Label VB.Net

Okay, now we have learned how to Show Drives with Folders and Files in TreeView in VB.Net using VB and C# code. You can also try and ask any question related to this topic describe in SKOTechLearn Tips.

Change jTable Column Header and Rows Color in Java NetBeans Easily

In this post, SKOTechLearn will explain how to Change Color of jTable in Java like Column Header Color, grid Color, Rows Color, Selection Color. When I was started programming in java and using jTable, I faced problem of jTable background color foreground color of particular cells or rows and columns.

So here are the simple and easy tips to Change jTable Column Header and Rows Color in Java Netbeans Easily.

Easily Add Column Header in jTable with Grid Settings in Java

So here SKOTechLearn will described, how to Change jTable Column Header and Rows Color in Java NetBeans in simple way?
jTable background and foreground color in Java

So, Let’s take a look of Following Color changing point.

  1. jTable Column Header Background Color and Foreground or Font Color 
  2. jTable Column Header Background Color and Foreground Color in NetBeans
  3. jTable Rows Background and Foreground Color
  4. Change Background and Foreground Color of Particular Column's Rows in jTable
  5. jTable Selection background and Foreground Color
  6. jTable Selection Background and Foreground Setting in NetBeans

First you have to import Color Class:
 import java.awt.Color;

Now, Let's Proceed with above given point.


 (1). jTable Column Header Background Color and Foreground or Font Color :

There are many ways to change Header’s back color. You can change it through predefined system color or you can use custom color.

Column Header background with default system Color:
 MyTblView.getTableHeader().setBackground(Color.MAGENTA);

Column Header background with Custom Color :
 MyTblView.getTableHeader().setBackground(Color.decode("#696B9E"));

Or you can use JTableHeader class.

Enable or Show jTable Sorting Option in Java

First import this class:
 import javax.swing.table.JTableHeader;

Then use this class with following way:
 JTableHeader TblHeader = MyTblView.getTableHeader();
 TblHeader.setBackground(Color.GREEN);
Same above code process will apply here; we can set Foreground color with system default and custom color setting.

Column Header Foreground with default system Color :
 MyTblView.getTableHeader().setForeground(Color.BLUE);

Column Header Foreground with Custom Color :
 MyTblView.getTableHeader().setForeground(Color.decode("#FCE7FC"));

JTableHeader class for Foreground color code:
JTableHeader TblHeader = MyTbleView.getTableHeader();
 TblHeader.setForeground(Color.RED);

When you run any code the output will show in following way:
jTable_ColumnHeader_Background_and_Foreground_Color_Java


 (2). jTable Column Header Background Color and Foreground Color in NetBeans :

If you are using NetBeans for swing GUI project using jTable, the column header color will apply in different coding way. You have to use DefaultTableCellRenderer class in NetBeans Code.

DefaultTableCellRenderer MyHeaderRender = new DefaultTableCellRenderer();
MyHeaderRender.setBackground(Color.decode("#696B9E"));
MyHeaderRender.setForeground(Color.decode("#FCE7FC"));

MyTblView.getTableHeader().getColumnModel().getColumn(0).setHeaderRenderer(MyHeaderRender);
MyTblView.getTableHeader().getColumnModel().getColumn(1).setHeaderRenderer(MyHeaderRender);
MyTblView.getTableHeader().getColumnModel().getColumn(2).setHeaderRenderer(MyHeaderRender); 

After that this will show given output:
Netbeans_jTable_Header_Color


 (3). jTable Rows Background and Foreground Color :

There is simple code for doing this. But remember one thing; it can change color of all rows. The simple and easy codes are as follows:
 MyTblView.setBackground(Color.LIGHT_GRAY);
 MyTblView.setForeground(Color.BLUE);
This code will not be use for particular rows settings.

This will show the following output.
jTable_Rows_Background_and_ForeGround_Color


 (4). Change Background and Foreground Color of Particular Column's Rows in jTable :

Now, this is the very interesting point, because I have searched this point in many web-page and not find any suitable way to do this.

But, SKOTechLearn will explain simple tips to change Particular Column color of jTable in Java it, write or copy given code and see what happen.

First you have to import DefaultTableCellRenderer class:
import javax.swing.table.DefaultTableCellRenderer;

After that write given code:
 DefaultTableCellRenderer MyCellrendar = new DefaultTableCellRenderer();
 
 MyCellrendar.setBackground(Color.yellow);
 MyCellrendar.setForeground(Color.RED);

 MyTblView.getColumnModel().getColumn(1).setCellRenderer(MyCellrendar);

The output will be display like:
jTable_Particuluar_Column_and_cell_color_java
In getColumn() method, you can put any column number inside it and this will apply on that particular column's rows.

 (5). jTable Selection background and Foreground Color :

In java, there is facility to change selection color of particular rows in jtable according to requirement.

You can apply one line code as described below:
 MyTblView.setSelectionBackground(Color.BLACK);
 MyTblView.setSelectionForeground(Color.YELLOW);

jTable_Selection_Background_Foreground_Color


 (6). jTable Selection Background and Foreground Setting in NetBeans :

If you are using NetBeans, then you can simply go to “Properties” window and find “selectionBackground” and “selectionForeground” option and choose color according to your requirement.

Steps are described in given following image:
jTable_Selection_Color_Setting_Netbeans

So, these are the color changing process which is explained in Change jTable Column Header and Rows Color in Java NetBeans Easily.

Add Column Header in JTable and Grid Line Settings in jTable in Java

When you design you java project and want to show list of data in rows and columns format, you require a table or list, but List only contain one column with multiple rows and table contains multiple columns with multiple rows. You can find complete details of jTable class.

So Friends, here SKOTechLearn will discuss about jTable in Java with details description of Add Column Header in JTable in Java with jTable Grid setting in java NetBeans.

Change jTable's Column Header, Rows, Cell, Selection Color With Simple Steps

Suppose, you want to display some records which contains some Column. Then we have to drag jTable or write code for Adding Column Header in Java with Grid Settigns.


Here we proceed with following way:

  1. Add Column Header in jTable in Java Code
  2. Add Column Header in jTable in Netbeans through Properties
  3. jTable Grid Line Setting in java code
  4. jTable Grid line Setting in java Netbeans through Properties

So, let’s start with point to point.


(1). Add Column Header in jTable in Java Code :

For Column Header in JTable, you have to import some class as describe bellow:
 import javax.swing.JFrame;
 import javax.swing.JScrollPane;
 import javax.swing.JTable;
 import javax.swing.table.DefaultTableModel;

After that simply write following code:
 import javax.swing.JFrame;
 import javax.swing.JScrollPane;
 import javax.swing.JTable;
 import javax.swing.table.DefaultTableModel;

 public class MyTableClass {

   public static void main(String[] args) {
    // TableModel is use for showing rows and columns
    DefaultTableModel MyTablemodel = new DefaultTableModel();
    //Create New Table
    JTable MyTableView = new JTable(MyTablemodel);
    // Add jTable in jScollPane for Showing Column Header
    JScrollPane MyScrollPane= new JScrollPane(MyTableView);
    //Add Column Name 
    MyTablemodel.addColumn("MyColHead_ID");
    MyTablemodel.addColumn("MyColHead_Name");
    MyTablemodel.addColumn("MyColHead_Contact");
    //Add jFrame for showing Table inside frame
    JFrame MyTblFrame = new JFrame();
    MyTblFrame.setTitle("jTable Column Header Frame");
    //Set jFrame Size
    MyTblFrame.setSize(410, 320);
    MyTblFrame.add(MyScrollPane);
    MyTblFrame.setVisible(true);
   }
    
 }

Note : If you want to add rows and columns, DefaultTableModel will provide facility to do this.

When you execute this code this will show the following result:
jTable Column Header in Java


 (2). Add Column Header in jTable in NetBeans through Properties :

If you are using NetBeans for Java, First drag jTable in jFrame after that simply follow the following steps.

1.
 Right Click on jTable control and find “Table Contents…” option.

2.
 Click on “Table Contents…” option. “Customizer Dialog” will be displayed.

3.
 “Customizer Dialog” contains three tabs (Table Model, Columns, Rows ).

4.
 For headers, you have to choose “Columns” tab.

5.
 In “Columns” tab, you will find a table containing “Title, type, Resizable, Editable”. This is use for Column header settings.

6.
 Choose “Columns” tab which is also contain some buttons(Insert, Delete, Move Up, Move Down).

7.
 ‘Insert’ button is used to add Columns, ‘Delete’ is used for delete Columns, ‘Move Up’ and ‘Move Down’ button is used for move column left or right in jTable according to your requirement.

8.
 Select ‘Title’ Column from table and go to “Title” box and write your column Name.

9.
 After that simply close “Customizer Dialog”.

jTable Column Header Settings in Netbeans
Column Header Settings in NetBeans

When all settings will be done, your table will looks like bellow.
jTable Column Header Setting output in Netbeans


 (3). jTable Grid Line Setting in java code :

If you want to change Grid Line color of jTable, first you have to add some rows and then you can write following code which is very simple and one line code.

Grid Color Setting Code:
 MyTableView.setGridColor(Color.red);

Now check it with following code:
public static void main(String[] args) {
    DefaultTableModel MyTablemodel = new DefaultTableModel();
    JTable MyTableView = new JTable(MyTablemodel);
   
    //jTable grid Line Settings
    MyTableView.setGridColor(Color.red);
    
    JScrollPane MyScrollPane= new JScrollPane(MyTableView);
    MyTablemodel.addColumn("MyColHead_ID");
    MyTablemodel.addColumn("MyColHead_Name");
    MyTablemodel.addColumn("MyColHead_Contact");
    // add some rows
    MyTablemodel.addRow(new Object[]{"Col1Row1_0000", "Col2Row1_ABCD", "Col3Row1_XXX0124556"});
    MyTablemodel.addRow(new Object[]{"Col1Row1_0001", "Col2Row1_EFGH", "Col3Row1_XXX01253344"});
    
    JFrame MyTblFrame = new JFrame();
    MyTblFrame.setTitle("jTable Column Header Frame");
    
    MyTblFrame.setSize(410, 250);
    MyTblFrame.add(MyScrollPane);
    MyTblFrame.setVisible(true);
  }

This will display output in given following figure:
jTable Gird Color Change in Java


 (4). jTable Grid Line Setting in java Netbeans through Properties :

If you are using NetBeans for creating Swing project, you will find that jTable has no GridLines. First you have to add Gridlines then you can change Grid color according to your requirement.
 MyTableView.setShowGrid(true);
 MyTableView.setGridColor(Color.MAGENTA);

Or you can simple choose Grid Color from “Properties” window like bellow:
jTable Grid Color Properties in Netbeans

So, In this post you can see, how amazing is to work in java and NetBeans framework. You can simply Add Column Header in JTable and Grid Line Setting in jTable in Java which is detailed explained by SKOTechLearn.

Best Way of JTable Sorting in Java Netbeans with Details

jTable basically used for displaying information in the form of rows and columns. In Java you can easily design your table according to your need, so In this post we learn the Best way of jTable Sorting in Java NetBeans.

Easy Way to Add Coulmn Header and Change Grid Line Color of jTable in Java

Here, SKOTechLearn will explain row sorting of jTable with following way.

  1. Static way to Enable Row Sorting of jTable in Java
  2. Sort Particular Column of jTable in Java dynamically
  3. Disable Particular Column for Sorting of jTable in Java dynamically

Suppose we add some records in table. Now we have to proceed with above given point.


 (1). Static way to Enable Row Sorting of jTable in Java :

If you want to enable row sorting during design time. And sort it during run time then it can be done by two ways:

Enable Row Sorting through Properties in NetBeans

In NetBeans, you can just go to jTable’s "Properties" window, and find “autoCreateRowSorter” option from it.

Now, you have to check this option for enabling sorting like bellow.
AutoCreateRowSorter Setting in JTable in Netbeans
autoCreateRowSorter Setting
When you will check mark on “autoCreateRowSorter” and run application, you have to double click on any Column Header, the column will be sorted according to row’s value in ascending or descending way.
jTable Column Sorting in Java
jTable Column Sorting

Enable Row Sorting through code in Java NetBeans

if you want to set RowSorter through code then you can simply add this  "MyTableView.setAutoCreateRowSorter(true);" code in following way.
 public TableSortFrame() {     
   initComponents();
   //Here MyTableView is jTable   
   MyTableView.setAutoCreateRowSorter(true);
 }

So, this way you can easily create jTable with row sort setting in design time.


 (2). Sort Particular Column of jTable in Java dynamically :

Suppose, you make a project or application where you need to sort only specific column, then you have to follow with further steps.

Suppose, we want to sort Column No. 2 as describe above given table’s data. Now we sort “MyCol2” at runtime.

But first we have to import some classes:
 import javax.swing.table.TableModel;
 import java.util.ArrayList;
 import java.util.List;
 import javax.swing.table.TableRowSorter;
 import javax.swing.RowSorter;
 import javax.swing.SortOrder;

After that, we will drag jButton and write code for it like bellow:
 private void ColSortBtnActionPerformed(java.awt.event.ActionEvent evt) {  
   // MyTableView is jTable        
   TableRowSorter<TableModel> ColSort = new TableRowSorter<>(MyTableView.getModel());
   MyTableView.setRowSorter(ColSort);
   List<RowSorter.SortKey> ColSortingKeys = new ArrayList<>();
   //"SortColNo" is use to set Column No for Sorting
   int SortColNo = 1;
   //"SortKey" is used for sort order for a particular column
   ColSortingKeys.add(new RowSorter.SortKey(SortColNo, SortOrder.ASCENDING));
 
   ColSort.setSortKeys(ColSortingKeys);
   ColSort.sort();
  }       

In above code, We have changed jTable’s Name with “MyTableView”.

When you run jFrame. And click on “ColSortBtn”. This will show the following output:
jTable particular Column Sorting in Java
Friend, in above given way, you can easily sort any specific or particular column of jTable in Java at run time.

 Note: If you Double Click on any other column, then the sorting will also be apply on that column.


 (3). Disable Particular Column for Sorting of jTable in Java dynamically :

As you can see, the above given sorting process will be apply on any other column at run time.

If, you want to fix that only particular column will be sort and other column will not be used as sorting process. Then you have to disable that particular column for sorting.

Disable Column Sorting of jTable in Java

Suppose, you want to apply sorting in Column No. 3, and Disable Sorting in Column 1 and Column 2 then you will simply write following code for this process:
 private void ColSortBtnActionPerformed(java.awt.event.ActionEvent evt) {  
    TableRowSorter<TableModel> ColSort = new TableRowSorter<>(MyTableView.getModel());
    MyTableView.setRowSorter(ColSort);
    List<RowSorter.SortKey> ColSortingKeys = new ArrayList<>();
    //"SortColNo" is use to set Column No for Sorting
    int SortColNo = 2;
    //"SortKey" is used for sort order for a particular column
    ColSortingKeys.add(new RowSorter.SortKey(SortColNo, SortOrder.ASCENDING));
 
    ColSort.setSortKeys(ColSortingKeys);
    ColSort.sort();
    //Disable sorting in column 0 and column 1
    ColSort.setSortable(0, false);
    ColSort.setSortable(1, false);
 }
When you run it, this will work like following image.
Disable Column Sorting in jTable in Java
So Friends, you can try it yourself and find that what will happen. Simply create project in Java and write code for jTable Row sorting in Java Netbeans using SKOTechLearn Tips.

SQL Server Database Connection String in Java NetBeans with Query

In java, when you want to connect MS SQL Server Database and want to show Table’s record in java, then you have to remember one thing, you have to require suitable database driver for java.

So, Here SKOTechLearn will describe the process steps by step for SQL Server Database Connection String in Java with Query.

Connect Database And Access All Tables and Records with NetBeans

For This process you have to follow the steps given following.

  1. Download “sqljdbc4.jar” file 
  2. Attach “sqljdbc4.jar” File in Project’s Package
  3. Import SQL Class and Other Related Class 
  4. SQL Server Connection Code in Java with Example
  5. Use SQL Server Query in Java NetBeans


 Step(1). Download “sqljdbc4.jar” file :

If you want to use database connection on your projects, you have to know that you have to required suitable driver for database connection in java.

So, For SQL Server Connection in Java, you can use “sqljdbc4.jar” file for driver.

You can find it from many sites, and here are two sites where you can find this driver easily.

First Site
Second Site

 Step(2). Attach “sqljdbc4.jar” File in Project’s Package :

After that you have to create your project and when you expand your project in NetBeans, you will find there are many Package Folders available.

 1.
 Find “Libraries” Package Folder from you project.

 2.
 Right click on “Libraries” Package Folder. And Select third option “Add JAR/Folder…”.

 3.
 This option will show you “Add JAR/Folder” Window.

 4.
 Browse your downloaded “sqljdbc4.jar” file.

Add sqljdbc4 jar file in Java Project's Libraries
This jar file will be added on your project’s “Libraries” like above given image.

How to Set Default Main Class in Java Using Netbeans

 Step(3). Import SQL Class and Other Related Class :

Now, before start connection string, you have to import some class as described below.
 //java.sql.Connection is use for establishing connection from database
 import java.sql.Connection;
 //java.sql.DriverManager is used for calling driver with connection string
 import java.sql.DriverManager;
 //javax.swing.JOptionPane for Display Message
 import javax.swing.JOptionPane;


 Step(4). SQL Server Connection Code in Java with Example :

Now let’s try to connect database from server in java Netbeans, We will write code inside jButton’s ActionPerformed event.
 private void SQLConn_BtnActionPerformed(java.awt.event.ActionEvent evt) {    
  try {
     Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
     Connection SQlCnn = DriverManager.getConnection("jdbc:sqlserver://XXX.XXX.X.XX; databaseName= MySQLDB; user= MYSQLUser; password= MySQLPasswrd");
     JOptionPane.showMessageDialog(null, "SQL Server Connection Successfully.");
     SQlCnn.close();
  }catch (Exception CnnErr){
     JOptionPane.showMessageDialog(null, "SQL Server Connection Problem");
  }
 }

When you run this code, the following output will be shown:
SQL Server Connection String Output in Java
Simply copy above code and modify servername, databasename, username and password then run your project.

Simple Way to Display Image in Java


 Step(5). Use SQL Server Query in Java NetBeans :

Suppose we have a table “MySQLDBTable” and there is two column “MyTBL_ID” and “MyUsrName”. And this table contains some records like bellow:

Database Table's Record in Netbeans
So, if you want to display all records, you have to use “Select Query Statement”. And write code in NetBeans in following way.

Use of  Select Query in Java 


private void SQLQuery_BtnActionPerformed(java.awt.event.ActionEvent evt) {
  try {
     Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
     Connection SQlCnn = DriverManager.getConnection("jdbc:sqlserver://XXX.XXX.X.XX; databaseName= MySQLDB; user= MYSQLUser; password= MySQLPasswrd");
     Statement MyDBstmt = SQlCnn.createStatement();
     ResultSet MyRSet = MyDBstmt.executeQuery("Select * From MySQLDBTable");
     while( MyRSet.next()) {
          System.out.println(MyRSet.getString("MyTBL_ID") + "   |   " + MyRSet.getString("MyUsrName"));
        }    
     MyRSet.close();
     MyDBstmt.close();
     SQlCnn.close();
        
   }catch (Exception DBErr){
      JOptionPane.showMessageDialog(null, "SQL Server Connection Problem");
   }
 }   

When you run this code, this will show you following output.
Select Query Output in Java NetBeans
So, these are the steps for establishing connection from database server or SQL Server Database Connection String in Java Netbeans with Query.

What Settings for Auto Resize Control in Java Using Netbeans?

Show Files List With Icons In Listview Using ImageList in VB6.0

In this post, we will learn items with image in Listview. Sometimes we require a list which contain image including items. The listview will use for this process due to its fast and easiest way in vb6.0. There is a simple process for doing practical on your VB6.0 application development. So, SKOTechLearn will explain the way to Show Files List with Icons in Listview using ImageList in VB6.0.

In the following steps we describe the 3 code process, in which you can use anyone code process for your desire.

Dynamically Add Items in ListView in VB6

Show files List with Path and Icon in Listview using ImageList in vb6.0 like bellow:
ListView_with_Files_and_Icons_in_VB6.0

Let’s find and learn, how can we find this type of output?


 (1). Create some images for Icons:

 We have to create some images for showing as icon in Listview. Now ,try to create through Paint with Print Screen process as I created bellow.

Images for Listview Icons in Vb6.0


 (2). Drag Some Controls:

 Now drag some controls like Command button for doing activity and Listview for Showing List with icons and Path and ImageList Control for fetching images.

Here we changed Listview1 name is MyLstView and ImageList1 name is MyImageList

Simply use ListView for Edit or Delete Selected Items


 (3) ImageList and Listview Settings: 

 First we add some image in ImageList through properties and set every image with Key name, which is use for calling inside Listview. After that we setting on Listview Properties like Column header and View type etc.

ImageList properties and ListView Properties Settings

In above given image you can Set Listview Properties with Column Header easily.

Now write code for listing Files with icon as describe bellow.


 Process(1):
 In this process we use Select Case Statement for showing files with path and icons in Listview.

VB6.0:
 Private Sub ShowFileIcon_Btn_Click()
 'First you have to set listview smallicon with ImageList
 Set MyLstView.SmallIcons = MyImageList
 Dim i As Integer
 i = 1
 With MyLstView

  Dim myFilesList As String
  'Use Dir for Collection files' List
  myFilesList = Dir("C:\SKOTechLearn_Files\*.*")
  'Clear Listview
  MyLstView.ListItems.Clear
  'Loop wntil Files' list will not Null or Empty
  While myFilesList > vbNullString

   Dim MyFLExten As String
   'Following formula is used for Extract "Extension" from Files
   MyFLExten = UCase(Mid(myFilesList, InStrRev(myFilesList, "."), Len(myFilesList)))
      
   Select Case MyFLExten
      Case ".JPG"
           ' Listview.ListItems.Ass [Index], [key], [Text],[Icon], [SmallIcon]
           .ListItems.Add , , myFilesList, , "ImgIco1"
      Case ".PNG"
              .ListItems.Add , , myFilesList, , "ImgIco1"
      Case ".XLS", ".XLSX"
              .ListItems.Add , , myFilesList, , "XlsIco6"
      Case ".PDF"
              .ListItems.Add , , myFilesList, , "PdfIco2"
      Case ".TXT"
              .ListItems.Add , , myFilesList, , "TxtIco4"
      Case ".XPS"
              .ListItems.Add , , myFilesList, , "XpsIco7"
      Case ".DOC", ".DOCX"
              .ListItems.Add , , myFilesList, , "DocIco5"
      Case Else
              .ListItems.Add , , myFilesList, , "OtherIco8"
    End Select

    .ListItems(i).ForeColor = vbBlue
    'List with Path and Files
    .ListItems(i).ListSubItems.Add , , "C:\SKOTechLearn_Files\" & myFilesList
    .ListItems(i).ListSubItems(1).ForeColor = vbRed
    .ListItems(i).ListSubItems.Add , , MyFLExten
    ' retun remaining Dir File's List
     myFilesList = Dir
    DoEvents
    i = i + 1
  Wend

 End With

 End Sub


Remove Multiple Checked Items from Listview Easily


 Process(2):
 In this Process we Use If Else Statement for showing Files List with icons in ListView.

VB6.0:
 Private Sub ShowFileIcon_Btn2_Click()
 'First you have to set listview smallicon with ImageList
 Set MyLstView.SmallIcons = MyImageList
 Dim i As Integer
 i = 1
 With MyLstView

   Dim MyFlList As String
  'Use Dir for Collection files' List From path
   MyFlList = Dir("C:\SKOTechLearn_Files\*.*")
   MyLstView.ListItems.Clear
   While MyFlList > vbNullString

      Dim MyFLExt As String
     'following formula used to extact "Extension" From Files
      MyFLExt = UCase(Mid(MyFlList, InStrRev(MyFlList, "."), Len(MyFlList)))

      If MyFLExt = ".JPG" Or MyFLExt = ".PNG" Or MyFLExt = ".XLS" Or MyFLExt = ".XLSX" Or MyFLExt = ".PDF" Or MyFLExt = ".TXT" Or MyFLExt = ".XPS" Or MyFLExt = ".DOC" Or MyFLExt = ".DOCX" Then

          If MyFLExt = ".JPG" Then
              ' Listview.ListItems.Ass [Index], [key], [Text],[Icon], [SmallIcon]
              .ListItems.Add , , MyFlList, , "ImgIco1"
          End If
          If MyFLExt = ".PNG" Then
              .ListItems.Add , , MyFlList, , "ImgIco1"
          End If
          If MyFLExt = ".XLS" Or MyExt = ".XLSX" Then
              .ListItems.Add , , MyFlList, , "XlsIco6"
          End If
          If MyFLExt = ".PDF" Then
              .ListItems.Add , , MyFlList, , "PdfIco2"
          End If
          If MyFLExt = ".TXT" Then
              .ListItems.Add , , MyFlList, , "TxtIco4"
          End If
          If MyFLExt = ".XPS" Then
              .ListItems.Add , , MyFlList, , "XpsIco7"
          End If
          If MyFLExt = ".DOC" Or MyExt = ".DOCX" Then
              .ListItems.Add , , MyFlList, , "DocIco5"
          End If
          
      Else
              .ListItems.Add , , MyFlList, , "OtherIco8"
      End If

      .ListItems(i).ForeColor = vbBlue
      .ListItems(i).ListSubItems.Add , , "C:\SKOTechLearn_Files\" & MyFlList
      .ListItems(i).ListSubItems(1).ForeColor = vbRed
      .ListItems(i).ListSubItems.Add , , MyFLExt
      ' retun remaining Dir File's List
       MyFlList = Dir
     DoEvents
     i = i + 1
   Wend

 End With
 End Sub


 Process(3):
In this process we use FileSystemObject for show Files in Listview with Icons.

How To Add FileSystemObject (scrrun.dll) in VB6.0?

For Using FileSystemObject, you have to first add references ‘Microsoft Scripting Runtime’. This reference contains FileSystemObject class.

The following image will show how to add Microsoft Scripting Runtime (scrrun.dll) in VB6.0.

1.
  Go to Project menu and find “References..” option.

2.
  Click on this option and this will show “References..” window.

3.
  This window will show the Available References List.

4.
  Find “Microsoft Scripting Runtime” and check on it.


add FileSystemObject class in VB6.0
In this way you can add any Reference.

After adding Microsoft Scripting Runtime. Write following code.

VB6.0:
 Private Sub FilesListFSO_Cmd_Click()
 Dim myfsobj As New FileSystemObject
 Dim myfldr As Folder
 Dim myfl As File
 Set myfldr = myfsobj.GetFolder( "C:\SKOTechLearn_Files\" )
 'First you have to set listview smallicon with ImageList
 MyLstView.ListItems.Clear
 Set MyLstView.SmallIcons = MyImageList

 With MyLstView
   Dim li As Integer
   li = 1

   For Each myfl In myfldr.Files
      Dim MyFLExten As String
      'Extract Extension through FileSystemobject's GetExtensionName method
      MyFLExten = UCase(myfsobj.GetExtensionName(myfl))

      Select Case MyFLExten
          Case "JPG"
              .ListItems.Add , , myfl.Name, , "ImgIco1"
          Case "PNG"
              .ListItems.Add , , myfl.Name, , "ImgIco1"
          Case "XLS", "XLSX"
              .ListItems.Add , , myfl.Name, , "XlsIco6"
          Case "PDF"
              .ListItems.Add , , myfl.Name, , "PdfIco2"
          Case "TXT"
              .ListItems.Add , , myfl.Name, , "TxtIco4"
          Case "XPS"
              .ListItems.Add , , myfl.Name, , "XpsIco7"
          Case "DOC", "DOCX"
              .ListItems.Add , , myfl.Name, , "DocIco5"
          Case Else
              .ListItems.Add , , myfl.Name, , "OtherIco8"
      End Select

      .ListItems(li).ForeColor = vbBlue
      .ListItems(li).ListSubItems.Add , , myfl
      .ListItems(li).ListSubItems(1).ForeColor = vbRed
      .ListItems(li).ListSubItems.Add , , MyFLExten
      DoEvents
      li = li + 1

   Next
 End With
 'After show files list, clear Files Folders and FileSystemObject class
 Set myfl = Nothing
 Set myfldr = Nothing
 Set myfsobj = Nothing
 End Sub


Give above 3 process will show the same output as shown bellow image.
Listview With Icons, path and Filenames in Vb6.0
So, SKOTechLearn has Explained with some simple process to Show Files List With Icons In Listview Using ImageList in VB6.0.

How to move checked items from one Listview to Another?