Adding an event listener to combo box
I am working on a mortgage calculator and I cannot figure out how to add an event listener to a combo box.
I want to get the mortgage term and interest rate to calucate the mortgage using the combo cox. Here is my program.
Modify the mortgage program to allow the user to input the amount of a mortgage
and then select from a menu of mortgage loans: 7 year at 5.35%, 15 year at 5.50%, and
30 year at 5.75%. Use an array for the different loans. Display the mortgage payment
amount. Then, list the loan balance and interest paid for each payment over the term
of the loan. Allow the user to loop back and enter a new amount and make a new
selection, with resulting new values. Allow user to exit if running as an application
(can't do that for an applet though).
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.text.NumberFormat;
import java.util.Locale;
//creates class MortgageCalculator
public class MortgageCalculator extends JFrame implements ActionListener {
//creates title for calculator
JPanel row = new JPanel();
JLabel mortgageCalculator = new JLabel("MORTGAGE CALCULATOR", JLabel.CENTER);
//creates labels and text fields for amount entered
JPanel firstRow = new JPanel(new GridLayout(3,1,1,1));
JLabel mortgageLabel = new JLabel("Mortgage Payment $", JLabel.LEFT);
JTextField mortgageAmount = new JTextField(10);
JPanel secondRow = new JPanel();
JLabel termLabel = new JLabel("Mortgage Term/Interest Rate", JLabel.LEFT);
String[] term = {"7", "15", "30"};
JComboBox mortgageTerm = new JComboBox(term);
JPanel thirdRow = new JPanel();
JLabel interestLabel = new JLabel("Interest Rate (%)", JLabel.LEFT);
String[] interest = {"5.35", "5.50", "5.75"};
JComboBox interestRate = new JComboBox(interest);
JPanel fourthRow = new JPanel(new GridLayout(3, 2, 10, 10));
JLabel paymentLabel = new JLabel("Monthly Payment $", JLabel.LEFT);
JTextField monthlyPayment = new JTextField(10);
//create buttons to calculate payment and clear fields
JPanel fifthRow = new JPanel(new GridLayout(3, 2, 1, 1));
JButton calculateButton = new JButton("CALCULATE PAYMENT");
JButton clearButton = new JButton("CLEAR");
JButton exitButton = new JButton("EXIT");
//Display area
JPanel sixthRow = new JPanel(new GridLayout(2, 2, 10, 10));
JLabel displayArea = new JLabel(" ", JLabel.LEFT);
JTextArea textarea = new JTextArea(" ", 8, 50);
public MortgageCalculator() {
super("Mortgage Calculator"); //title of frame
setSize(550, 350); //size of frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = getContentPane();
GridLayout grid = new GridLayout(7, 3, 10, 10);
pane.setLayout(grid);
pane.add(row);
pane.add(mortgageCalculator);
pane.add(firstRow);
pane.add(mortgageLabel);
pane.add(mortgageAmount);
pane.add(secondRow);
pane.add(termLabel);
pane.add(mortgageTerm);
pane.add(thirdRow);
pane.add(interestLabel);
pane.add(interestRate);
pane.add(fourthRow);
pane.add(paymentLabel);
pane.add(monthlyPayment);
monthlyPayment.setEnabled(false);
pane.add(fifthRow);
pane.add(calculateButton);
pane.add(clearButton);
pane.add(exitButton);
pane.add(sixthRow);
pane.add(textarea); //adds texaarea to frame
pane.add(displayArea);
setContentPane(pane);
setVisible(true);
//Adds Listener to buttons
calculateButton.addActionListener(this);
clearButton.addActionListener(this);
exitButton.addActionListener(this);
mortgageTerm.addActionListener(this);
interestRate.addActionListener(this);
public void actionPerformed(ActionEvent event) {
Object command = event.getSource();
JComboBox mortgageTerm = (JComboBox)event.getSource();
String termYear = (String)mortgageTerm.getSelectedItem();
if (command == calculateButton) //calculates mortgage payment
int year = Integer.parseInt(mortgageTerm.getText());
double rate = new Double(interestRate.getText()).doubleValue();
double mortgage = new Double(mortgageAmount.getText()).doubleValue();
double interest = rate /100.0 / 12.0;
double monthly = mortgage *(interest/(1-Math.pow(interest+1,-12.0 * year)));
NumberFormat myCurrencyFormatter;
myCurrencyFormatter = NumberFormat.getCurrencyInstance(Locale.US);
monthlyPayment.setText(myCurrencyFormatter.format(monthly));
if(command == clearButton) //clears all text fields
mortgageAmount.setText(null);
//mortgageTerm.setText(null);
//interestRate.setText(null);
monthlyPayment.setText(null);
if(command == exitButton) //sets exit button
System.exit(0);
public static void main(String[] arguments) {
MortgageCalculator mor = new MortgageCalculator();
The OP already did this to both JComboBoxes.
mochatay, here is a new actionPerformed method for you to use.
I've improved a few things here and there...
1) You can't just cast the ActionEvent's source into a JComboBox!
What if it was a JButton that fired the event? Then you would get ClassCastExceptions (I'm sure you did)
So check for all options, what the source of the ActionEvent actually was...
2) You can't assume the user will always type in valid data.
So enclose the Integer and Double parse methods in try-catch brakcets.
Then you can do something when you know that the user has entered invalid input
(like tell him/her what a clumsy idiot they are !)
3) As soon as user presses an item in any JComboBox, just re-calculate.
I did this here by programmatically clicking the 'Calculate' button.
Alternatively, you could have a 'calculate' method, which does everything inside the
if(command==calculateButton) if-block.
This will be called when:
a)calculateButton is pressed
b)when either of the JComboBoxes are pressed.
public void actionPerformed (ActionEvent event)
Object command = event.getSource ();
if (command == calculateButton) //calculates mortgage payment
int year = 0;
double rate = 0;
double mortgage = 0;
double interest = 0;
/* If user has input invalid data, tell him so
and return (Exit from this method back to where we were before */
try
year = Integer.parseInt (mortgageTerm.getSelectedItem ().toString ());
rate = new Double (interestRate.getSelectedItem ().toString ()).doubleValue ();
mortgage = new Double (mortgageAmount.getText ()).doubleValue ();
interest = rate / 100.0 / 12.0;
catch (NumberFormatException nfe)
/* Display a message Dialogue box with a message */
JOptionPane.showMessageDialog (this, "Error! Invalid input!");
return;
double monthly = mortgage * (interest / (1 - Math.pow (interest + 1, -12.0 * year)));
NumberFormat myCurrencyFormatter;
myCurrencyFormatter = NumberFormat.getCurrencyInstance (Locale.US);
monthlyPayment.setText (myCurrencyFormatter.format (monthly));
else if (command == clearButton) //clears all text fields
/* Better than setting it to null (I think) */
mortgageAmount.setText ("");
//mortgageTerm.setText(null);
//interestRate.setText(null);
monthlyPayment.setText ("");
else if (command == exitButton) //sets exit button
System.exit (0);
else if (command == mortgageTerm)
/* Programmatically 'clicks' the button,
As is user had clicked it */
calculateButton.doClick ();
else if (command == interestRate)
calculateButton.doClick ();
//JComboBox mortgageTerm = (JComboBox) event.getSource ();
//String termYear = (String) mortgageTerm.getSelectedItem ();
}Hope this solves your problems.
I also hope you'll be able to learn from what I've indicated, so you can use similar things yourself
in future!
Regards,
lutha
Similar Messages
-
Problem in event handling of combo box in JTable cell
Hi,
I have a combo box as an editor for a column cells in JTable. I have a event listener for this combo box. When ever I click on the JTable cell whose editor is combo box,
I get the following exception,
Exception occurred during event dispatching:
java.lang.NullPointerException
at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.setDispatchComponent(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.mousePressed(Unknown Source)
at java.awt.AWTEventMulticaster.mousePressed(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Can any one tell me how to over come this problem.
Thanks,
RaghuHere's an example of the model I used in my JTable. I've placed 2 comboBoxes with no problems.
Hope this helps.
public class FileModel5 extends AbstractTableModel
public boolean isEditable = false;
protected static int NUM_COLUMNS = 3;
// initialize number of rows to start out with ...
protected static int START_NUM_ROWS = 0;
protected int nextEmptyRow = 0;
protected int numRows = 0;
static final public String file = "File";
static final public String mailName = "Mail Id";
static final public String postName = "Post Office Id";
static final public String columnNames[] = {"File", "Mail Id", "Post Office Id"};
// List of data
protected Vector data = null;
public FileModel5()
data = new Vector();
public boolean isCellEditable(int rowIndex, int columnIndex)
// The 2nd & 3rd column or Value field is editable
if(isEditable)
if(columnIndex > 0)
return true;
return false;
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
public Class getColumnClass(int c)
return getValueAt(0, c).getClass();
* Retrieves number of columns
public synchronized int getColumnCount()
return NUM_COLUMNS;
* Get a column name
public String getColumnName(int col)
return columnNames[col];
* Retrieves number of records
public synchronized int getRowCount()
if (numRows < START_NUM_ROWS)
return START_NUM_ROWS;
else
return numRows;
* Returns cell information of a record at location row,column
public synchronized Object getValueAt(int row, int column)
try
FileRecord5 p = (FileRecord5)data.elementAt(row);
switch (column)
case 0:
return (String)p.file;
case 1:
return (String)p.mailName;
case 2:
return (String)p.postName;
catch (Exception e)
return "";
public void setValueAt(Object aValue, int row, int column)
FileRecord5 arow = (FileRecord5)data.elementAt(row);
arow.setElementAt((String)aValue, column);
fireTableCellUpdated(row, column);
* Returns information of an entire record at location row
public synchronized FileRecord5 getRecordAt(int row) throws Exception
try
return (FileRecord5)data.elementAt(row);
catch (Exception e)
throw new Exception("Record not found");
* Used to add or update a record
* @param tableRecord
public synchronized void updateRecord(FileRecord5 tableRecord)
String file = tableRecord.file;
FileRecord5 p = null;
int index = -1;
boolean found = false;
boolean addedRow = false;
int i = 0;
while (!found && (i < nextEmptyRow))
p = (FileRecord5)data.elementAt(i);
if (p.file.equals(file))
found = true;
index = i;
} else
i++;
if (found)
{ //update
data.setElementAt(tableRecord, index);
else
if (numRows <= nextEmptyRow)
//add a row
numRows++;
addedRow = true;
index = nextEmptyRow;
data.addElement(tableRecord);
//Notify listeners that the data changed.
if (addedRow)
nextEmptyRow++;
fireTableRowsInserted(index, index);
else
fireTableRowsUpdated(index, index);
* Used to delete a record
public synchronized void deleteRecord(String file)
FileRecord5 p = null;
int index = -1;
boolean found = false;
int i = 0;
while (!found && (i < nextEmptyRow))
p = (FileRecord5)data.elementAt(i);
if (p.file.equals(file))
found = true;
index = i;
} else
i++;
if (found)
data.removeElementAt(i);
nextEmptyRow--;
numRows--;
fireTableRowsDeleted(START_NUM_ROWS, numRows);
* Clears all records
public synchronized void clear()
int oldNumRows = numRows;
numRows = START_NUM_ROWS;
data.removeAllElements();
nextEmptyRow = 0;
if (oldNumRows > START_NUM_ROWS)
fireTableRowsDeleted(START_NUM_ROWS, oldNumRows - 1);
fireTableRowsUpdated(0, START_NUM_ROWS - 1);
* Loads the values into the combo box within the table for mail id
public void setUpMailColumn(JTable mapTable, ArrayList mailList)
TableColumn col = mapTable.getColumnModel().getColumn(1);
javax.swing.JComboBox comboMail = new javax.swing.JComboBox();
int s = mailList.size();
for(int i=0; i<s; i++)
comboMail.addItem(mailList.get(i));
col.setCellEditor(new DefaultCellEditor(comboMail));
//Set up tool tips.
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for mail Id list");
col.setCellRenderer(renderer);
//Set up tool tip for the mailName column header.
TableCellRenderer headerRenderer = col.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer)
((DefaultTableCellRenderer)headerRenderer).setToolTipText(
"Click the Mail Id to see a list of choices");
* Loads the values into the combo box within the table for post office id
public void setUpPostColumn(JTable mapTable, ArrayList postList)
TableColumn col = mapTable.getColumnModel().getColumn(2);
javax.swing.JComboBox combo = new javax.swing.JComboBox();
int s = postList.size();
for(int i=0; i<s; i++)
combo.addItem(postList.get(i));
col.setCellEditor(new DefaultCellEditor(combo));
//Set up tool tips.
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for post office Id list");
col.setCellRenderer(renderer);
//Set up tool tip for the mailName column header.
TableCellRenderer headerRenderer = col.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer)
((DefaultTableCellRenderer)headerRenderer).setToolTipText(
"Click the Post Office Id to see a list of choices");
} -
How to populate data in the data table on combo box change event
hi
i am deepak .
i am very new to JSF.
my problem is i want to populate data in the datatable on the combo box change event.
for example ---
combo box has name of the city. when i will select a city
the details of the city should populate in the datatable. and if i will select another city then the datatable should change accordingly..
its urgent
reply as soon as possible
thanks in advancei am using Rational Application Developer to develop my application.
i am using a combo box and i am assigning cityName from the SDO.
and i am declaring a variable in the pageCode eg.
private String cityName;
public void setCityName(String cityName){
this.cityName = cityName;
public String getCityName(){
return cityName;
<h:selectOneMenu id="menu1" styleClass="selectOneMenu" value="#{pc_Test1.loginID}" valueChangeListener="#{pc_Test1.handleMenu1ValueChange}">
<f:selectItems
value="#{selectitems.pc_Test1.usercombo.LOGINID.LOGINID.toArray}" />
</h:selectOneMenu>
<hx:behavior event="onchange" target="menu1" behaviorAction="get"
targetAction="box1"></hx:behavior>
and also i am declaring a requestParam type variable named city;
and at the onChangeEvent i am writing the code
public void handleMenu1ValueChange(ValueChangeEvent valueChangedEvent) {
FacesContext context = FacesContext.getCurrentInstance();
Map requestScope = ext.getApplication().createValueBinding("#{requestScope}").getValue(context);
requestScope.put("login",(String)valueChangedEvent.getNewValue());
and also i am creating another SDO which is used to populate data in datatable and in this SDO in the where clause i am using that requestParam .
it is assigning value in the pageCode variable and in the requestParam but it is not populating the dataTable. i don't no why??
it is possible that i may not clear at this point.
please send me the way how my problem can be solved.
thanks in advance -
Catching COMBO BOX item changed in VALIDATE event
Hi expert,
I need to catch the item changed event for a combo box.
below the code:
<B1Listener(BoEventTypes.et_VALIDATE, False)> _
Public Overridable Sub OnAfterValidate(ByVal pVal As ItemEvent)
Dim form As Form = B1Connections.theAppl.Forms().Item(pVal.FormUID)
Dim mt As Matrix = Form.Items.Item("Matrix_0").Specific
if (pVal.ColUID.Equals("TipoList") And pVal.ItemChanged) Then
end if
but pVal.ItemChanged is always equal to false even if I change the value selected in combo box.
can anyone help me?
Thanks in advance.
Best regards
AndreaHi Andrea,
you can also catch the Event through
pVal.EventType =SAPbouiCOM.BoEventTypes.et_COMBO_SELECT
through this event, you can perform you're reuqirement.
regards
shiva -
Displaying text in a combo box.
Hi, i was wondering if anyone could help me finish an application i am working on. I have two forms, one inputs dat to a text file and another retrieves it. i want to display the text in a combo box and then click an event in the combo box and a description
of the event will appear in a text box, also if i select a date on the second form the events in the combo box change for that date if there is events for it. the first form is working fine , i was looking for help with the second one please. my code
so far is:
namespace TicketInformation
public partial class TicketInformationForm : Form
public TicketInformationForm()
InitializeComponent();
//creating the community events list.
List<Community_Event> CommnunityEvents;
//create the Create Event list method.
private void CreateEventList()
CommnunityEvents = new List<Community_Event>();
// call the extract Data method.
ExtractData();
//Clear any events from the combo box before proceeding.
eventComboBox.Items.Clear();
//for each event item in the Commuity event list,add it to the eventComboBox.
foreach (Community_Event item in CommnunityEvents)
eventComboBox.Items.Add(item.Description);
//if the events count is greater then 0, display the following
if (CommnunityEvents.Count > 0)
//if there are no events for the date selected display the following
eventComboBox.Text = " -Events- ";
descriptionTextBox.Text = "Pick an event";
}//end if
else
//if there are no events for the date selected display the following
eventComboBox.Text = " No Events ";
descriptionTextBox.Text = "No events today.";
}//end else
//Creating the Method ExtractData
private void ExtractData()
CommnunityEvents.Clear();
// load the data from the file
List<Community_Event> tempList = new List<Community_Event>();
//string[] fileLines = File.ReadLines(@"C:\Users\IAN\Documents\calendar.txt");
foreach(string line in File.ReadLines("calendar.txt"))
string[] items = line.Split(",".ToCharArray());
if (items.Length >= 5)
Community_Event newEvent = new Community_Event();
newEvent.Day = Convert.ToInt32(items[0]);//Converting the Integer to a string.
newEvent.Time = items[1];
newEvent.Price = Convert.ToDecimal(items[2]);//Converting the decimal to a string.
newEvent.Event = items[3];
newEvent.Description = items[4];
//add the new events to the Comminity Events list.
CommnunityEvents.Add(newEvent);
CommnunityEvents = (from ev in tempList
where ev.Day == 1
select ev).ToList();
private void dateMonthCalendar_DateChanged(object sender, DateRangeEventArgs e)
//calling the create event list method to display any events in the eventscombo box.
CreateEventList();
private void eventComboBox_SelectedIndexChanged(object sender, EventArgs e)
private void descriptionTextBox_TextChanged(object sender, EventArgs e)
private void TicketInformationForm_Load(object sender, EventArgs e)
//calling the create event list to open the form with today's events displayed if any.
CreateEventList();
public class Community_Event
//Declare a DayValue property of type int
private int DayValue;//day of the event
public int Day// Name of the Property
get
return DayValue;
set
DayValue = value;
//Declare a TimeValue property of type string
private string timeValue;//time of the event
public string Time// Name of the Property
get
return timeValue;
set
timeValue = value;
//Declare a priceValue property of type Decimal
private decimal priceValue;//price of the event
public decimal Price// Name of the Property
get
return priceValue;
set
priceValue = value;
//Declare a eventNameValue property of type string
private string eventNameValue;//name of the event
public string Event// Name of the Property
get
return eventNameValue;
set
eventNameValue = value;
//Declare a DescriptionValue of type string
private string DescriptionValue;//description of the event
public string Description// Name of the Property
get
return DescriptionValue;
set
DescriptionValue = value;
Thanks
DHi Dylan2412,
According to your description, you'd like to pass the ComboBox.Text to the second form's TextBox.
In Form1:
private void button1_Click(object sender, EventArgs e)
Form2 f2 = new Form2(this.comboBox1.Text); //pass the comboBox1.Text
f2.Show();
In Form2:
public Form2(string s) //get the string;
InitializeComponent();
this.textBox1.Text = s;
You could get the comBoBox refer to this sample above.
If you have any other concern regarding this issue, please feel free to let me know.
Best regards,
Youjun Tang
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Layer/OCG Visibility based on Combo Box Selection
Hello,
I'm VERY new to javascript, so please bear with me. I have a combo box with multiple selections. For some selections, I would like a separate OCG layer to appear, and with other selections that same layer to disappear.
For example:
ComboBox1: A, B, C
Layer 1 default: hidden
A - toggle layer 1: hidden
B - toggle layer 2: hidden
C - toggle layer 3: visible
I have seen the javascripting involved turning layers on/off with buttons, but I'm having some difficultly with the combo box.
Thanks!
MikeThe code would be much the same as with buttons. Use the Validate event of the combo box to get the selected value (event.value) and show/hide the appropriate OCGs. If the combo box items have export values, you'd use the Keystroke event so you can get the export value of the selected item via the event.changeEx property: http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/JS_API_AcroJS.88.607.html
-
Populate Combo Box field into another field
I've got a form (form1) based off a table (table1). In the form I have a field from table1 called
bagtype that is a combobox type field with a row source from another table with two fields that show up in the drop down box when selected. When I select a field from the dropdown box only the first field populates the actual form field
(and underlying table) which is what I want. What I'd also like to happen is the second field of the combo box that doesn't populate the bagtype field is for it to populate another field (from table1) on the same form and store that
value in the underlying table as well. The other field in the form is called
AStd.
TAKHi,
you need 1 line of VBA code in the AfterUpdate event of the combo box:
Me!NameOfTheTargetFieldOrControl = Me!BagType.Column(1)
The column index is zero based i.e. 0 = first column of the combo box, 1 = second column etc.
cu
Karl
Access FAQ (de/it): donkarl.com
Access Lobby: AccessDevelopers.org -
Connected Combo box problem ! please help me
Dear Friends....!
I am developing project in which i have 3 combo :
1) District Selection
2) Taluka Selection
3) Village Selection
Depend on village selection , perticular persons on that village is displayed on the page.
This values must be fetched from DATABASE !
<b> I tried with JAVASCRIPT but with it i can connect two combo and
can't access database inside javascript. WHAT IS THE SOLUTION EXCEPT AJAX ( That i don't KNOW ) </b>
may be i can put 3 combo together and on first OnChange event
i can submit page and process another page and put values in
another combo and forward page to combo page again.
i am very much confused HELP ME !
please i don't know AJAX else problem would be easily solved.
EVEN I CAN"T MANUALLY PUT DATA IN JAVASCRIPT bcoz my villages
are more than 400.
how to put java database code in javascript OnChange event ???
to fetch data of another combo ?
HELP WITH EASY SOLUTION.
Thanks
GHanshyam
================================
SOLUTION FOR TWO COMBO
function populate(o) {
d=document.getElementById('de');
if(!d){return;}
var mitems=new Array();
mitems['Choose']=[''];
mitems['Salads']=['Select Item','Tuna Salad','Cesar Salad','Green Salad','Prawn Salad'];
mitems['Main Courses']=['Select Item','Filet Mignon','Porterhouse','Flank','T-Bone'];
mitems['Drinks']=['Select Item','Milkshake','Soda','Mixed Drink','Juice'];
mitems['Desserts']=['Select Item','Ice Cream','Fresh Fruit','Pie'];
mitems['Snacks']=['Select Item','Brownies','Cookies','Potato Chips'];
d.options.length=0;
cur=mitems[o.options[o.selectedIndex].value];
if(!cur){return;}
d.options.length=cur.length;
for(var i=0;i<cur.length;i++) {
d.options.text=cur[i];
d.options[i].value=cur[i];
<!-- Paste this code into the HEAD section of your HTML document.
You may need to change the path of the file. -->
<script type="text/javascript" src="dropdownBox.js"></script>
<!-- Paste this code into the BODY section of your HTML document -->
<form action="" method="get">
<label for="or">Our menu:</label>
<select name="or" id="or" onchange="populate(this)">
<option value="Choose">Select from the Menu</option>
<option value="Salads">Salads</option>
<option value="Main Courses">Main Courses</option>
<option value="Drinks">Drinks</option>
<option value="Deserts">Deserts</option>
<option value="Snacks">Snacks</option>
</select>
<label for="de">Select:</label>
<select name="de" id="de"></select>
<input type="submit" value="Show me" />
</form>
<p><div align="center">
</div><p>may be i can put 3 combo together and on first
OnChange event
i can submit page and process another page and put
values in
another combo and forward page to combo page again.Almost there. What you should do is submit the page on the onChange event of the combo box; but submit to the same JSP. Then, depending on the values that each of the combo boxes contains, run a query for villages in that District and under that Talluka.
And populate the third combo box. If any one of the ( first two ) boxes is empty i.e user didnt' select a value, then you'll automatically get no value for the combo boxes from the query.
Something like this
<%
String selectedDistrict = request.getParameter("districtcombobox");
String selectedTalluka = request.getParameter("tallukacombobox");
//make sure you don't nulls
selectedDistrict = selectedDistrict == null?"":selectedDistrict;
selectedTalluka = selectedTalluka == null?"":selectedTalluka;
PreparedStatement psFetchTallukas = con.prepareStatement("select tallukaname from tallukas where tallukadistrict = ?");
PreparedStatement psFetchVillages = con.prepareStatement("select villagename from villages where villagetaluka = ?");
psFetchTallukas.setString(1, selectedDistrict);
psFetchVillages.setString(1, selectedTalluka);
rsTallukas = psFetchTallukas.executeQuery();
rsVillages = psFetchVillages.executeQuery();
//now, print out your <option> elements under the corresponding <select> tags for each of the 3 select boxes
%>For your onChange event you don't need to do anything except call form.submit() where the action should be the same JSP. In case your form is going to be submitted to another page on the final submit i.e after selecting all required values; then in the onChange event handler, before the submit(), you should change the action property of the form to the same page and then submit. -
Event listener on inline graphic
Hi
Is there a way to add an event listener to an inline graphic.
I cant seem to find much... or any help concerning this in
the forums.
I remember reading a post about this a while back where
someone wanted to add a doubble click to an inline graphic without
success. Has that been resolved?
Im desperate to get this working and any help would be much
appreciated
Thank youHI
Thanks again for the reply. Check StatusChangeEvent.status
for "ready" works perfectly.
Sorry to ask more questions on this topic but I cant find
documentation or info anywhere else. If you could give me a link I
would be happy to go that route...
I added an event listener to the inline graphic and gave it a
name as follows:
ILG.graphic.name = LIG.source.toString();
ILG.graphic.addEventListener(MouseEvent.MOUSE_OVER,
ILGhandeler);
then when I trace the target I get //instance23
eg trace(e.target.name) //instance23
but if I do the following I get the source that im looking
for:
trace(e.target.parent.parent.name) // path/to/graphic.
1) Is what IM doing good practise?
2) can I add the source to something other than the .name
//eg ILG.graphic.theurl = ILG.source.toString();
3) Is there a way to target and replace or update an
ILGElement just by knowing its source.
ie (replace or update) ILGElement where LIGElement.source ==
"theurl"
Help with this will be awesome. Thank you for your patience -
Action event automatically triggered for combo box
Hi all,
I am facing a typical event handling problem for combo box in Swing(Using Net Beans 5.0, jdk 1.4.2)
While adding items to combo box it is firing action event twice instead of once irrespective of no. of items added to it.
For eg if there are 1 or more than 1 item added to combo box it is triggerring action event twice(one just after when first item is added and one again when rest all items are added)
and if there is no item then also it is triggering once.
Can you please help me out.
Thankspost the SSCCE code, then only it is easy to find the problem
-
Hi i am trying to put a simple application together to let me put events into a text file and then let me click a date on a second form to let me see my events for that date in a text box. I have all the input forms working correctly but am struggling a
bit with the reading data part. i would really appreciate if anyone can give me any pointers as to how i can get the info to appear in the second form, so far my second form looks like this:
public TicketInformationForm()
InitializeComponent();
//creating the community events list.
List<Community_Event> CommnunityEvents;
//create the Create Event list method.
private void CreateEventList()
CommnunityEvents = new List<Community_Event>();
// call the extract Data method.
ExtractData();
if (CommnunityEvents.Count > 0)
//if there are no events for the date selected display the following
eventComboBox.Text = " -Events- ";
descriptionTextBox.Text = "Pick an event";
else
//if there are no events for the date selected display the following
eventComboBox.Text = " No Events ";
descriptionTextBox.Text = "No events today.";
//Create Method ExtractData
private void ExtractData()
CommnunityEvents.Clear();
// load the data from the file
List<Community_Event> tempList = new List<Community_Event>();
string[] fileLines = File.ReadLines(@"C:\Users\IAN\Documents\calendar.txt");
foreach(string line in fileLines)
string[] items = fileLines[1].Split(",".ToCharArray());
Community_Event newEvent = new Community_Event();
newEvent.Day = Convert.ToInt32(items[0]);//Converting the Integer to a string.
newEvent.Time = items[1];
newEvent.Price = Convert.ToInt32(items[2]);//Converting the decimal to a string.
newEvent.Event = items[3];
newEvent.Description = items[4];
CommnunityEvents = (from ev in tempList
where ev.Day == 1
select ev).ToList();
private void dateMonthCalendar_DateChanged(object sender, DateRangeEventArgs e)
//calling the create event list method to display any events in the eventscombo box.
CreateEventList();
private void eventComboBox_SelectedIndexChanged(object sender, EventArgs e)
private void descriptionTextBox_TextChanged(object sender, EventArgs e)
private void TicketInformationForm_Load(object sender, EventArgs e)
//calling the create event list to open the form with today's events displayed if any.
CreateEventList();Hi, thanks for the reply, sorry I should have mentioned that I have already created the community event class with the get and set properties set up in it for all the fields I am adding to the text file like date time etc. i just do not seem to be able
to extract the data using the code I have above. sorry I am relatively new to this stuff and am just trying out a few applications to teach myself. -
Combo box, ring and event to modify them runtime
Hi,
I attached a picture of the block diagram. Using LV 8.2.1, win XP.
What I want : User should select from Main Selection, and that brings up new values for strings in the other menus (tried both combo box and menu ring items).
Teh problem : This block doesn't do that. Why? Looking with probe, I see the event captured and data are ok until the property node. They are not writed and on the front panel I see no difference.
Thanx
Attachments:
double box test.jpg 97 KB
Test doppio ring.vi 21 KBSlyfer wrote:
I thought that the code inside the while loop but outside the event structure wasn't care.
So if I want to do something continuosly (for example continuosly comparing two integer values to have a real-time boolean led indicator on front panel), do I put the code in the middle? This is a bit confusing thinking about the "timeout event"....
Use the timeout event or put in the middle (=outside event structure but inside while loop.... at which CPU rate is executed?? too fast?) ??
Just a suggestion. The timeout event for the Event Structure [ES] is equivalent to that of providing a small delay inside the while loop.
But it is not mandatory. If you dont wire some value to the timeout terminal, but still want to something, like comparison, you can very well put that code outside the ES but inside the while loop. It ll execute.
Else you can wire a value like 50 or 100 to the timeout terminal [ this gives enough time for the execution of the various codes inside the various events configured for the ES], so that the ES times out for every 50 or 100 ms when none of the other events occurs. If you put your comparison code here, it ll be doing the comparison all the time or whenever the ES waits and crosses the specified ms after an event has happened.
I hope this gives you a clear idea about eventstructures.
See the below links for more details on Event Structures.
http://zone.ni.com/devzone/cda/tut/p/id/3331
http://zone.ni.com:80/reference/en-XX/help/371361B-01/lvconcepts/using_events_in_labview/
http://zone.ni.com/reference/en-XX/help/371361B-01/lvhowto/caveatsrecmndtnsevnts/
- Partha
LabVIEW - Wires that catch bugs! -
Reg - 'F1' key event in Combo box
Hi,
Requirement:
I have requirement that to launch a browser window on press of 'F1' key while the movie (swf) has focus. I did it and working fine for me in web application.
Problem statement:
When a movie had been launched and having focus in 'Combo box' (which has list of items starts with A to Z letters) control then, i pressed 'F1' key but the browser window has not been launched, instead 'Combo box's key action event get fired and the item starts with the letter 'P' has been selected in the combo box list. If now again i press 'F1' key the browser window has launched as per my requirement.
This behavior is happening whenever the launched movie has focus in 'Combo box'; otherwise if the focus is on some other control like TextInput etc., no problem for me. One more information, if the Combo box doesn't have any item starts with the letter 'P' then no problem for me.
I tried to understand the behavior of combo, but still i don't have any clue. Please share your knowledge/thoughts.
Environment:
Flex builder 3.5
Adobe flash player 11.2
Windows XP SP3
Regards,
ManiHi,
I just overridden the keydown handler function in ComboBox component to avoid its own event propagation behavior if 'F1' key is pressed and its working fine for me.
Thanks for all,
-Mani -
Everytime I open ICal a box comes up with "Adding New Events" - Program freezes
Everytime I open ICal a box comes up with "Adding New Events" and I can't get rid of it without force quitting out of the program. Any suggestions???
I am having the same problem with no luck trying to find any help. Please help us find a solution for this.
-
Adding Images to a Combo Box-Acrobat 9 Pro
Hello everyone. Can images be used as selections in a combo box in Acrobat 9 Pro? If so, how can I set that up? I only see an option for text choices when I look at the combo box properties. Basically, I want to click the drop-down and see images (clip-art basically) to choose from instead of text choices. Thank you for the help.
Yeah, unfortunately, that isn't an option for the people will be using this form. I really need to know if there is a way to have 1 text box that I can alter line spacing.
Maybe you are looking for
-
Since updating to new firefox I have lost a very helpful tool. Before, when I clicked on a website to visit, the color of the print would change from blue to purple to indicate that I had visited that site. Now it does not do that so it is difficult
-
How do I add a dismissable notice to my (office 365) public website?
Hi I have a public website and I want to add a small pop-up message that says something like "We have placed cookies on your computer to help make this website better. We use a Google Analytics script which sets cookies. More details can be found in
-
hi everyone, i am using a bat file to package an air file , this application runs on windows 7 32 bit, it need to call another windows application , so i google and then find i need to add -target native when package , so i added. the bat file is lik
-
Not able to connect to internet...Please Help!
I switched from PC to mac today and bought a Mac Book. I have been trying to connect to network and have had no success. It identifies my network and asks for my WEP password, which I retrieved from my internet company. I tried with every type of sec
-
Also what is statistical conditions ? Why we define the Account keys and accruel keys for certain condition types in pricing procedure, what is the significance of the same from the perspective of the accounting? When i defined the account key for on