Friday 28 February 2014

Eclipse Shortcuts

I am just adding few links that have very good information about Eclipse Shortcuts.


  1. DZone Eclipse Zone
  2. Vogella



Tuesday 25 February 2014

Java: Iterating through the Map

This example demonstrates different way of iterating or looping through a Map-HashMap. Folling topics are covered

  1. Iterating through the Map using iterator
  2. Iterating through the Map keys
  3. Iterating through the Map values
  4. Iterating using a for loop

public class MapIteration
{
public static void main(String[] args)
{
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "Jan");
map.put(2, "Feb");
map.put(3, "Mar");
map.put(4, "Apr");
map.put(5, "May");
map.put(6, "Jun");

Iterator<Entry<Integer, String>> iter = map.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry<Integer, String> mapEntry = (Map.Entry<Integer, String>) iter.next();
System.out.println("Key: " + mapEntry.getKey() + ", Value :" + mapEntry.getValue());
}

for (Map.Entry<Integer, String> entry : map.entrySet())
{
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}

Iterator keysIter = map.keySet().iterator();
while (keysIter.hasNext())
{
Integer key = (Integer) keysIter.next();
System.out.println("Key: " + key);
}

for (String value : map.values())
{
System.out.println("Value : " + value);
}
}
}

Monday 24 February 2014

Java: Deleting a record from MySQL databbase


  • Create a simple GUI using GridBagLayout
  • Get input from the user to delete the corresponding record
  • Delete a record from the database on pressing the button
We will delete a customer record from the database. User has to provide the customer account number in order to delete the customer. The program will contain a class for handling database transaction, one for creating the GUI and a driver program.

Here is the class that creates our GUI.

public class SimplePanel extends JFrame
{
JTextField accountNumber;

public SimplePanel()
{
setTitle("Delete record from Database");
accountNumber = new JTextField(10);
}

public void createAndDisplay()
{
JPanel panel = new JPanel(new GridBagLayout());

JPanel banner = new JPanel();
banner.add(new JLabel("Delete record from the database"), BorderLayout.CENTER);
banner.setBorder(BorderFactory.createLineBorder(Color.BLACK));

GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
panel.add(banner, c);

JLabel label = new JLabel("Customer Account Number");
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
panel.add(label, c);

c.gridx = 1;
c.gridy = 2;
c.gridwidth = 1;
panel.add(accountNumber, c);

JButton deleteBtn = new JButton("Delete");
deleteBtn.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
CustomerHandler handler = new CustomerHandler();
try
{
handler.deleteCustomer(Integer.valueOf(accountNumber.getText()));
}
catch (Exception e)
{
e.printStackTrace(); // handle the exception in a better way. this is just an example
}
}
});
c.gridx = 0;
c.gridy = 3;
panel.add(deleteBtn, c);

this.getContentPane().add(panel);
pack();
setVisible(true);
}
}

Here is the output window from the above program

For the DBConnection class have a look at this post. And the handler that will actually delete the record from the database

public class CustomerHandler
{
public void deleteCustomer(int customerAccouontNumer) throws Exception
{
DBConnection db = new DBConnection();
Connection conn = db.getConnection();
Statement st = null;
              // First check if the conn is null then throw an exception or handle in some other way
try
{
st = conn.createStatement();
st.execute("Delete from Customer where account_number = " + customerAccouontNumer + ";");
}
catch (Exception e1)
{
throw new Exception("Unable to delete customer!" + e1.getMessage());
}
finally
{
// close the connection and the statement
}
}

And the driver program

public class Driver
{
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
SimplePanel p = new SimplePanel();
p.createAndDisplay();
}
});
}
}

Remember to do the imports. 

Java: JOptionPane Example

This example covers following topics:

  • How we can use JOptionPane to display a message dialog
  • How to get user input through JOptionPane
  • How to use a custom JPanel on the JOptionPane
  • How to work on the user input data
Here goes the program


