MySQL Connection in Python with MYSQL Select Query in Python

When we want to connect MYSQL Database with application then we have to first consider about MYSQL Connection Driver and MySQL ConnectionString. So here we will describe MYSQL Database Connection in Python or MYSQL connection in Python with database in three ways. 

  1. Using Pyodbc in MYSQL Connection
  2. Using mysql.connector for MYSQL Connection
  3. Using pymysql for MYSQL Connection

Fist thing we have to know that if we want to connect any type of Database organization, then we have to use Driver from particular database organization like MYSQL. So, Lets Start from pyodbc in python.


(1). Using Pyodbc in MYSQL Connection :

For using pyodbc, you have to install pyodbc through pip. Now, lets know the following connection string of pyodbc.


pyodbc.connect("DRIVER={Driver_Name}; User=Server_User; Password=server_Password; Server=localhost/server IP; Database=DatabaseName;")

So, Write following code to show database table’s record in following way:
import pyodbc 

mysqlcn = pyodbc.connect("DRIVER={MySQL ODBC 8.0 ANSI Driver}; User=sko; Password=xxxxxx; Server=xxx.xxx.xxx.xx; Database=mydatabase; ")
dbcursor = mysqlcn.cursor() 
dbcursor.execute("SELECT * FROM TestTable") 
myfield = dbcursor.fetchone() 
# Loop to fetch one by one data.
while myfield:
      # Print partuculat column data from table
print (myfield[0]) 
myfield = dbcursor.fetchone()

#Now Close cursor and connection
dbcursor.close()
mysqlcn.close() 

In this code we use “MySQL ODBC 8.0 ANSI Driver” in pyodbc. 

This will show following output:

MySQL Connect using Pyodbc Output

Show MySQL Data in Listbox in Python


If you want to show data or you can use MYSQL Select Query in Python to show data in Listbox then following code will be help in you coding.

Show Database Record in Listbox:

import tkinter as mytk
from tkinter import *
import pyodbc 

MytkForm = mytk.Tk()
MytkForm.title('MySQL with pyodbc') MytkForm.geometry("250x100") # Create Listbox MyTklist = mytk.Listbox(MytkForm)
#Clear Listbox MyTklist.delete(0,END) mysqlcn = pyodbc.connect("DRIVER={MySQL ODBC 8.0 ANSI Driver}; User=sko; Password=xxxxxx; Server=xxx.xxx.xxx.xx; Database=mydatabase;") dbcursor = mysqlcn.cursor() #MySQL Select Query in Python dbcursor.execute("SELECT * FROM TestTable") myfield = dbcursor.fetchone() while myfield: # Add Field data in Listbox MyTklist.insert(END,myfield[0]) myfield = dbcursor.fetchone() dbcursor.close() mysqlcn.close() MyTklist.pack() MytkForm.mainloop()

OUTPUT: 

MySQL Data Show in Listbox in Python



(2). Using mysql.connector for MYSQL Connection

In this point we will learn how to use mysql.connector for database connection and also learn how to List MYSQL data through column name in python. 

Mysql.connector ConnectionString in Python


mysql.connector.connect(host="XXX.XXX.XXX.XX", user="Database_User", password="Database_Password", database="DatabaseName")

Now Lets, see how to show data?
import mysql.connector
#ConnectionString
mydb = mysql.connector.connect(host="XXX.XXX.XXX.XX", user="sko", password="mypassword", database="mydatabase")
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM TestTable")
myresult = mycursor.fetchall()
for mycol in myresult:
   # Get Second Column's row List
   print(mycol[1])

mydb.close()
mycursor.close() 

OUTPUT:

MySQL Connect using mysql.connector


In this given output, you can see, we show only second column data through “mycol[1]” this code. 

MySQL Column Value show through Column Name in Python in Listbox: 


As you saw before, we are showing data through Column Number, but if we have more columns and want to show particular column value then we have to determine Column Name

So, through following way you can use to show column value through Column Name. You have to add following code in cursor method.


mycursor = mydb.cursor(dictionary=True)

Lets see with full details:
import mysql.connector
import tkinter as mytk
from tkinter import *

