JComboBox in Java Swing

JComboBox is Drop down box with multiple values in Java Swing.

It is defined as javax.swing.JComboBox<E>.

Here E is type of element of JComboBox.

JComboBox Constructors

Sr NoConstructors and Description
1JComboBox()
Create a JComboBox with default default data model
2JComboBox(ComboBoxModel aModel)
Create a JComboBox with ComboBoxModel aModel
3JComboBox(E[] items)
Create a JComboBox with specified array
4JComboBox(Vector items)
Create a JComboBox with specified Vector

Methods of JComboBox

Sr NoMethods and Description
1void addItem(E item)
Add an Item to item list
2Object getSelectedItem()
Returns the selected Item
3void removeItem(Object anObject)
Remove an Item from Item list
4void removeItem(Object anObject)
Remove an Item from Item list
5void addActionListener(ActionListener l)
Add action listener
6getItemAt(int index)
Get Item at specified index

JComboBox add and show items

  1. Create a frame with any size.
  2. Create Reference for Container, JLables and JComboBox.
  3. get content page and set its layout null.
  4. Create JLabels and JComboBox objects.
  5. Add elements to JComboBox using addItem() and by using String[]
  6. Set bounds for JLables and JComboBox
  7. Add all Components to container.

Examples of JComboBox

JComboBox add and show items
Fig: JComboBox add and show items

JComboBox actionlistener get selected item and get selected index

jComboBox1.addActionListener(this); is used to add action listener to jComboBox1.

You have to override actionPerformed(ActionEvent e) to handle combo box event.

combo.getSelectedItem() displays the selected item

combo.getSelectedIndex() is used to display selected item index.

JComboBox indexing starts from 0.

jcombobox get selected item example

JComboBox actionlistener get selected item and get selected index
Fig: JComboBox actionlistener get selected item and get selected index

JComboBox set selected item and set selected index

  1. create JComboBox
  2. To select specific item based on name use comboBoxRef.setSelectedItem("Item Name");
  3. To select specific item based on index use comboBoxRef.setSelectedIndex(3);
  4. Index number must be between 0 to itemSize-1
JComboBox set selected item and set selected index
Fig JComboBox set selected item and set selected index

jcombobox get selected item using ItemListener

JComboBox Example ItemListener

  1. Create JComboBox
  2. Add ItemListner to this
  3. override itemStateChanged(ItemEvent e) method
  4. get Item Event Source from combobox
  5. select item and index by using getSelectedItem() and getSelectedIndex()
JComboBox ItemListener Example
Fig: JComboBox ItemListener Example

JComboBox Show Image in combo box using ListCellRenderer and ItemListner

JComboBox Show Image in combo box using ListCellRenderer and ItemListner
Fig: Show image in JComboBox

How to use combobox in java netbeans

We have developed many examples in netbeans.

It is a very simple copy and above example and paste in netbeans/ eclipse then run.

Run a swing program is same as simple java program

How to use combobox in java netbeans
Fig: How to use combobox in java netbeans
JCombobox Example in netbeans
Fig: JCombobox Example in netbeans

Read More

  1. JLabel in Java Swing
  2. JComboBox in Java Swing
  3. JTable in Java Swing
  4. JTable Pagination in Java JDBC
  5. Registration Form in Java Swing
  6. Login form in Java Swing
  7. Simple Calculator in Java Applet
  8. Applet Life Cycle in Java

Image Reference

https://freeicons.io/indian-republic-day-icons/india-gate-indian%20republic%20day-icon-7661#

Taj Mahal icon icon by Icons8

https://thenounproject.com/term/victoria-memorial/2165511/

Registration Form in Java Swing with MySql Database

Registration Form in Java Swing is covered in this Post.

To develop this project we used NetBeans IDE.

Steps to develop Registration Form in Java Swing is as below

  1. Create User Interface (UI) Using JFrame
  2. Collect all data in Model sent from UI
  3. Validate and Process Received data
  4. Saving data to MySql Database
Project Explorer for Registration Form

Here we have added three external Jar files

  1. mysql-connector-jar-5.1.14-bin.jar – To connect Java program with MySql Database
  2. jBCrypt-0.4.jar – To encrypt password
  3. jdatepicker-1.3.4.jar– To include date picker in JFrame

To Develop Registration form we are considering example of Student.

We will create basic interface to collect student data in JFrame.

Our Final UI JFrame will as below

Registration Form in Java Swing

1 Create User Interface using JFrame

A. Create a basic structure for frame

In main method we created RegisterFrame class object.

set title, visibility, specified frame coordinated and height and width with bounds and other properties.

Created constructor RegisterFrame() to create and initialize frame components (JLable, JTextBox, JButton, …) .

Method setBounds() is used to set location, width and height of components.

addComponents() is used to add components to Container.

Output of above code is as below