public class JOptionPaneExample
{
private double price;
private JTextField priceField;
private JLabel priceLabel;

public JOptionPaneExample()
{
priceField = new JTextField(10);
}

public void createAndDisplayGUI()
{
int selection = JOptionPane.showConfirmDialog(null, getPanel(), "Price Form : ", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

if (selection == JOptionPane.OK_OPTION) // if the use entered data and pressed OK
{
price = Double.valueOf(priceField.getText());

JOptionPane.showMessageDialog(null, "Price is : " + Double.toString(price), "Price : ", JOptionPane.PLAIN_MESSAGE);
}
else if (selection == JOptionPane.CANCEL_OPTION) // if the user pressed cancel button
{
// Do something here.
}
}

private JPanel getPanel()
{
JPanel basePanel = new JPanel();
basePanel.setOpaque(true);
basePanel.setBackground(Color.BLUE.darker());

JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(3, 2, 5, 5));
centerPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
centerPanel.setOpaque(true);
centerPanel.setBackground(Color.WHITE);

priceLabel = new JLabel("Enter Price : ");

centerPanel.add(priceLabel);
centerPanel.add(priceField);
basePanel.add(centerPanel);

return basePanel;
}
}


Don't forget to import and write the driver program yourself. Here's the output from the program



Sunday 23 February 2014

Java: Putting an image in ToolTipText

Here is how an image can be added to a ToolTipText

public class ToolTipBasic
{
public static void main(String args[])
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
createAndShowGui();
}
});
}

private static void createAndShowGui()
{
JFrame frame = new JFrame("ToolTipText Tutorial");
Container contentPane = frame.getContentPane();
JButton b = new JButton("Button");
setToolTipImageAndBackground("This is tool tip text", b);
contentPane.add(b, BorderLayout.NORTH);
frame.setSize(300, 200);
frame.setVisible(true);
}

private static void setToolTipImageAndBackground(String toolTipText, JButton b)
{
Color backgroundColor = new Color(255, 255, 255);
UIManager.put("ToolTip.background", backgroundColor);
b.setToolTipText("<html><img src=\"" + ToolTipBasic.class.getResource("/images/Key.gif") + "\">" + toolTipText);
}

The program adds a WHITE background color to the tooltip and puts an image to the tool tip.
Here is the output:


Java: ToolTipText

This post is a tutorial for ToolTipText. Following topics are covered

  • How to put a ToolTipText to a JButton
  • How to change the backgroud color of the ToolTipText

Here is the program that demonstrates the behavior

public class ToolTipBasic
{
public static void main(String args[])
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
createAndShowGui();
}
});
}

private static void createAndShowGui()
{
JFrame frame = new JFrame("ToolTipText Tutorial");
Container contentPane = frame.getContentPane();
JButton b = new JButton("Button");
setToolTipTextBackground("This is tool tip text", b);
contentPane.add(b, BorderLayout.NORTH);
frame.setSize(300, 200);
frame.setVisible(true);
}

private static void setToolTipTextBackground(String toolTipText, JButton b)
{
Color backgroundColor = new Color(255, 255, 255);
// Set tooltiptext background color using created Color
UIManager.put("ToolTip.background", backgroundColor);
b.setToolTipText(toolTipText);
}
}

I have removed the imports to make the program look shorter. And here is the output from the program:


Friday 21 February 2014

Java: Display year in a JComboBox

A short example program will compute next 10 years and will display it in a JComboBox

public class JComboBoxExample
{
private JPanel getPanel()
{
JPanel p = new JPanel(new FlowLayout());
JComboBox<String> yearsCbx = new JComboBox<String>();
String[] years = getNextTenYears();
yearsCbx.setModel(new javax.swing.DefaultComboBoxModel<String>(years));

JLabel yearLbl = new JLabel("Select Year");
p.add(yearLbl);
p.add(yearsCbx);

return p;
}

public void createAndShowGUI()
{
JFrame frame = new JFrame("JComoBox Example");
frame.setMinimumSize(new Dimension(500, 200));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.add(getPanel());
// Display the window.
frame.pack();
frame.setVisible(true);
}

private String[] getNextTenYears()
{
String[] years = new String[10];
Calendar cal = Calendar.getInstance();
int thisYear = cal.get(Calendar.YEAR);
for (int i = 0; i < years.length; i++)
years[i] = Integer.toString(thisYear + i);

return years;
}
}