MytkForm2 = mytk.Tk()
MytkForm2.title('MySQL with mysql.connector') MytkForm2.geometry("270x120") MyListData= mytk.Listbox(MytkForm2)
mydb = mysql.connector.connect(host="XXX.XXX.XXX.XX", user="sko", password="mypassword", database="mydatabase") #Fetch Particular Column Value through Column name with using dictionary mycursor = mydb.cursor(dictionary=True) mycursor.execute("SELECT * FROM TestTable") myresult = mycursor.fetchall() for MyColName in myresult: MyListData.insert(END, MyColName ["MyDetails"]) mydb.close() mycursor.close() MyListData.pack() MytkForm2.mainloop()

Now, This will Show output according to Column Name.
MySQL Data in ListBox using column name in python


(3). Using Pymysql for MYSQL Connection

You can use another connector in python that's call pymysql. First you have to install pymysql. After that you have to use following connection string.
pymysql.connect(host="XXX.XXX.XXX.XX", user="MySQLUsername", password="MYSQLPassword", database="MYSQLDatabase")

Then write following code to show data in Python.
import pymysql

# database connectionstring
connmysql = pymysql.connect(host="XXX.XXX.XXX.XX", user="sko", password="mypassword", database="mydatabase")
cursordb = connmysql.cursor()

# execute your query through execute().
cursordb.execute("SELECT * FROM TestTable")

# get all row through fetchall().
data = cursordb.fetchall()
for colnm in data:
    print(colnm[0])

# close connection
connmysql.close()

OUTPUT:



Conclusion: You can use any one of these method. You will find some performance differences. But you will find exact result using any connector in python.

So, this way you can Connect MYSQL in Python with step by step process.

How to Make Image Selected Area Transparent in Gimp

In this post SKOTechLearn will describe How to Make Image Selected Area Transparent in GIMP or Image Selected Area Transparent in GIMP. As you know GIMP provide image processing of all kind of image formats. You can modify, beautify and change format of image through this application.

Selected Area Transparent in Gimp

Here, we will describe three way to make area transparent in GIMP. You just follow the steps described bellow with following points:

 

  1. Use ‘Rectangle Select Tool’ To Make Selected Area Transparent
  2. Use ‘Free Select Tool’To Make Selected Area Transparent
  3. Use ‘Eraser Tool’To Make Selected Area Transparent

So, First Open your Image in Gimp. Then proceed with following way:

(1). Use ‘Rectangle Select Tool’ To Make Selected Area Transparent :

If you want to use ‘Rectangle Select Tool’, you have to follow the steps in GIMP.

 1.
 Right click on Image in Gimp.

 2.
 A drop down menu will appear, Go to ‘Layer’ option.

 3.
 In ‘Layer’, go to ‘Transparency’ option.

 4.
 Then Select ‘Add Alpha Channel’.

Let's see the instruction given in following figure.

 
Add Alpha Chanel In Gimp


 5.
 After that select ‘Rectangle Select Tool’ from ‘Tools’.

 6.
 Now, select area where you want to make selection transparent.

 7.
 And Press ‘Delete’ from Keyboard.

Select Tool For Selection Transparent in Gimp



Now, let's proceed to second process.

 

(2). Use ‘Free Select Tool’ To Make Selected Area Transparent :

Like above given Points for ‘Add Alpha Channel’. You have to do same in this process. 

 (Right Click) Image >> “Layer” >> “Transparency” >> “Add Alpha Channel” 

 1.
 After this Process, you have to go to ‘Tools’ window and select ‘Free Select Tool’.

 2.
 Then point on area which you want to make transparent.

 3.
 And then join start and end point of ‘Free Select Tool’ then Press ‘Delete’ Button from Keyboard.




This will make desire area transparent.

 

(3). Use ‘Eraser Tool’ To Make Selected Area Transparent :

Same way you have to select ‘Add Alpha Channel’ like first process.

(Right Click) Image >> “Layer” >> “Transparency” >> “Add Alpha Channel” 

 1.
 After that Select ‘Eraser Tool’.

 2.
 Then go to ‘Eraser ToolProperties and Increase or decrease EraserSize’ according to area selection.

 3.
 Then click on area of Image.

This will make eraser area transparent.
Eraser Tool For Selection Transparent in Gimp


Note: If you want to increase or decrease transparency level, you have to simply go to ‘Eraser’ tool’s Properties window and Increase or decrease ‘Opacity’ from 0 to 100%.