JFrame Basic Size
Fig: JFrame height and width

This is basic layout for our Registration form.

B. Adding Components to JFrame

Components JLabel, JTextField, JRadioButton, JPasswordField, JCombobox, JButton etc are used here.

To select Date from Date Picker additional Jar jdatepicker-1.3.4.jar is added to project.

B Add the basic component in JFrame

  1. Components are Declare as Instance variable
  2. Objects of components are created inside Default Constructor
  3. setBounds() is used to set position ,width and height of components.
  4. addComponents() is used to add components in Container.
  5. addActionListener() is used to add action listener on registerButton.
  6. actionPerformed() is over ridden to handle event

Last two steps are handled later on.

After adding basic components it will create Frame as below

Adding Components in JFrame
Fig: Adding Basic Components in JFrame

C Add JDatePicker in JFrame

First check jdatepicker-1.3.4.jar is added in project

Imports for JDatePicker

Adding JDatePicker in constructor

complete code after adding JDatePicker

DateLabelFormatter class is used to show date selector.

JDatePicker Example
Fig: JDatePicker Addition in JFrame

It will complete our UI

2 Collect all data in Model sent from UI

To collect data Register button is clicked and all data from text box and other input fields are collected and set to student Model.

Lets First See student model Students.java

This class contains basic fields of student, constructors, getter and setter methods and to string method.

Adding following code to RegisterFrame.java

  1. ActionLister is added for registerButton
  2. actionPerformed() is overridden to handle click event on register button

Based on genderFemale and genderMale is selected gender variable.is set based on that.

Similar way storing programName, branchName and semesterName from respective dropdown list.

To get value from JDatePicker datePicker.getJFormattedTextField().getText() is used.

It returns value in string to convert string date to java.sql.date Date.valueOf(dobString) is used.

3 Validate and Process Received data

Received data is stored in Student object.

We have already validated dob field.

Other fields are validated in Validation.java

  1. All fields are checked for Empty.
  2. Name length must be more than 4 and less than 20
  3. Validation for Mail id
  4. Mobile Number must be 10 digits long
  5. Password must be between 8 to 20 characters
  6. Password must contain One digit one upper case letter and special symbol
  7. RePassword and password must match

Creating object of validation and and checking for errors if error occurs then it is shown using showMessageDialog().

Processing Data

Processing data is done before and after validation

  1. Based on male and female JRadioButton we assigned male or female to gender variable.
  2. Get Dob from JDatePicker as string and then converted again to java.sql.Date.
  3. BCrypt is used to encrypt password and set to encPassword().

4 Saving data to MySql Database

Validated and processed data and stored in Student object.

To save data of student object first create student table as given below.

ConnectionFactory.java

This file is used to connect java with database and returns the connection object.

Database name :ebhor
Username: ebhor_user
Password: 21V6

RegisterDAO.java

registerStudent() takes a student object and save each field to database using java preparedStatement();

RegisterFrame.java

Receiving response from registerStudent().

Finally Saving data on student table

Student Registration Example
Fig: Registration Done
MySql student table perview
Fig: MySql student table perview

How to create a registration form in java swing

The above tutorial explains about to create a registration form in java swing.

How to create a registration form in java using netbeans

Follow the above steps to develop registration form

registration form in java source code download

Read More

  1. JLabel in Java Swing
  2. JComboBox in Java Swing
  3. JTable in Java Swing
  4. JTable Pagination in Java JDBC
  5. Login form in Java Swing
  6. Simple Calculator in Java Applet
  7. Applet Life Cycle in Java

JTable in Java Swing with Examples

JTable in Java is a swing component, that is used to show data in two dimensional Grid.

It is used to display and edit data in cell format in table

Constructors of JTable

Sr NoConstructor and Description
1JTable()
Construct a Default JTable with default values
2JTable​(int numRows, int numColumns)
Construct JTable with numRows and numColumns empty cells using DefaultTableModel
3JTable​(Object[][] rowData, Object[] columnNames)
Construct JTable with rowData and provide column names with columnNames
4JTable​(TableModel dm)
Construct a JTable with TableModel dm as a data model
5JTable​(TableModel dm, TableColumnModel cm)
Constuct JTable with TableModel dm and TableColumnModel cm
6JTable​(TableModel dm, TableColumnModel cm, ListSelectionModel sm)
Constuct JTable with TableModel dm and TableColumnModel cm and ListSelectionModel sm

Methods of JTable

Sr NoMethods and Description
1int getRowCount()
Returns Number of Rows in JTable
2int getRowHeight()
Returns Row Height of JTable
3JTableHeader getTableHeader()
Returns JTable Header
4Object getValueAt​(int row, int column)
Returns the cell value

All Constructors and method are available at official doc

JTable Java Example to Show Data

Without JScroll Pane we have to add Table Header in container.

