I have two JComboBox in a form and I added an ItemListener to them and I should overwrite itemStateChanged(), now I wanna say if the first JComboBox items selected do something and else if the second JComboBox items selected do another thing, but I don't know how? Maybe code can help you.
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange()==ItemEvent.SELECTED)
picture.setIcon(pics[box.getSelectedIndex()]);
}
In the second line of code I don't know how to recognize which JComboBox state has changed.
You can use ItemEvent#getSource()
Example:
public void itemStateChanged(ItemEvent e) {
if(e.getSource() instanceof JComboBox){
JComboBox combo = (JComboBox) e.getSource();
//rest of code
}
Now for distinct combo1 from combo2 , you have 2 options , you can set names to that components like this.
combo1.setName("combo1");
combo2.setName("combo2");
And in the itemListener
if(e.getSource() instanceof JComboBox){
JComboBox combo = (JComboBox) e.getSource();
if("combo1".equals(combo.getName())){
// your code
}
.
.// rest of code
}
Or if you know that they are the same instance, then you can always use ==.
if(combo1 == e.getSource() ){
// your code
}else if (combo2 == e.getSource()){
//code for combo 2
}
There are two ways to do that, the first is to check the source on the event object and see which combo box it matches to.
The alternative is to add a different listener into each combo box, then you know that any calls going into one listener are from the corresponding control. This is a good use for an anonymous inner class.
Related
I am making a Basic calculator app in java which has 2 JTextFields and 1 JComboBox. What i want to know if there is a way to let a JButton detect what you selected in the JComboBox, when i did it with the text field it looked something like this
static String divide = "/";
if (n == JOptionPane.OK_OPTION) {
if (symbol.getText().equals(divide)){
<code>
}
}
So is there a similar way to do this with JComboBoxs??
String[] symbols = {times, minus, plus, divide};
That's the JComboBox's content code.
You can get selected item from JComboBox with method .getSelectedItem().
Say you have String[] symbols = {times, minus, plus, divide}; as an input when constructing JComboBox (see constructor JComboBox(E[] items) )
JComboBox jcb = new JComboBox(symbols);
//you will see the string you selected
System.out.println(jcb.getSelectedItem());
Perhaps use action listener
String[] quantities1 = {"/","+"};
JComboBox comboBox = new JComboBox(quantities1);
comboBox.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
//do stuff when a section is performed
//you can use comboBox.getSelectedItem() to get the selected value
}
}
);
I've got two JComboBox. First one has model with elements "one", "two", "three" and second has model with elements "three", "four". And when user choose element "three" in first JComboBox, he can't choose element "three" in second one JComboBox. And in reverse - when user choose element "three" in second one JComboBox, he can't choose same element in first one CB. How can i do this in Java ?
Thank you for answers.
One more question. When i dynamically create ComboBoxes (when someone clicked the button - in button actionListener), and every new ComboBox has same model - same list of elements. How can i check this case ? Same like Blip said ?
In my opinion you could add ItemListener to the 2 JComboBox. If the user selects the object "three" in any of the JComboBox then the object "three" could be removed from the other JComboBox's model. And if the user deselects the object "three" in one JComboBox then the object "three" can be added to the model of the other JComboBox.
You could implement in the following way:
Lets have have the two JComboBox stored in variables box1 and box2 which could be implemented as :
JComboBox<String> box1 = new JComboBox<>(new String[]{"one", "two", "three"});
JComboBox<String> box2 = new JComboBox<>(new String[]{"three", "four"});
Now add itemListener to both these JComboBox and pass it to a method say boxItemSelected:
box1.addItemListener(new ItemListener(){
itemStateChanged(ItemEvent e){
boxItemSelected(e);
}
});
box2.addItemListener(new ItemListener(){
itemStateChanged(ItemEvent e){
boxItemSelected(e);
}
});
Now to implement the boxItemSelected(e)
void boxItemSelected(ItemEvent e){
//Check the item selected/deselected is "three" else do nothing.
if (e.getItem().equals("three")){
//Find the box on which this action was not performed to change its model.
JComboBox<String> oppositeBox;
if(e.getSource().equals(box1)){
oppositeBox = box2;
}else{
oppositeBox = box1;
}
//Check the item is selected or deselected to remove or add "three" to item list.
if(e.getStateChange() == ItemEvent.SELECTED){
oppositeBox.removeItem("three");
}else{
oppositeBox.addItem("three");
}
}
}
Addition Information
Here if you have more than 1 items that are overlapping and can be selected only in one JComboBox, a slight modification of the method boxItemSelected could be take care of your problem as Illustrate below:
Change the line in the above code from:
if (e.getItem().equals("three"))
to
if (e.getItem().equals("three") || e.getItem().equals("<new item>") || ....)
And change
oppositeBox.removeItem("three");
oppositeBox.addItem("three");
to
oppositeBox.removeItem(e.getItem());
oppositeBox.addItem(e.getItem());
Here under any circumstance the user cannot select the same items in both the JComboBox. And all these happen behind the scene without the knowledge of the user using the user-interface.
When i dynamically create ComboBoxes (when someone clicked the button
- in button actionListener), and every new ComboBox has same model - same list of elements. How can i check this case ? Same like Blip said
?
In response to the above I am considering that all the items in all the JComboBox same and are stored in a List variable, and if 1 item is selected in any one of the JComboBox then that item cannot be selected in rest of the JComboBox. If my assumption is correct, then I suggest you do the following:
Create a List<JComboBox<?>> say boxes and initialise it as below:
List<JComboBox<?>> boxes = new ArrayList<>();
In your JButton (the button that dynamically JComboBox) variable's ActionListener implementation create a variable say items as an instance of List to store the items of the JComboBox and add the items
List<String> items = new Vector<>();
items.add("One");
items.add("Two");
......
Now remove the items from from the items variable that are selected in other JComboBox that are dynamically generated:
Iterator<JComboBox<?>> iterator = boxes.iterator();
while(iterator.hasNext()){
JComboBox<?> existing = iterator.next();
items.remove(existing.getSelectedItem());
}
Now after initialisation of the JComboBox instance say box set the Model of the box to the previously initialised and trimmed List variable items
box.setModel(new DefaultComboBoxModel(items));
now add the JComboBox variable box to the List variable boxes:
boxes.add(box);
Also in this above mentioned ActionListener implementation add the ItemListener to box, the newly instantiated variable of JComboBox and pass it to the method boxItemSelected:
box.addItemListener(new ItemListener(){
itemStateChanged(ItemEvent e){
boxItemSelected(e);
}
});
Now the implementation of the boxItemSelected has to be changed to accommodate the changes:
void boxItemSelected(ItemEvent e){
//Create an iterator to iterate over the boxes
Iterator<JComboBox<?>> iterator = boxes.iterator();
while(iterator.hasNext()){
//Get the current instance of comboBox from the list
JComboBox<?> current = iterator.next();
//If the box in which the select or de-select
//event has occurred is the current comboBox then do nothing.
if(e.getSource().equals(current)(
continue;
}
//If the event is select then remove the Item from the
//current comboBox else add the Item to the current comboBox.
if(e.getStateChange() == ItemEvent.SELECTED){
current.removeItem(e.getItem());
}else{
current.addItem(e.getItem());
}
}
}
So this is definitely possible. The best way I think would be to check the selected index of both boxes and then perform your logic based on the results of that index value. In the example below you can see that demonstrated. What is happening is there is an ActionListener on ComboBox1 and 2. If the values match, I used index but you can also get the string value to make sure they don't match up.
public class SOF extends JFrame {
private JPanel mainPanel, comboPanel;
private JComboBox jcb1, jcb2;
public SOF()
{
super("Combo Box Example");
mainPanel = new JPanel();
mainPanel.add(configureCombo());
add(mainPanel);
setSize(200,200);
setLocationRelativeTo(null);
setVisible(true);
jcb1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
//You can replace this with, jcb2.getSelectedItem if you don't know the indexes or if they will be random.
if((jcb1.getSelectedIndex() == 2) && (jcb2.getSelectedIndex() == 0))
{
JOptionPane.showMessageDialog(null, "Cannot select 3 in both field.");
jcb1.setSelectedIndex(-1);
jcb2.setSelectedIndex(-1);
}
//ANOTHER OPTION
If((jcb1.getSelectedValue().equals("three") && (jcb2.getSelectedValue().equals("three")
{
LOGIC
}
}
});
jcb2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
//You can replace this with, jcb2.getSelectedItem if you don't know the indexes or if they will be random.
if((jcb2.getSelectedIndex() == 0) && (jcb1.getSelectedIndex() == 2))
{
JOptionPane.showMessageDialog(null, "Cannot select 3 in both field.");
jcb1.setSelectedIndex(-1);
jcb2.setSelectedIndex(-1);
}
}
});
}
private JPanel configureCombo()
{
String[] cb1List = {"one", "two", "three"};
String[] cb2List = {"three", "four"};
comboPanel = new JPanel(new GridLayout(1,2));
jcb1 = new JComboBox(cb1List);
jcb2 = new JComboBox(cb2List);
comboPanel.add(jcb1);
comboPanel.add(jcb2);
return comboPanel;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
SOF s = new SOF();
}
}
On either one if matching boxes are selected an error message will pop up and deselect both comboboxes.
You could futz with the combobox's model, but easier would be to just check the selected values when the user asks the program to accept the values, perhaps in the ActionListener of a JButton, and then if two of the same values have been selected, deselect them and warn the user with a JOptionPane. Alternatively, you could have code in listeners (either Actionlistener or ItemListener) added to both JComboBox's that check the other combobox's selected value to make sure that they are not the same, and if so, warn the user and deselect the erroneous selection.
I need a listener on a CombobBox which is a cellEditor on a JTable.
This listener must give me the new selected value and the row id.
Problem with my below solution is that the listner is linked to all rows, so when I change one ComboBox value in one row, then move to another row (with a different combo value) an event is raised, but the selected row has not yet changed. How can I get rid of this case ?
Thanks
column = jTableCheck.getColumnModel().getColumn(9);
JComboBox comboBox = new JComboBox(comboGenre);
comboBox.addItemListener(new ItemListener(){
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
int row = jTableCheck.getSelectedRow();
Popup.info(e.getItem() + " SELECTED, row="+row);
}
}
});
column.setCellEditor(new DefaultCellEditor(comboBox));
Don't use an ItemListener on the combo box.
Instead you should be using a TableModelListener. An event will be fired whenever the data in the TableModel is changed. So you add the TableModelListener to the TableModel of your JTable.
The TableModelEvent will give your row/column of the cell that changed. You can get the changed value from the TableModel.
Or maybe you would want to use a Table Cell Listener which is similar to the TableModelListener except the code is only invoked when the value is actually changed and you use an Action to do the processing.
In fact, I already used a TableCellListener on another table, but forgot about that!
I found out a usefull class here: http://tips4java.wordpress.com/2009/06/07/table-cell-listener/
So I want to have a JMenu Level with three JCheckBoxMenuItem like Easy, normal and expert.
Of course, only one can be checked and if one is checked, it can't be unchecked (enabled(false)) because it's the only one.
I want when one JCheck is checked, all others are unchecked.
So it seems easy, but the only solution I found is to do it with a lot of "if" conditions.
Is there a way to do it with a better algorithm ?
It sounds like you'd be better off using a JRadioButton since check boxes are generally used for multiple-choice options and radio buttons for a single selection out of many. JRadioButtons can be grouped together using a ButtonGroup which allows only one selected at a time.
public void stateChanged(ChangeEvent e) {
if (e.getSource() == cb1 && cb1.isSelected()) {
cb2.setSelected(false);
cb3.setSelected(false);
} else if (e.getSource() == cb2 && cb2.isSelected()) {
cb3.setSelected(false);
cb1.setSelected(false);
} else if (e.getSource() == cb3 && cb3.isSelected()) {
cb1.setSelected(false);
cb2.setSelected(false);
}
}
i just put all my JCheckBoxMenuItems in an array
and every time i select a JCheckBoxMenuItem i call this method
public void clearCheckBoxes(){
for (JCheckBoxMenuItem arrayCB1 : arrayCB) {
if (arrayCB1 != cb) {
arrayCB1.setSelected(false);
} else {
arrayCB1.setSelected(true);
}
}
}
The annoying part was having to manualy put them in the array,maybe the jMenu class has a method that returns the complete array but i didnt bother looking
arrayCB[0]=bridgeCB;
arrayCB[1]=swampCB;
arrayCB[2]=flowerCB;
arrayCB[3]=MountainCB;
arrayCB[4]=Mountain2CB;
arrayCB[5]=forestCB;
arrayCB[6]=parisCB;
arrayCB[7]=roadCB;
arrayCB[8]=waveCB;
arrayCB[9]=lakeCB;
just in case , this is how you create the array
JCheckBoxMenuItem [] arrayCB=new JCheckBoxMenuItem[10];
i dont know about that lots of if statements way of doing it
I am working on Java swing application using data base with MySQL
I need to know if I can deactivate components until select an element from JComboBox? I must know the choice of the 1st jcombobox to fill the 2nd JComboBox; the 1st choice is a foreign key on the 2nd, like that :
ResultSet res = st.executeQuery("SELECT NomF FROM famille_de_type");
while (res.next()) {
comboBox_Fam_innewT.addItem(res.getString(1));
}
this is my example :
Of course, you can. When you start work call setEnabled(false) to second comboBox. And add to 1st combobox ItemListener. It will be listen item selection.
firstComboBox.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
if (e.getStateChange()==ItemEvent.SELECTED)
{
Object selectedItem = e.getItem(); // new item selected
// TODO select values for 2nd combobox
// TODO fill 2nd combobox
secondComboBox.setEnabled(true);
}
}
});
So in the ActionListenr of the JComboBox, simply call the setEnabled methods, passing false to disable them, or true to enable them
I need to know if i can deactivate components until select an element from jcombobox ?
YES. Why not Component.SetEnabled(false)?
Also you might want to look at ItemListener interface to achieve your goal. Here is more about Handling Events on a Combo Box.