JComboBox addActionListener does not work - java

So I have this project,
the source code is here.
When you run the project and goto Processing, there is a jcombobox there that is suppose to have an addActionListener.
p_customer_list = new JComboBox<>(customers_name);
pp_customer_list.setPreferredSize(new Dimension(360, 35));
panel_processing_header.add(pp_customer_list);
//pp_customer_list.addActionListener(this);
pp_customer_list.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
JComboBox tmpBox = (JComboBox) e.getSource();
int selected = tmpBox.getSelectedIndex();
pp_refresh_data(selected);
}
});
This is what I have so far, its suppose to find the selected index when the value of the combobox changes and pass it to pp_refresh_data() but for some reason it does not run (I tried putting a JOptionPane to see when the code is executed, and its only executed once when the program runs.)

Hard to tell from just a partial code snippet, but do you have 2 combos, one named "p_customer_list" and another named "pp_customer_list"?
This could be your problem. You may be adding the listener to the wrong combo, or you may be adding the wrong combo to your panel, or maybe you don't need two, or maybe...
Again, it's hard to tell from just a snippet.

Related

Why the method of my jtable getSelectedRow() don't work?

this is my first question, so help me please. I try to save the value of the method getStelectedRow in a type int variable(row) to next can use the method getValueAt(row,column). My problem is the value of my variable, it's -1, and this means the row is not selected, but I'm selecting a row.
The error is the next:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
If need more details just say me. Thanks.
EDIT:
My code is:
int row = jTablePersonal.getSelectedRow();
String query = "select * from table where id ='"+jTablePersonal.getValueAt(row,0)+"'";
The error point to the variable "row" when I call the method "getValueAt(row,0)"
Seems like a newbie problem. Given your explanation
"My problem is the value of my variable, it's -1, and this means the row is not selected, but I'm selecting a row."
You do not have this code inside a listener, you have like it your constructor or something. You want to have the code inside the listener. Something like
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if (row != -1) {
// do something
}
}
});
If you are using the Netbeans GUI Builder tool, you can
From the design view right click the button and go to Events -> Action -> actionPerformed
Go to you source view and you should see some auto-generated code like
jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
}
Write the code there.
You should also take some time to read How to write Event Listeners. GUI Programs are event driven, so you need to learn how to respond to these events by registering listeners
the problem is about getSelectedRow();
getSelectedRow is only work if table is current selected
my suggestion is , make temp variable to get last selectedrow to prevent error ,like
if(table.getSelectedRow()!=-1)
{
int lastselected=table.getSelectedRow();
}

Java Checkbox Action

I have a check box and when I create an Action script from the Netbeans' design, it creates a function like;
private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {
total=8.99f;
xc = "XCheese";
exTop++;
calculateTotal(total);
updateTextArea();
}
This works perfectly, but I want to set everything to zero when the jCheckBox1 is unchecked, if I uncheck it the way the code is now, no changes appear.
It is an sample of code. Hope it will help you.
private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {
if(checkBox.isSelected() ){
total=8.99f;
xc = "XCheese";
exTop++;
calculateTotal(total);
updateTextArea();
}else{
// set everything zero here.
}
}
Start by taking a look at How to Use Buttons, Check Boxes, and Radio Buttons
Basically, the ActionListener will be called when ever the check box is selected (checked) or unselected (unchecked). You need to check the state of the check box when ever the method is called.
Take a look at AbstractButton#isSelected which will tell you the (in this case) the checked state of the JCheckBox

Making a label editable depending on a variable in an array