This is the simplest and easy way to manually select area and make it transparent. 

In Gimp, you will find many other tools that provide facility to transparent selected part in GIMP. So, this way you can make Image Selected Area transparent in GIMP with SKOTechLearn easy tips.

Add Itmes in ComboBox in Tkinter Python with Loop Example

Here, we will discuss and Learn about Tkinter Combobox in Python. Here we will learn how to Add Items in Combobox in Tkinter or Add Items in ComboBox in Tkinter through Loop in Python. So, we will proceed with step by step Process with following points.


  1. Manually Add Items in ComboBox Tkinter in python
  2. Add Items in ComboBox Tkinter in python through Loop

Now, lets Learn point wise given bellow.

 How To Get value From Textbox to Label in Tkinter in Python?

(1). Manually Add Items in ComboBox Tkinter in python :

If you want to add items in design time or manually then you have to write following code in Python. Tkinter provide ttk class to show combobox and its attributes. So, Manually add items process code in tkinter described in following way:
import tkinter as tk
from tkinter import *
from tkinter import ttk

MyrootDialog = tk.Tk(className="Add Items in Tkinter Combobox")
#Set Tkinter window Size
MyrootDialog.geometry("300x100")

mytkcombo = ttk.Combobox(MyrootDialog, values=['SKO', 'Tech', 'Learn'])
#Set Combobox Position in Python
mytkcombo.place(relx=0.5, rely=0.3, anchor='center')
mytkcombo['state'] = 'readonly'
#mycombo.pack()

MyrootDialog.mainloop()
When you run this code, this will show you following output.

Manually Show items in Combobox Tkinter
Items in Tkinter ComboBox in Python


So, In this way you can add items in ComboBox tkinter in Python through static way. Now let’s Learn about dynamic way at run time.


(2). Add Items in ComboBox Tkinter in python through Loop :

Now, if You want to add itmes in tkinter combobox at runtime with loop or loop to add items in tkinter combobox in python, you have to implement some code in python like bellow: 

Example 1:
import tkinter as tk
from tkinter import *
from tkinter import ttk

MyrootDialog = tk.Tk(className="Add Items in Tkinter Combobox")
#Set Tkinter window Size
MyrootDialog.geometry("300x100")

mytkcombo = ttk.Combobox(MyrootDialog)
# For Loop
for x in range(5):
   # Add itmes in combobox through Loop code
   mytkcombo['values']= tuple(list(mytkcombo['values']) + [str(x)])
mytkcombo.place(relx=0.5, rely=0.3, anchor='center')

MyrootDialog.mainloop()

This is the dynamic way to show items in combobox at run time through loop. This will show following output:
Loop Items in ComboBox Tkinter
Loop Items in ComboBox



Show Month in Combobox Tkinter through Loop

Example 2:

Now, lets See another Example to showing month name in ComboBox through Loop . In this example we use array list to add items in ComboBox Python.
import tkinter as tk
from tkinter import *
from tkinter import ttk
import calendar

MyrootDialog = tk.Tk(className="Add Items in Tkinter Combobox")
#Set Tkinter window Size
MyrootDialog.geometry("300x100")

mytkcombo = ttk.Combobox(MyrootDialog)
# Define Array List
strList=['']
for mnt in range(1, 13):
   #Add Month Name through Loop
   strList.append(calendar.month_name[mnt])
#Add Items in Tkinter Combobox through Array
mytkcombo['values'] = strList
mytkcombo.place(relx=0.5, rely=0.3, anchor='center')

MyrootDialog.mainloop()




After running this code you will see the output like following way:

Show Month In ComboBox in Tkinter
Show Month Name in Tkinter ComboBox in Python


So, these are the three way to show or Add Items in Combobox in tkinter in Python, you can choose anyone according to your application or software requirement.

Steps to Change Dark Theme to Light Theme in Visual Studio Code

If you like Light Theme in Code Editor in Visual Studio Code then here SKOTechLearn will describe the steps to Change Dark Theme to Light Them in Visual Studio Code. And Here we will also describe the steps to Customize Color or Theme in Visual Studio Code.

Dark theme to Light Theme in Visual Studio Code

By default VS Code contain Dark theme. You know that Visual Studio is highly customized code editor compare to all other code editor. And you can find many feature to change Look and Feel in Visual Studio Code.