And the Driver program

public class Driver
{
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JComboBoxExample cbx = new JComboBoxExample();
cbx.createAndShowGUI();
}
});
}
}


And here is the output from the program


Java: Search a record from a database table

In this example we will search a customer's record from a database table named 'CUSTOMER'. The database used is MySQL and the code is written in Eclipse IDE.

To search the data from the table a database connection is needed. To get the connection to the database follow the instructions and use the code in this post -> Connecting Java and MySQL in Eclipse

Once the DBConnection  class is there we will make a CustomerHandler class that will query the database and return the searched record.

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

public class CustomerHandler
{
public CustomerHandler()
{
}
public Customer searchCustomer(int customerAccountNumber) throws Exception
{
Customer c = null;
DBConnection db = new DBConnection();
Connection conn = db.getConnection();
PreparedStatement st = null;

if (conn == null)
{
throw new Exception("Unable to connect to the database. conection = null!");
}
try
{
st = conn.prepareStatement("Select * from Customer where account_number = ?");
st.setInt(1, customerAccountNumber);
ResultSet rs = st.executeQuery();

if (rs.next())
{
c = new Customer();
c.setAccountNumber(rs.getInt("account_number"));
c.setDate(rs.getDate("date"));
                                c.setName(rs.getString("name"));
}
catch (Exception e1)
{
Logger.getGlobal().severe("Unable to retrieve customer data from the database: " + e1.getMessage());
System.out.println("SQLException: " + e1.getMessage());
e1.printStackTrace();
throw new Exception("Unable to retrieve customer data from the database!" + e1.getMessage());
}
finally
{
try
{
if (conn != null)
{
conn.close();
}
if (st != null)
{
st.close();
}
}
catch (SQLException e1)
{
Logger.getGlobal().severe("Error occured while closing the connection or statement: " + e1.getMessage());
System.out.println("SQLException: " + e1.getMessage());
e1.printStackTrace();
throw new SQLException("Error occured while closing the connection or statement. " + e1.getMessage());
}
}
return c;

}
}

To check the working of our class we will write a driver class 

public class Driver
{
public static void main(String[] args)
{
CustomerHandler custHandler = new CustomerHandler();
int customerAccountNumber = 1;
try
{
custHandler.searchCustomer(customerAccountNumber);
}
catch (Exception e)
{
e.printStackTrace();
}
        }
}


Finally the Customer class to save the results.

import java.util.Date;

public class Customer
{
private int accountNumber;
private Date date;
private String customerName;

public Customer()
{
}

public int getAccountNumber()
{
return accountNumber;
}

public void setAccountNumber(int accountNumber)
{
this.accountNumber = accountNumber;
}

public Date getDate()
{
return date;
}

public void setDate(Date date)
{
this.date = date;
}

public String getCustomerName()
{
return customerName;
}

public void setCustomerName(String customerName)
{
this.customerName = customerName;
}
}

Sunday 16 February 2014

Java: JTabbedPane example with close button

This example demonstrates how a close button can be placed on a JTabbedPane. We will write a class JTabbedPaneWIthCloseButton. This class will generate a window with 4 tabs each with a close button and a custom title. If the button is pressed the corresponding tab will be closed.

The class adds a panel to the JTabbedPane and then adds a customer title which is also a JPanel. The title panel consists of a button and a title label.

public class JTabbedPaneWithCloseButton
{
private static JPanel getTitlePanel(final JTabbedPane tabbedPane, final JPanel panel, String title)
{
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
titlePanel.setOpaque(false);
JLabel titleLbl = new JLabel(title);
titleLbl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
titlePanel.add(titleLbl);
JButton closeButton = new JButton("x");

closeButton.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
tabbedPane.remove(panel);
}
});
titlePanel.add(closeButton);

return titlePanel;
}

