To make a button round we can first make a shape.xml in our drawable folder
shape.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<stroke
android:width="6dp"
android:color="#FFFFFF" />
<solid android:color="#FF66B2" />
<corners
android:bottomLeftRadius="45dp"
android:bottomRightRadius="45dp"
android:topLeftRadius="45dp"
android:topRightRadius="45dp" />
</shape>
This shape can be used as a background of the button:
<Button
android:id="@+id/round1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/round_button"
android:gravity="center" />
Wednesday, 23 July 2014
Tuesday, 22 July 2014
Androlid: SQLite database plugin for Eclipse
Follow following steps to download and use SQLite database viewer in Eclipse:
Download .jar file from the following -> link
Download .jar file from the following -> link
- Place the plugin .jar file in your Eclipse plugins folder (e.g. eclipse/plugins)
- Close and Restart Eclipse
- Start the emulator in Eclipse
- Switch to the DDMS Perspective in Eclipse
- Go to the 'File Explorer' tab to locate your device's database file
- Navigate 'data -> data -> com.yourproject -> databases -> yourDB
- Open the database file in Questoid (click on the icon shown in the figure)
- Switch to the 'Questoid SQLite Browser' tab that appears in the bottom
- Switch to the 'Browse Data' sub tab
- Select your table from the drop down menu and browse the table data
ADB server didn’t ACK, Failed to start Daemon
Follow the steps to get rid of this problem:
Step 1: Open the task manager, which has adb.exe process and end (kill) that process
Step 2: Now, close the eclipse, which is currently running on my computer.
Step 3: Again, restart eclipse then solved that problem.
Step 1: Open the task manager, which has adb.exe process and end (kill) that process
Step 2: Now, close the eclipse, which is currently running on my computer.
Step 3: Again, restart eclipse then solved that problem.
Android: Start or Stop adb server from Command line
Open the cmd from Start ⇒ run ⇒ cmd
Command to kill ADB server
adb kill-server
Command to start ADB server
adb start-server
Command to kill ADB server
adb kill-server
Command to start ADB server
adb start-server
Tuesday, 8 July 2014
HOW DO I CHANGE THE DATA TYPE FOR COLUNM IN MySQL
Query to change data type in MySQL table:
ALTER TABLE TABLENAME MODIFY COLUMNNAME double;
Example using this query:
ALTER TABLE transaction MODIFY receivedamount double;
Here:
TABLENAME = TRANSACTION
COLUMNNAME = RECEIVEDAMOUNT
DATATYPE = DOUBLE
ALTER TABLE TABLENAME MODIFY COLUMNNAME double;
Example using this query:
ALTER TABLE transaction MODIFY receivedamount double;
Here:
TABLENAME = TRANSACTION
COLUMNNAME = RECEIVEDAMOUNT
DATATYPE = DOUBLE
MySQL change column name query
Here is a generic form of the query to change a column name in MySQL table:
alter table TABLENAME change OLDCOLUMNNAME NEWCOLUMNNAME varchar (10) ;
Example using this query:
Alter table transaction change amount receivedamount varchar(10);
Here:
TABLENAME = TRANSACTION
OLDCOLUMNNAME = AMOUNT
NEWCOLUMNNAME = RECEIVEDAMOUNT
alter table TABLENAME change OLDCOLUMNNAME NEWCOLUMNNAME varchar (10) ;
Example using this query:
Alter table transaction change amount receivedamount varchar(10);
Here:
TABLENAME = TRANSACTION
OLDCOLUMNNAME = AMOUNT
NEWCOLUMNNAME = RECEIVEDAMOUNT
Sunday, 11 May 2014
Java: Inserting a record into MySQL database table
The given method inserts an areacode object's values to the database. It is assumed that can connect to the database. If you are not able to connect to the MySQL database please visit http://pallandri.blogspot.com/2014/02/connecting-java-and-mysql-in-eclipse.html
The code assumes that you have a DBConnection class that return a database connection. If not then check the above link.
public void addAreaCode(int areaCode, String areaName)
{
db = DBConnection.getInstance();
Connection conn = db.getConnection();
PreparedStatement stmt = null;
if (conn == null)
{
inserted.setValue("Cannot get a connection to the database");
return;
}
try
{
stmt = conn.prepareStatement("INSERT INTO AREA_CODES(area_code, area_name) " + "VALUES (?,?)");
stmt.setInt(1, areaCode);
stmt.setString(2, areaName);
stmt.executeUpdate();
}
catch (SQLException e1)
{
Logger.getGlobal().severe("Error occured while adding the area code: " + e1.getMessage());
System.out.println("SQLException: " + e1.getMessage());
e1.printStackTrace();
inserted.setValue("Unable to add area code. " + e1.getMessage());
}
finally
{
try
{
DBConnection.closeConnection();
if (stmt != null)
{
stmt.close();
}
}
catch (SQLException e1)
{
Logger.getGlobal().severe("Error occured while inserting the area code: " + e1.getMessage());
System.out.println("SQLException: " + e1.getMessage());
e1.printStackTrace();
}
}
}
The code assumes that you have a DBConnection class that return a database connection. If not then check the above link.
public void addAreaCode(int areaCode, String areaName)
{
db = DBConnection.getInstance();
Connection conn = db.getConnection();
PreparedStatement stmt = null;
if (conn == null)
{
inserted.setValue("Cannot get a connection to the database");
return;
}
try
{
stmt = conn.prepareStatement("INSERT INTO AREA_CODES(area_code, area_name) " + "VALUES (?,?)");
stmt.setInt(1, areaCode);
stmt.setString(2, areaName);
stmt.executeUpdate();
}
catch (SQLException e1)
{
Logger.getGlobal().severe("Error occured while adding the area code: " + e1.getMessage());
System.out.println("SQLException: " + e1.getMessage());
e1.printStackTrace();
inserted.setValue("Unable to add area code. " + e1.getMessage());
}
finally
{
try
{
DBConnection.closeConnection();
if (stmt != null)
{
stmt.close();
}
}
catch (SQLException e1)
{
Logger.getGlobal().severe("Error occured while inserting the area code: " + e1.getMessage());
System.out.println("SQLException: " + e1.getMessage());
e1.printStackTrace();
}
}
}
Saturday, 26 April 2014
Java: Array Tutorial
public class ArrayBasic
{
public static void main(String[] args)
{
//Declare an int array of size 100
int[] array = new int[100];
//insert elements using for loop
for(int i= 0; i<=99; i++)
{
array[i] = i;
}
//display elements
for(int i = 0; i <=99; i++)
{
System.out.println("Index" + i + " =" + array[i]);
}
}
}
{
public static void main(String[] args)
{
//Declare an int array of size 100
int[] array = new int[100];
//insert elements using for loop
for(int i= 0; i<=99; i++)
{
array[i] = i;
}
//display elements
for(int i = 0; i <=99; i++)
{
System.out.println("Index" + i + " =" + array[i]);
}
}
}
Labels:
Java: Array Tutorial
Wednesday, 2 April 2014
JTable Example
import javax.swing.*;
import java.awt.*;
@SuppressWarnings("serial")
public class JTableExample extends JPanel
{
public JTableExample()
{
super(new GridLayout(1, 0));
JTable table = new JTable(5, 4);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
Color light_blue = new Color(205, 235, 255);
scrollPane.setBackground(light_blue);
scrollPane.getViewport().setBackground(light_blue);
table.getTableHeader().setBackground(light_blue);
}
public static void createAndShowGUI()
{
JFrame frame = new JFrame("JTableExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTableExample newContentPane = new JTableExample();
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
}
public class Driver
{
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JTableExample.createAndShowGUI();
}
});
}
}
import java.awt.*;
@SuppressWarnings("serial")
public class JTableExample extends JPanel
{
public JTableExample()
{
super(new GridLayout(1, 0));
JTable table = new JTable(5, 4);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
Color light_blue = new Color(205, 235, 255);
scrollPane.setBackground(light_blue);
scrollPane.getViewport().setBackground(light_blue);
table.getTableHeader().setBackground(light_blue);
}
public static void createAndShowGUI()
{
JFrame frame = new JFrame("JTableExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTableExample newContentPane = new JTableExample();
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
}
public class Driver
{
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JTableExample.createAndShowGUI();
}
});
}
}
Labels:
JTable Example
Java: Changing JTable's Background Color in a JScrollpane
If a JTable is being displayed in a JScrollPane and the table shows only few rows of data and the rest of table is empty. Changing the color of the empty table space wont work with setBackground(...). To do this
JTable#setFillsViewportHeight(true);
or
JScrollPane#getViewport().setBackground(JTable#getBackground());
or you can to fits JScrollPanes JViewport to the JTables view by
JTable#setPreferredScrollableViewportSize(JTable#getPreferredSize());
This solution is taken from stackoverflow.
JTable#setFillsViewportHeight(true);
or
JScrollPane#getViewport().setBackground(JTable#getBackground());
or you can to fits JScrollPanes JViewport to the JTables view by
JTable#setPreferredScrollableViewportSize(JTable#getPreferredSize());
This solution is taken from stackoverflow.
Friday, 28 February 2014
Eclipse Shortcuts
I am just adding few links that have very good information about Eclipse Shortcuts.
Labels:
Eclipse Shortcuts
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
- Iterating through the Map using iterator
- Iterating through the Map keys
- Iterating through the Map values
- 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);
}
}
}
Labels:
Java: Iterating through the Map
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
Labels:
Java: JOptionPane Example
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:
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
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:
- 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:
Labels:
Java: ToolTipText
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;
}
}
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
Labels:
Java: Display year in a ComboBox
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.
{
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;
}
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;
}
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.
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;
}
}
Labels:
Database,
Java: Search a record in a table
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);
}
}
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();
}
}
}
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;
}
}
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
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);
}
}
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:
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());
}
}
}
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());
}
}
}
Labels:
Java: Vector Example
Subscribe to:
Posts (Atom)