Change visual studio code background color

Now, we can choose any one process for Change Code Editor Color in Visual Studio Code:

  1. Change Theme of Visual Studio Code through Shortcut Key
  2. Change Theme of Visual Studio Code through Settings
  3. Change Color Theme of Visual Studio Code through Code


(1). Change Theme of Visual Studio Code through Shortcut Key:

When you open VSCode, and want to change theme, then simply you have to press two different shortcut Key one by one same time.

Press First Shortcut Key:  CTRL + K 
After that Press second Shortcut Key:  CTRL + T 

Now, you will see a drop down Option Box “Select Color Theme (Up/Down Keys To Preview)” will appear containing list of existing theme like bellow:

Change Theme in Visual Studio Code through Shortcut Key

This Option Box contain two types of Theme Category first is “light themes” and second is “dark themes”. If you want to change VSCode in light theme, then choose first category.


(2). Change Color Theme of Visual Studio Code through Settings:

If you want to proceed for color change through VSCode settings, then you have to follow the steps:

1.
First Go to “File” menu.

2.
Find “Preferences” and select it.

3.
And then select “Color Theme[Ctrl+K Ctrl+T]” option from it.

4.
Now, a drop down list will appear containing themes options. Choose anyone which you like.

Settings to change Theme color in Visual Studio

As you can see, in this way you can change Dark Theme to Light Theme in VSCode.

(3). Change Color Theme of Visual Studio Code through Code:

This is very interesting process to Change Look and Feel Of Visual Studio Code. In this Process you can change every Part of VSCode Tool's color according to your desire. You have to Simply proceed with following way:

1.
Same as above given steps, you have to first go to “File” menu then “Preferences” then “Settings”.

2.
You will find “Settings” Tab will appear. Go to Search Bar and search for “.json”.

3.
You will get “Edit in Settings.json” option. Just click on it.

4.
Now “Settings.json” file will display. Add color code like bellow:

{
     "workbench.colorCustomizations": {
     //For Code editor Color Change
     "editor.background": "#edeafa",
     "editor.foreground": "#4b4548",

     //For Sidebar Color Change
     "sideBar.background": "#fddcaa",
     "sideBar.foreground": "#612144", 

     //Change Activity Bar Color
     "activityBar.background": "#7f61a7",
     "activityBar.foreground": "#c5ff3e",
     "activityBar.inactiveForeground": "#6dc58f"
     }
} 

After writing this code, save it and see what happen:
Customise Theme Color in Visual Studio Code

As you can see you can manually create theme in VSCode.

So, this way you can easily Customize Theme Color of Visual Studio Code. And also set Light theme in VSCode.

Steps to Get Entry Or Text Value in Label in Python Tkinter

In python using Tkinter, there are two types of Input Box first is Tkinter Entry Box and Second is Tkinter Text. And if you want to get String or Get Value from Entry in Tkinter or Get Tkinter Text Value in Python then here you will find detailed process to consider how to use it in your Project.


How to use Tkinter Label in Python with features


Important Note: We Find that Text widget can not work in Tab Order. You have to write more code effort to perform Tab order in Text in Tkinter. But if you use Entry widget in python. There will no problem in tab order.

Now Let’s Learn How to Get Value from Entry in Python Tkinter or Get Value from Text with following way:

  1. Get Entry Value in Label in Python Tkinter
  2. Get Text Value in Label in Python Tkinter

So, Let’s Start.

(1). Get Entry Value in Label in Python Tkinter :

As you know that for perform any action in Python you have to define Function. So for getting value you have to define function as bellow and Get Entry Value.

Python Code:
from tkinter import *

MyRootDialog=Tk()
#Set Tkinter Size And Location
MyRootDialog.geometry("200x150+100+100")

#Set Tkinter Title
MyRootDialog.title("Get Input Value in Label")

# Define Function for get Value
def Get_MyInputValue():
     getresult = MyEntryBox.get()
     myTKlabel['text'] = getresult

# Create Tkinter Entry Widget
MyEntryBox = Entry(MyRootDialog, width=20)
MyEntryBox.place(x=5, y=6)

myTKlabel = Label(MyRootDialog, borderwidth=1, relief="ridge", height=3, width=25)
myTKlabel.place(x=4, y=42)