/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
public static void createAndShowGUI()
{
JFrame frame = new JFrame("Tabs");
frame.setMinimumSize(new Dimension(500, 500));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane();

JPanel panel = new JPanel();
panel.setOpaque(false);
tabbedPane.add(panel);
tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(panel), getTitlePanel(tabbedPane, panel, "Tab1"));

JPanel panel1 = new JPanel();
panel1.setOpaque(false);
tabbedPane.add(panel1);
tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(panel1), getTitlePanel(tabbedPane, panel1, "Tab2"));

JPanel panel2 = new JPanel();
panel2.setOpaque(false);
tabbedPane.add(panel2);
tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(panel2), getTitlePanel(tabbedPane, panel2, "Tab3"));

JPanel panel3 = new JPanel();
panel3.setOpaque(false);
tabbedPane.add(panel3);
tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(panel3), getTitlePanel(tabbedPane, panel3, "Tab4"));

frame.add(tabbedPane);

// Display the window.
frame.pack();
frame.setVisible(true);
}

}

I have erased the imports in order to make it shorter. Now we need a driver class.

public class Driver
{
public static void main(String[] args)
{
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
            JTabbedPaneWithCloseButton.createAndShowGUI();
            }
        });
}
}

The output from the program looks like this:

Saturday 15 February 2014

Java: JTable example with TableModel

This article describes about the JTable without using the Table model. In order to use a Table Model we will first write a class for a table model. The table will display the data from a database table named "customer". Customer table has three columns {account_number, date, name}.

import java.util.Vector;
import javax.swing.table.AbstractTableModel;

public class CustomerTableModel extends AbstractTableModel
{
private static final long serialVersionUID = -7174062695601475724L;
public static final int ACCOUNT_NUMBER = 0;
public static final int DATE = 1;
public static final int NAME = 2;
private String[] columnNames;
private Vector<Customer> data;

public CustomerTableModel(Vector<Customer> customerVector, String[] columns)
{
columnNames = columns;
data = new Vector<Customer>(customerVector);
}

public String getColumnName(int column)
{
return columnNames[column];
}

@Override
public int getColumnCount()
{
return columnNames.length;
}

@Override
public int getRowCount()
{
return data.size();
}

@Override
public Object getValueAt(int row, int column)
{
Customer record = (Customer) data.get(row);
switch (column)
{
case ACCOUNT_NUMBER:
return record.getAccountNumber();
case DATE:
return record.getDate();
case NAME:
return record.getCustomerName();
default:
return new Object();
}
}

}

Above class extends AbstractTableModel. This table model will be used by a JTable.

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

@SuppressWarnings("serial")
public class CustomJTable extends JFrame
{
public CustomJTable(CustomerTableModel model)
{
super("JTable Example");
JPanel tablePanel = new JPanel(new BorderLayout());
JTable table = new JTable();
table.setModel(model);
tablePanel.add(new JScrollPane(table));
add(tablePanel);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
pack();
}
}

Now we will write a handler  class which will retrieve data from the database table. For the handler class check this post where we retrieve data from MySQL table 

Now we will write a driver class that will run the program and display our output.

import java.util.Vector;

public class Driver
{
public static void main(String[] args)
{
CustomerHandler custHandler = new CustomerHandler();
java.util.ArrayList<Customer> customerList = custHandler.getAllCustomers();

if (customerList == null || customerList.isEmpty())
{
customerList = new java.util.ArrayList<Customer>();
}
String[] columnNames =
{ "accountNumber", "date", "customerName", "customerAddress", "advance", "nicNumber", "telNumber", "connectionType", "connectionFee" };

CustomerTableModel tableModel = new CustomerTableModel(new Vector<Customer>(customerList), columnNames);
CustomJTable table = new CustomJTable(tableModel);
}
}

Notice that the Driver class uses CustomerHandler and Customer class which are taken from this post.
It is inappropriate in a way to display the table from the same class but in order to make  it shorted we can do it. A new class can be added which generates the GUI for the JTable and driver can call it.

Here is the output from our program.