container.setLayout(new BorderLayout());
container.add(table.getTableHeader(), BorderLayout.PAGE_START);
container.add(table, BorderLayout.CENTER);

These lines are used to add header and data.

JScrollPane JTable Example in Java Swing

Here we set container layout to null.

Added JScrollPane to JTable and set bound in JScrollPane.

Setting Column Width in JTable

table.getColumnModel().getColumn(index).setPreferredWidth(size);

is used to set column width.

column index start from zero.

Java JTable Example to find Number of Rows and Columns and Finding JTable Cell Value on Clicking on Cell

Table have method getRowCount() and getColumnCount() to find the number of rows and colums in table.

table.addMouseListener is used to get mouseClick event if mouse it clicked one time them we get table’s getSelectedRow() and getSelectedColumn() to get clicked row and columns.

getValueAt(row,column) is used to get value at cell.

JTable Cell Value on Click
Fig: JTable Cell Value on Clicking

How to Show Image in JTable Cell

Here we are getting table’s Column Model and setting .setCellRenderer is getDefaultRenderer and setting ImageIcon.class to column.

table.getColumnModel().getColumn(3).setCellRenderer(table.getDefaultRenderer(ImageIcon.class));

Show Image in JTable Cell
Fig: Show Image in JTable Cell

How to display data from database in jtable in java using DefaultTableModel

DefaultTableModel is used to create JTable. We are extracting data from database and assigning row to DefaultTableModel and printing it to Frame.

Example: how to display database values in jtable in java

Download mysql-connector-java-5.1.14-bin.jar or any latest jar to connect java with mysql

DefaultTableModel to get data From Database
Fig: DefaultTableModel to get data From Database

Editing JTable Cell and using CheckBox and JComboBox in JTable

To make out JTable editable we created MyTableModel that extends AbstractTableModel.

Here we have override methods and one of the method in

public boolean isCellEditable(int row, int col) {
return true;
}

making true in above method allows user to edit cell value.

To Show JComboBox in table cell TableColumn is used as below.

TableColumn tc = table.getColumnModel().getColumn(4);
tc.setCellEditor(new DefaultCellEditor(branchList));

Editing JTable Cell  CheckBox and JComboBox in JTable
Fig: Editing JTable Cell CheckBox and JComboBox in JTable

How to Change Row Color of JTable

How to Change Row Color of JTable
Fig: How to Change Row Color of JTable

How to change Column Color of JTable

in above example instead or row use column as below

How to change Column Color of JTable
Fig: How to change Column Color of JTable

How to Change Row Color of JTable on Row Select

Change Column Color of JTable on Row Select
Fig : Change Column Color of JTable on Row Select

How to Change Cell Color of JTable on hasFocus

Change Cell Color of JTable on hasFocus
Fig: Change Cell Color of JTable on hasFocus

How to Color Specific Cell Based on value in JTable

prepareRenderer is used to access specific cell in JTable as below

How to Color Specific Cell Based on value in JTable
Fig: How to Color Specific Cell Based on value in JTable

Read More

  1. JLabel in Java Swing
  2. JComboBox in Java Swing
  3. JTable in Java Swing
  4. JTable Pagination in Java JDBC
  5. Registration Form in Java Swing
  6. Login form in Java Swing
  7. Simple Calculator in Java Applet
  8. Applet Life Cycle in Java

Java program to add two numbers

java program to add two numbers is a very simple program.

It is required by learners How can we add two numbers.

We will start with simple addition and try to cover additional things here.

Java program to add two numbers

Steps to add two numbers

  1. Store two numbers in two variables
  2. Add both variables and store in another variable
  3. Print the result

Here we take a=5 and a=6 two variables

added a and b and stored in variable sum

printed the sum in consol.

Fig: Addition of two numbers in Notepad++
Fig: Compilation and run of Addition program

Addition of two numbers in java

Above we add two integer numbers.

Here lets take two decimal numbers in java we represent decimal number in float and double

Addition of two decimal numbers in java

The process is same only we changed data types.

Addition of two numbers in java

Here we are considering two numbers one is integer and another is double.

Here a is integer data type and b is double data type.

For addition a is automatically promoted to double data type by the compiler the addition is performed.

Whenever two or more variable of different data types take part in any operation then a lower data type is always converted to higher data type.

This automatic conversion is done by compiler and the process in known as widening.

Addition of short numbers in java

Here variable a and b both are short type.

While adding two short numbers it is converted to integer and the result is stored in integer data type.

Both byte and short data types are converted to an integer.

Sum of two numbers in java using method

In the above program sum() is a static method so we called it with Class name.

add1(), add2(), add3() and add4() are non static so we called by object of class.

Methods are with and without argument and with and without return type.

Write the definition of a method add, which receives two integer parameters and returns their sum.