#command will call the defined function
MyTkButton = Button(MyRootDialog, height=1, width=10, text="Get text", command= Get_MyInputValue)
MyTkButton.place(x=4, y=112)

mainloop()

One more thing here you can use get value in Label through following two way:

myTKlabel['text'] = getresult

or

myTKlabel.config(text = getresult)

You can use it according to your desire. Both will present same result.

Output:
Get Entry value in Tkinter in Python

You can also Set Tkinter window in Center Location.

(2). Get Text Value in Label in Python Tkinter :

Now if you use Tkinter Text widget in python then you have to write following code to get Tkinter text in python.

Note: Get Value from Tkinter Entry Widget code: MyEntryBox.get()
And for get Value from Tkinter Text Widget code: MyTktextBox.get("1.0", 'end-1c')

In Text Widget you have to pass Index inside Get() function:

Code:
from tkinter import *

MyRootDialog=Tk()
#Set Tkinter Size And Location
MyRootDialog.geometry("200x150+100+100")

#Set Tkinter Title
MyRootDialog.title("Get Input Value in Label")

# Define Function for get Text Value
def Get_TKTextValue():
      myTxtresult = MyTktextBox.get("1.0", 'end-1c')
      myTKlabel.config(text = myTxtresult)

# Create Tkinter Text Widget
MyTktextBox=Text(MyRootDialog, height=1, width=20)
MyTktextBox.place(x=5, y=6)


myTKlabel = Label(MyRootDialog, borderwidth=1, relief="ridge", height=2, width=25)
myTKlabel.place(x=4, y=42)

#command will call the defined function
MyButton = Button(MyRootDialog, height=1, width=10, text="Get text", command= Get_TKTextValue)
MyButton.place(x=4, y=92)

mainloop()

Now, when you run you code, this will present following output.


Different types of Multi Line String process in Python


Output:
Get Text Value in Python

So, these above given code process is use to Get Tkinter Text Value in Label or Get Entry Value in Python.

String in Python with Single, Multi-Line, Concatenate in Python

First of all you have to understand about String in Python. Basically a String is a collection of characters which is used to define a word or sentence or paragraph with single or multiple lines. And here we also describe some basic Format of String or Integer Concatenation in Python.

Use String in Python

In Python, when we define a string, it will be define either Single (‘ ’) Quote or Double Quote ( “ ”).
For simple example you can use print() function for display simple word or sentence as form of string as given bellow:

print( "SKOTechLearn" )
print( 'SKOTechLearn' )
Output:
>>>
SKOTechLearn
SKOTechLearn
>>>


So, let’s see the types and use of String with following way:

  1. Single Line String using Variable 
  2. Use String to Passing value in Function 
  3. Multi-Line Sting using Variable 
  4. Concatenate Strings in Python 
  5. Concatenate integer or number with String


(1). Single Line String in Python using Variable :

Suppose you want to store your word or sentence and show during process then we simply assign a Variable.

mystrng = "Hello SKOTechLearn"
print(mystrng)
Output:
>>>
Hello SKOTechLearn
>>>


(2). Use String to Passing value in Function in Python:

This is very important point which is used in every programming process. Here you can use string for passing in other function or references.

You can simply cover following points:

➤ Python pass function as argument with parameters
➤ How to pass string as parameter in python function?
➤ Python pass function name as argument
➤ Python call function from string with arguments

You have to simply learn following process:

Myfstr = "skotechlearn"
MyPFunc( Myfstr )

def MyPFunc ( Myfstr ):
    # upper() method is use to show Characters in Capital Letters
    skstr = Myfstr.upper()
    print (skstr)
Output:
>>>
SKOTECHLEARN
>>>

You can simply use this process with many ways according to your application requirement process.


(3). Multi-Line Sting in Python using Variable :

As you can understand how to store or show string in python, but when you want to store multiline sentence or paragraph on your application, what is the code process we apply?

You have to simply write word or sentence in start and end with Triple Quotes (""" """) or You can simply use “\n” between you sentence with following way:

Multi-line String using Triple Quotes (""" """) :

MyMultilineStr = """This is Triple Quote multiline Sentence
Using Python Code
With Simple output"""
print (MyMultilineStr)
Output:
>>>
This is Triple Quote multiline Sentence
Using Python Code
With Simple output
>>>


Multi-line using “\n” :