The output shows more columns then the ones in the Table model. It is because I have removed many columns from the class to make it shorter. I hope this is helpful. If not then let me know what is missing and I will try to add it.

Java: Retrieving data from MySQL database table

Example demonstrates how we can retrieve data from a MySQL table in Java. The table used in this example is named "Customer" and contains customer data.

We will write a Customer class which will contain the data retrieved from the database.

public class Customer
{
private int accountNumber;

private String name;

public Customer(int acn, String name)
{
accountNumber = acn;
this.name = name;
}

public int getACN()
{
return accountNumber;
}

public String getName()
{
return name;
}
}


Now we will write a CustomerHandler class which will retrieve the data from the database. 

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

public class CustomerHandler
{
public CustomerHandler()
{
}

public ArrayList<Customer> getAllCustomers()
{
ArrayList<Customer> customerList = null;

DBConnection db = new DBConnection();
Connection conn = db.getConnection();
try
{
Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery("SELECT * FROM customer");
if (rs != null)
{
customerList = new ArrayList<Customer>();
while (rs.next())
{
int acNumber = rs.getInt(1);
String name = rs.getString(2);
Customer customer = new Customer(acNumber, name);
customerList.add(customer);
}
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return customerList;
}

}


For getting the Connection con check the Connecting Java and MySQL link. The DBConnection class provided in that link can be used to get the database connection.

Finally there is a Driver class which calls the CustomerHandler and displays the data:

import java.util.ArrayList;
public class Driver
{
public static void main(String[] args)
{
CustomerHandler custHandler = new CustomerHandler();
ArrayList<Customer> customerList = custHandler.getAllCustomers();
if (customerList == null || customerList.isEmpty()) 
                      {
                             System.out.println("No records found");
                             return;
                      }
for (Customer c : customerList)
{
System.out.println("Customer Name: " + c.getName());
System.out.println("Account Number: " + c.getACN());
}
}
}


Java: JTable example without a model

JTable has different variations. One can be very simple and used to display vector or array data. Another one can display values from databases.
The disadvantages of simple JTable constructor are as follows from docs.oracle.com

  • They automatically make every cell editable.
  • They treat all data types the same (as strings). 
  • They require that you put all of the table's data in an array or vector, which may not be appropriate for some data.

Above diagram displays the output from the example program.
The simple JTable use no model and this example will demonstrate how it is used.

import java.awt.*;
import javax.swing.*;

@SuppressWarnings("serial")
public class JTableWithOutModel extends JFrame
{

// constructor that will display a JTable based on elements received as
// arguments
public JTableWithOutModel(Object[][] data, String[] columnNames)
{
super("Static JTable example");

// JPanel that contains the table
JPanel tablePanel = new JPanel(new BorderLayout());
JTable table = new JTable(data, columnNames);
tablePanel.add(new JScrollPane(table));
add(tablePanel);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
pack();
}

public static void main(String[] args)
{
// The constructor with array arguments is used for the JTabel
// Therefore we will declare the arrays holding the column names and
// data

String[] columnNames =
{ "First Name", "Last Name", "Game", "Age", "Smoking" };

// The two-dimensional Object array initializes and stored data
Object[][] data =
{
{ "Kathy", "Smith", "Snowboarding", new Integer(25), new Boolean(false) },
{ "John", "Doe", "Rowing", new Integer(23), new Boolean(true) },
{ "Sue", "Black", "Knitting", new Integer(24), new Boolean(false) },
{ "Jane", "White", "Speed reading", new Integer(20), new Boolean(true) },
{ "Joe", "Brown", "Pool", new Integer(30), new Boolean(false) } };

new JTableWithOutModel(data, columnNames);
}
}

Java: Vector Example

A Java Vector is similar in many aspects to an ArrayList but it is synchronized. A Vector implements a dynamic array.

Here is an example demonstrating the vector operations:

  • How to initialize a vector
  • How to populate a vector adding one element at a time
  • How to add multiple elements to a vector atonce
  • How to add a Collection - List to a vector
  • How to add an array to a vector
  • How to display / read data from vector using for() loop
  • How to display / read data from vector using Enumiration
  • How to display / read data from vector using Iterator

public class VectorExample
{
private Vector<String> stringVector = new Vector<String>(10, 2);

// Initial size of the vector is 10 and when more then 10
// elements will be added then the size will increase by 2.

public VectorExample()
{
populateVector();
addListToVector();
addArrayToVector();
displayData();
readVectorUsingEnumeration();
readVectorUsingIterator();
}

private void populateVector()
{
String str = "Index";

for (int i = 0; i < 10; i++)
{
stringVector.addElement(str + i);
}
}

private void displayData()
{
for (String s : stringVector)
{
System.out.println(s);
}
}

/*
* This shows how to add an entire list to a vector
*/
private void addListToVector()
{
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
stringVector.addAll(list);
String[] array =
{ "array1", "array2", "array3" };
stringVector.addAll(Arrays.asList(array));
}

/*
* Adding a string array to a vector
*/
private void addArrayToVector()
{
String[] array =
{ "array1", "array2", "array3" };
stringVector.addAll(Arrays.asList(array));
}

/*
* Reading a vector data using Enumeration
*/
private void readVectorUsingEnumeration()
{
Enumeration<String> enm = stringVector.elements();
while (enm.hasMoreElements())
{
System.out.println(enm.nextElement());
}
}

/*
* Reading a vector data using Iterator
*/
private void readVectorUsingIterator()
{
Iterator<String> itr = stringVector.iterator();
while (itr.hasNext())
{
System.out.println(itr.next());
}
}
}

Friday 14 February 2014

Java JComboBox


Above image displays an example of a JComboBox. It has only two items (Private and Commercial)

private String[] types = {"Private", "Commercial"}
private JComboBox connectionTypes =  = new JComboBox(types);
connectionTypes .setSelectedIndex(0);

If some action has to be performed on item selection
connectionTypes .addActionListener(new SomeActionListener());

A complete code example for JComboBox can be found in this post link -> ComboBox Example

MySQL: Add multiple columns to a table

How to add a column to an existing MySQL table. For example a table is created using the following query:

CREATE TABLE CUSTOMER (
account_number int  NOT NULL PRIMARY KEY,
date DATE,
name VARCHAR(20) NOT NULL,
address VARCHAR(60) NOT NULL,
advance INT,
nic_number VARCHAR(20)
);

Now execute the explain customer query:


The table has to be altered to include telephone, connection_type and connection_fee fields.


ALTER TABLE customer
    ADD COLUMN telephone int,
    ADD COLUMN connection_type VARCHAR(15),
    ADD COLUMN connection_fee int;

Now re-executing the explain customer query yields:



Similarly in order to add one column following query will work:

ALTER TABLE customer ADD COLUMN telephone int;

It can be mentioned that where this column should be added. If a new column need to be added before connection_fee and after connection_type, it can be mentioned using after keyword.

ALTER TABLE customer ADD COLUMN newField int AFTER connection_type;


Java: Display Calendar to pick a date using JXDatePicker


How do we display such a calendar in Java desktop based application?

The easiest way to do this is to use JXDatePicker. User can use JXDatePicker to select a date similar to a JComboBox. The selected date appears in a textbox as shown in the image above. 

NOTE: For using JXDatePicker download and use the SwingX jar in your project.
SwingX can be downloaded from this link

Add the jar that you downloaded from the above link to your project. Jar can be added following link -> this post

Here is a short program which demonstrates the usage of JXDatePicker

import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jdesktop.swingx.JXDatePicker;

public class DatePickerExample extends JPanel {

    public static void main(String[] args) {
        JFrame frame = new JFrame("JXPicker Example");
        JPanel panel = new JPanel();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(400, 400, 250, 100);

        JXDatePicker picker = new JXDatePicker();
        picker.setDate(Calendar.getInstance().getTime());
        picker.setFormats(new SimpleDateFormat("dd.MM.yyyy"));

        panel.add(picker);
        frame.getContentPane().add(panel);

        frame.setVisible(true);
    }
}

use picker.getDate() to get the user entered date.