I am making a registration page but I am fairly new to Java, I have a combo box for peoples Titles such as "Mr, Mrs, Miss, etc" one of the options is "Other..." And I have a text field next to the combo box to specify your title, I would like the text field to not be editable unless someone selects "Other..." in the combo box, How would I do this?
What it looks like at the moment:
I can't see what I'm doing wrong?
TitleSpecifyChoiceField.setEditable(false);
TitleSpecifyChoiceField.setText("Please specify title...");
TitleChoice.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Mr", "Mrs", "Miss", "Ms", "Dr", "Other..." }));
TitleChoice.setToolTipText("");
TitleChoice.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e) {
if (TitleChoice.getSelectedItem().equals("Other...")){
TitleSpecifyChoiceField.setEditable(true);
};
You would do this the same way you'd respond to any changes in a JComboBox -- by adding a listener to the JComboBox as per the Swing combo box tutorial. Inside the listener, change the setEnabled(...) setting on the JTextField depending on the selected item. i.e., by calling getSelectedItem() on the JComboBox and testing whether calling equalsIgnoreCase("other") is true.
Note that I recommend that you use setEnabled(...) not setEditable(...) as the former will give the user visual cues as to whether the JTextField should be edited or not.
Edit
Regarding your code:
TitleSpecifyChoiceField.setEditable(false);
TitleSpecifyChoiceField.setText("Please specify title...");
TitleChoice.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Mr", "Mrs", "Miss", "Ms", "Dr", "Other..." }));
TitleChoice.setToolTipText("");
TitleChoice.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e) {
if (TitleChoice.getSelectedItem().equals("Other...")){
TitleSpecifyChoiceField.setEditable(true);
}
}
});
Some problems and issues:
Does your JComboBox use Strings or does it hold other types of items?
You will want to add debugging code into your code to try to isolate the problem. For instance, inside of your ItemListener, add a System.out.println(...) to print out the selected item to be sure that the listener is working as expected.
You are checking if the item .equals("Other..."), a String literal. Instead consider making a String constant, OTHER that the JComboBox uses and that you test in the listener to be sure that the tested String and and the displayed are the same.
Again, I suggest you use setEnabled(...) not setEditable(...).
You should learn and follow Java naming conventions including beginning all variable names with lower case letter as this will help us to better understand your code.
You should fix your posted code indentation so that it is regular and makes sense (note my code above vs yours). Why do you want to make it harder for folks who are trying to help you to understand your code? Your job is to make ours as easy as possible as we're all volunteers.
Create and post an sscce to get the best and fastest help.
Add a listener to the combo box. When the selected item changes, call setEditable() on the text field.
You could try adding an ItemListener to your JComboBox and (as #HovercraftFullOfEels suggested) use setEnabled as opposed to setEditable. For a general idea, you could do something like this:
JTextField textField = ...;
JComboBox<String> comboBox = ...;
comboBox.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent e){
final String selected = (String)comboBox.getSelectedItem();
textField.setEnabled(selected.equals("other"));
}
}
);
Or if you are using Java 8 you could use this:
JTextField textField = ...;
JComboBox<String> comboBox = ...;
comboBox.addItemListener(
e -> {
final String selected = (String)comboBox.getSelectedItem();
textField.setEnabled(selected.equals("other"));
}
);

Java: Getting a checkbox name from a new JFrame

I have a JCheckBox defined as:
JCheckBox NewCB = new JCheckbox();
NewCB.setSelected(false);
NewCB.setMnemonic(KeyEvent.VK_C);
NewCB.addItemListener(this);
This Check Box is using an ItemLisener:
public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
if(source == NewCB) {TEST = "SELECTED"; System.out.println(TEST);}
}
I launch a JFrame when the program starts. If I add this CheckBox to the frame, it works fine. If I open a second JFrame, and add this Check Box to the 2nd frame, and the Object Source no longer works. Is there some other definition I need to make to get the Object source to read the check box name for any open frames?
First of all, you can't add a component to more than one parent; I'm not sure that's your problem though.
The thing you're calling the "name" of the checkbox isn't a property of the checkbox, but rather a property of a variable that points to the checkbox. The difference is important, because there could be many such variables. The checkbox doesn't know anything about the variables that point to it.
Given that, how do we solve the problem? You can set the "action command" of the checkbox, and then check that:
NewCB.setActionCommand("Fred");
// ...
if ("Fred".equals(((JCheckBox) source).getActionCommand())))
// ...

Actionperformed not triggered for JComboBox

I have an ActionListener attached to a JComboBox(uneditable). Once an item from the JComboBox is selected, I have to make the next button in the frame visible.
The skeleton of the code looks like this:
public void actionPerformed(ActionEvent evt)
{
if(evt.getSource()==jComboBox){
if(jComboBox.getSelectedIndex()==-1)
//Display an alert message
else{
nextButton.setVisible(true);
//Do other actions
}
}
}
It is found that actionPerformed is called only when the second, third, fourth (and so on) items are selected. But actionPerformed is not called when the first item is selected the very first time. But if the first item is selected after selecting other items actioPerformed gets called and the code works fine.
This error appears on some systems and doesn't on other systems. Any help in this regard would be appreciated.
Thanks in Advance!!
This is the normal behavour. The ActionEvent is not fired when you reselect the same item. If you want the event to be fired when you create the combo box then your code should be something like:
JComboBox comboBox = new JComboBox(...);
comboBox.setSelectedIndex(-1); // remove automatic selection of first item
comboBox.addActionListener(...);
comboBox.setSelectedIndex(0);
or
JComboBox comboBox = new JComboBox();
comboBox.addActionListener(...);
comboBox.addItem(...);
comboBox.addItem(...);
Seems like you first condition is a little wrong.
If you want to execute certain code if no item is in your JComboBox, you should check content size : jComboBox.getItemCount()==0 instead of jComboBox.getSelectedIndex()==-1, because selected index can depend upon various conditions, while getItemCount() is only 0 when, well, combo box is empty :-)

Categories