MyNextLineStr = "This is multiline Sentence \n Python Code \n With Next Line Process "
print (MyNextLineStr)
Output:
>>>
This is multiline Sentence
Python Code
With Next Line Process
>>>


(4). Concatenate Strings in Python :

There are 4 ways for concatenating string in Python.

First Process:


You can simply use “+” Sign for concatenate word or sentence.

FstStr = "SKO"
SecStr = "Tech"
ThirdStr = "Learn"

FinalStr = FstStr  + " " + SecStr + " " + ThirdStr
print (FinalStr)
Output:
>>>
SKO Tech Learn
>>>


Second Process:


You can simply use “{}{}{}”.format(StrVar1, StrVar2, StrVar3) function.

Tips1: "{}{}{}".format(StrVar1, StrVar2, StrVar3): if you don’t need space between string.
Tips2: "{} {} {}".format(StrVar1, StrVar2, StrVar3) : if you need to add space between string.

Note: Input Number of “{}” Curly Brace according to the number of string variable.

PStr1= "SKO"
PStr2 = "Tech"
PStr3 = "Learn"
PStr4 = "Tips"

#concatenate String without space
print("{}{}{}{}".format(PStr1, PStr2, PStr3, PStr4)) 

# concatenate String with space
print("{} {} {} {}".format(PStr1, PStr2, PStr3, PStr4))
Output:
>>>
SKOTechLearnTips
SKO Tech Learn Tips
>>>


Third Process:


In this process you can use "% s % s % s" % (StrVr1, StrVr2, StrVr3). Here you can add number of “% s” according to number of string value or variable.

"% s % s % s" : if you want to add space during concatenating variable. This will show sentence with space.
"% s% s% s" : This will show Concatenate variable without space.

For Example:
myVr1 = "This"
myVr2 = "is"
myVr3 = "Concatenate"
myVr4 = "Code"
#Sentance without space
print("%s%s%s%s" % (myVr1, myVr2, myVr3, myVr4)) 

# Add space between word or sentence
print("%s %s %s %s" % (myVr1, myVr2, myVr3, myVr4))
Output:
>>>
ThisisConcatenateCode
This is Concatenate Code
>>>


Forth Process:


Use .join for concatenate in python. For Simply you have to follow following syntax:

Concatenate Without Space: "".join([SkVr1, SkVr2, SkVr3])
Concatenate With Space: "".join([SkVr1, SkVr2, SkVr3])

For Example:
SkVr1 = "Learn"
SkVr2 = "Concatenate"
SkVr3 = "process"
# Concatenate process without space
print("".join([SkVr1, SkVr2, SkVr3])) 
# Concatenate process with space 
print(" ".join([SkVr1, SkVr2, SkVr3]))
Output:
>>>
LearnConcatenateprocess
Learn Concatenate process
>>>


(5). Concatenate integer or number in Python with String:

When you will try to concatenate integer in Python with alphabet or sentence, you will get the following error with normal process like bellow:
print(1 + "This is Alphabet")
>>>
Traceback (most recent call last):
 print(1+"This is Alphabet")
TypeError: unsupported operand type(s) for +: 'int' and 'str
>>> 

As you can see the above error will display. So, we try following way to solve this problem. There are four process for Concatenating Integer with String:

Process 1:
 Simply input number inside Double Quote(“ ”):

print("2"+ ". This is Alphabet")
Output:
>>>
2. This is Alphabet
>>>


Process 2:
 Using str() for converting Integer :

mynum = 2
combstr = "This is Alphabet"
print(str(mynum) + "=  " + combstr)
Output:
>>>
2= This is Alphabet
>>>


Process 3:
 Using .format method for concatenate of integer :

mynum = 2
combstr = "This is Alphabet"
print "Point No. {} is - {} for concatenate with Integer".format(mynum, combstr)
Output:
>>>
Point No. 2 is - This is Alphabet for concatenate with Integer
>>>


Process 4:
 Using “% s” for Concatenate integer :

mynum = 2
combstr = "This is Alphabet"
print("No. % s % s" % (mynum, combstr))
Output:
>>>
No. 2 This is Alphabet
>>>


So Friends, these are the process for Using String in Python, easily show Multi-line String in python, Passing String in function in Python, Concatenate String in Python, Concatenate Integer in Python.

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.