Reputation: 3
I am trying to generate an invoice number that contains name, branch and city with current date. I have gathered the information from JComboboxes and SimpleDateFormat. But in the end after we concat all the values and set them to a Jtextfield I get string index out of bound exception.
I am new to java and don't have much knowledge about it whatever efforts I have made for this are given as follows. I will be grateful to people interested in supporting me. Boots and Bouquets both are welcome.
private void bt_generateActionPerformed(java.awt.event.ActionEvent evt) {
if (evt.getSource() == bt_generate) {
if ((cb_bkname.getSelectedItem()
.equals("<html><font color=\"red\">SELECT NAME</font></html>"))
|| (cb_brname.getSelectedItem()
.equals("<html><font color=\"red\">SELECT BRANCH</font></html>"))
|| (cb_plname.getSelectedItem()
.equals("<html><font color=\"red\">SELECT PLACE</font></html>"))
){
} else {
String datePrefix = new SimpleDateFormat("MMMM dd, YYYY")
.format(new Date());
tf_rm_dt.setText(datePrefix);
Object name = cb_bkname.getSelectedItem();
String bn = name.toString().substring(0, 3);
Object branch = cb_brname.getSelectedItem();
String br = branch.toString().substring(0, 4);
Object city = cb_bkname.getSelectedItem();
String pl = city.toString().substring(0, 4);
String curdt = new SimpleDateFormat("dd-MM-YY")
.format(new Date());
tf_rm_id.setText("" + bn + "/" + br + "/" + "/" + curdt);
}
}
}
The StackTrace is as follows:
run:
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.substring(String.java:1955)
at myproj.DATAENTRY.bt_generateActionPerformed(DATAENTRY.java:2215)
at myproj.DATAENTRY.access$2300(DATAENTRY.java:20)
at myproj.DATAENTRY$24.actionPerformed(DATAENTRY.java:597)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
Upvotes: 0
Views: 1951
Reputation: 1294
This is an inefficient and overly complicated means to get information from a combo box! Can't you assign the selection, to an object (as an enum type, for example), prior to the concatenation? If you know what the selections are (which hopefully you do) you shouldn't ever need to use substring!
Upvotes: 0
Reputation: 28767
One of your strings is to short:
The error is either in one of these 3 lines
String bn=name.toString().substring(0, 3);
String br=branch.toString().substring(0, 4);
String pl=city.toString().substring(0, 4);
Print out the string, and check length before doing the substring()
Upvotes: 1