How can I make the comboBox available when the checkBox was uncheck (vice versa)
Why the comboBox is still disable after I unChecked the checkBox?
choice [] = {"A","B","C"};
JComboBox a = new JComboBox(choice);
JCheckBox chk = new JCheckBox("choice");
...
a.addActionListener(this);
chk.addActionListener(this);
...
public void actionPerformed(ActionEvent e) {
//disable the a comboBox when the checkBox chk was checked
if(e.getSource()==chk)
a.setEnabled(false);
//enable the a comboBox when the checkBox chk was unchecked
else if(e.getSource()!=chk)
a.setEnabled(true);
}
If I understand you correctly I think all that you need to do is to change the enabled state of the combo box based on the current value of the checkbox:
public void actionPerformed(ActionEvent e) {
if (e.getSource()==chk) {
a.setEnabled(chk.isSelected());
}
}
I have a similar set up, and I use an Item Listener, like so:
CheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange()==ItemEvent.SELECTED){
ComboBox.setEnabled(true);
}else if(e.getStateChange()==ItemEvent.DESELECTED){
ComboBox.setSelectedIndex(-1);
ComboBox.setEnabled(false);
}
}
});
This way the behaviour is different when selected and deselected.
I treid this and worked..
public class JF extends JFrame implements ActionListener {
String choice [] = {"A","B","C"};
JComboBox a = new JComboBox(choice);
JCheckBox chk = new JCheckBox("choice");
JF()
{
this.add(a, BorderLayout.NORTH);
this.add(chk, BorderLayout.CENTER);
setDefaultCloseOperation(EXIT_ON_CLOSE);
a.addActionListener(this);
chk.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
//NOTE THE FOLLOWING LINE!!!!
if(e.getSource()==chk)
a.setEnabled(chk.isSelected());
}
public static void main(String[] args) {
new JF().setVisible(true);
}
}
Your old code didn't work because, even unchecking a checkbox triggers the event. The source of the trigger is the checkbox.. so both while checking and unchecking the event source was chk
if (e.getSource() == chckbxModificar) {
if (chckbxModificar.isSelected()) {
cbxImpuesto.setEnabled(true);
cbxMoneda.setEnabled(true);
txtPorcentaje.setEditable(true);
txtSimbolo.setEditable(true);
} else {
cbxImpuesto.setEnabled(false);
cbxMoneda.setEnabled(false);
txtPorcentaje.setEditable(false);
txtSimbolo.setEditable(false);
}
}
I need to use a JCombo box and at the moment I am just printing messages to screen for testing. When I make a selection it works as expected, however when I then re-click the combo box to change selection I get the same message box before it lets me make another selection. How would I get it so that the action is only performed on initial selection?
String[] positions={"1","2","3","4"};
JComboBox combo = new JComboBox<String>(positions);
combo.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae ){
//Display selected stuff
JOptionPane.showMessageDialog(null, combo.getSelectedItem());
}
});
Use a boolean to know if it has already been checked or not.
Solution
String[] positions={"1","2","3","4"};
JComboBox combo = new JComboBox<String>(positions);
combo.addActionListener(new ActionListener(){
boolean comboAlreadyChecked = false;
#Override
public void actionPerformed(ActionEvent ae ){
//Display selected stuff
if (!comboAlreadyChecked){
JOptionPane.showMessageDialog(null, combo.getSelectedItem());
comboAlreadyChecked = true;
}
}
});
PS : The name of your boolean may be a little easier than this one. This is just to clarify.
After taking onboard the answers provided and through modifying the solution given in the aforementioned tutorial, I came up with the following solution:
String labels[] = {"", "A", "B", "C", "D", "E", "F"};
JComboBox comboBox = new JComboBox(labels);
ItemListener itemListener = new ItemListener() {
public void itemStateChanged(ItemEvent itemEvent) {
int state = itemEvent.getStateChange();
ItemSelectable is = itemEvent.getItemSelectable();
if (selectedString(is) == "A" & state == ItemEvent.SELECTED) {
System.out.println("A");
}
}
};
comboBox.addItemListener(itemListener);
Please try this
public static void main(String args[]) {
JComboBox comboBox = new JComboBox();
comboBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
System.err.println("new item: " + e.getItem());
}
});
}
I'm trying to add an ActionListener to my ComboBox. I want to open a form when a item is selected from the box. I successfully implemented it on a JButton but I can't figure out how to do it in a combobox. Can someone please help me out?
JComboBox<String> valBox = new JComboBox<>();
valBox.addItem("Apparat");
valBox.addItem("Smycke");
valBox.addItem("Aktie");
södra.add(valBox);
valBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (valBox.getSelectedIndex() == 0)
nyLyss.ApparatForm.form1();
}
});
The code that I wan't to execute when the first item is selected is this one:
class nyLyss implements ActionListener{
public void actionPerformed(ActionEvent ae) {
try{
ApparatForm form1 = new ApparatForm();
int svar = JOptionPane.showConfirmDialog(Layout.this, form1);
if(svar != JOptionPane.OK_OPTION)
return;
String namn = form1.getNamn();
int inköpspris = form1.getPris();
int slitage = form1.getPris();
// saker ap = new saker(namn, inköpspris, slitage);
// alla.add(ap);
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(Layout.this, "Felaktig indata!");
}
}
}
Thanks! :)
I would solve the problem with a ItemStateChanged listener on my combobox. Here a short example with a combobox called "mycombobox".
private void mycomboboxItemStateChanged(java.awt.event.ItemEvent evt) {
System.out.println(mycombobox.getSelectedItem());
}
The result is, that the application is printing out the selected item after every change of the selected item in the combobox "mycombobox".
My problem is a bit tricky. I am using an Editable JComboBox. It may contain case sensitive items. For example, it may have Item1 and item1. So, these two items should be treated as different in my case.
But the problem is, these two items is treated as same. No matter which Items I have selected, it always select the first one (Item1). I've searched in Google, but didn't find any solution. That's why, I am here.
Code:
//loading of Items
jdcbmItemType = new javax.swing.DefaultComboBoxModel(ItemTypeHandler.getItemTypeComboData(MainFrame.companyId));
private void jcbItemTypeMouseReleased(MouseEvent evt)
{
if (jcbItemType.getSelectedIndex() != -1)
{
loadItemTypeDetails(((ItemObject) jcbItemType.getSelectedItem()).getId());
}
else
{
resetFields();
}
}
public static Vector<ItemObject> getItemTypeComboDataV(BigInteger companyId, BigInteger categoryId, boolean addFirstElement, TriState deleted) throws ExceptionWrapper, EJBException
{
try
{
return (Vector<ItemObject>)lookupItemTypeFacade().getItemTypeComboData(companyId, categoryId, addFirstElement, deleted);
} catch (ExceptionWrapper exceptionWrapper)
{
throw exceptionWrapper;
} catch (EJBException ejbEx)
{
throw ejbEx;
} catch (Exception ex)
{
throw new ExceptionWrapper(ex.getMessage());
}
}
ItemObject is a customClass where one field is BigInteger and another is String.
getItemTypeComboData is functioning properly. So, you can assume to get a list of ItemObject from here and it will nicely convert it to Vector<ItemObject>
jcbItemType.getSelectedIndex() always return the same index for Item1 and item1. But it returns different index for item2.
I know, it would be better if I can use itemStateChanged event. But in my case, I can't use it. But my question is, MouseReleased and FocusLost works fine for different name string but not same string with different case. I am really stumbled.
Another way to ask the question:
Does MouseReleased or FocusLost event check for case-sensitive items?
How to resolve this problem?
Thanks.
Here is my SSCCE and this works fine , If this is not what youre looking for, then post your SSCCE for better sooner help!
import javax.swing.*;
import java.awt.event.*;
public class ComboBoxTest {
JComboBox combo;
JTextField txt;
public static void main(String[] args) {
new ComboBoxTest();
}
public ComboBoxTest() {
String items[] = {"Item1", "item1"};
JFrame frame = new JFrame("JComboBox Case-sensitivity Test");
JPanel panel = new JPanel();
combo = new JComboBox(items);
combo.setEditable(true);
txt = new JTextField(10);
panel.add(combo);
panel.add(txt);
frame.add(panel);
combo.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent ie) {
String str = (String) combo.getSelectedItem();
txt.setText(str);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 100);
frame.setVisible(true);
}
}
I think you are doing like this :-
String[] items = {"item1", "item2"};
JComboBox cb = new JComboBox(items);
cb.setEditable(true);
Now you have to access the JCombobox elements which you have insert into this as in array form like this:-
MyItemListener actionListener = new MyItemListener();
cb.addItemListener(actionListener);
class MyItemListener implements ItemListener {
// This method is called only if a new item has been selected.
public void itemStateChanged(ItemEvent evt) {
JComboBox cb = (JComboBox)evt.getSource();
// Get the affected item
Object item = evt.getItem();
if (evt.getStateChange() == ItemEvent.SELECTED) {
// Item was just selected
} else if (evt.getStateChange() == ItemEvent.DESELECTED) {
// Item is no longer selected
}
}
}
After adding the itemListener you can do your different tasks with individual JCombobox Item
Try this, it works fine...
use ActionListener() to capture the click... then use getSelectedItem() to capture the item clicked on the JComboBox
try this,
check in your console for the output
myComboBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent ie) {
String str = (String) myComboBox.getSelectedItem();
System.out.println(str);
}
I'm using a JComboBox with an ItemListener on it. When the value is changed, the itemStateChanged event is called twice. The first call, the ItemEvent is showing the original item selected. On the second time, it is showing the item that has been just selected by the user. Here's some tester code:
public Tester(){
JComboBox box = new JComboBox();
box.addItem("One");
box.addItem("Two");
box.addItem("Three");
box.addItem("Four");
box.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
System.out.println(e.getItem());
}
});
JFrame frame = new JFrame();
frame.getContentPane().add(box);
frame.pack();
frame.setVisible(true);
}
So when I changed the Combo box once from "One" to "Three" the console shows:
One
Three
Is there a way I can tell using the ItemEvent maybe, that it's the second item (ie. the user selected item)? And if someone can explain why it gets called twice, that would be nice too!
Thanks
Have a look at this source:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Tester {
public Tester(){
JComboBox box = new JComboBox();
box.addItem("One");
box.addItem("Two");
box.addItem("Three");
box.addItem("Four");
box.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
System.out.println(e.getItem() + " " + e.getStateChange() );
}
});
JFrame frame = new JFrame();
frame.getContentPane().add(box);
frame.pack();
frame.setVisible(true);
}
public static void main(String [] args) {
Tester tester = new Tester();
}
}
Use the getStateChange to determine if an item is selected or deselected
According to this thread,
It gets tripped when you leave one result and then called again when set to another result
Don't listen for itemStateChanged. Use an ActionListener instead, which is good for handling events of the combo.
You need a ItemStateListener if you need to separately handle deselection / selection depending on the item involved.
Changing the state of the item within itemStateChanged causes itemStateChanged to be fired... this called "reentrance".
I wanted to get the index string after selected and set in combobox
comboBox1.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
comboBox1ItemStateChanged();
}
}
});
Yo can do it like this:
import java.awt.event.*;
jComboBox1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Hello");
}
});
private void dropDown_nameItemStateChanged(java.awt.event.ItemEvent evt) {
if(evt.getStateChange() == ItemEvent.SELECTED)
{
String item = (String) evt.getItem();
System.out.println(item);
}
}
Good Luck!
The code is:
public class Tester {
private JComboBox box;
public Tester() {
box = new JComboBox();
box.addItem("One");
box.addItem("Two");
box.addItem("Three");
box.addItem("Four");
box.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == 1) {
JOptionPane.showMessageDialog(box, e.getItem());
System.out.println(e.getItem());
}
}
});
JFrame frame = new JFrame();
frame.getContentPane().add(box);
frame.pack();
frame.setVisible(true);
}
}
Have a look here,
box.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(e.getStateChange()== ItemEvent.SELECTED) {
//this will trigger once only when actually the state is changed
JOptionPane.showMessageDialog(null, "Changed");
}
}
});
When you select a new option, it will only once call the JOptionPane, indicating that the code there will be called once only.
Quote from Java Tutorial:
"Only one item at a time can be selected in a combo box, so when the user makes a new selection the previously selected item becomes unselected. Thus two item events are fired each time the user selects a different item from the menu. If the user chooses the same item, no item events are fired."
When the anyitem is selected from the combo box, it internally triggers selection change, i.e. it will call the function setSelectedItem.
If an explicit itemStateChanged event listener is implemented, the setSelectedItem will call itemStateChanged. So, when an item is selected it calls setSelectedItem then it calls itemStateChanged.
As the value of the combo box changes, even that too triggers itemStateChanged and hence itemStateChanged gets called.
I had written listener for item change to handle change in value of combo box when set internally from the code and that caused the function getting called twice.
Here are the 2 back traces, which gets invoked when a value is selected from combo box.
1st time on actual value change:
dataMgr.MainInterface.jComboBoxPaymentStatusValueChangeHandle(MainInterface.java:1431),
dataMgr.MainInterface.jComboBoxPaymentStatusItemStateChanged(MainInterface.java:1676),
dataMgr.MainInterface.access$600(MainInterface.java:28),
dataMgr.MainInterface$7.itemStateChanged(MainInterface.java:437),
javax.swing.JComboBox.fireItemStateChanged(JComboBox.java:1223),
javax.swing.JComboBox.selectedItemChanged(JComboBox.java:1271),
javax.swing.JComboBox.contentsChanged(JComboBox.java:1330),
javax.swing.AbstractListModel.fireContentsChanged(AbstractListModel.java:118),
javax.swing.DefaultComboBoxModel.setSelectedItem(DefaultComboBoxModel.java:93),
javax.swing.JComboBox.setSelectedItem(JComboBox.java:576), javax.swing.JComboBox.setSelectedIndex(JComboBox.java:622), javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(BasicComboPopup.java:852), java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:290), java.awt.Component.processMouseEvent(Component.java:6533), javax.swing.JComponent.processMouseEvent(JComponent.java:3324), javax.swing.plaf.basic.BasicComboPopup$1.processMouseEvent(BasicComboPopup.java:501), java.awt.Component.processEvent(Component.java:6298), java.awt.Container.processEvent(Container.java:2236), java.awt.Component.dispatchEventImpl(Component.java:4889), java.awt.Container.dispatchEventImpl(Container.java:2294), java.awt.Component.dispatchEvent(Component.java:4711), java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888), java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525), java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466), java.awt.Container.dispatchEventImpl(Container.java:2280), java.awt.Window.dispatchEventImpl(Window.java:2746), java.awt.Component.dispatchEvent(Component.java:4711), java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758), java.awt.EventQueue.access$500(EventQueue.java:97), java.awt.EventQueue$3.run(EventQueue.java:709), java.awt.EventQueue$3.run(EventQueue.java:703), java.security.AccessController.doPrivileged(Native Method), java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76), java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86), java.awt.EventQueue$4.run(EventQueue.java:731), java.awt.EventQueue$4.run(EventQueue.java:729), java.security.AccessController.doPrivileged(Native Method), java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76), java.awt.EventQueue.dispatchEvent(EventQueue.java:728), java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201), java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116), java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105), java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101), java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93), java.awt.EventDispatchThread.run(EventDispatchThread.java:82)]
2nd time from the due to operation on combobox
dataMgr.MainInterface.jComboBoxPaymentStatusValueChangeHandle(MainInterface.java:1431),
dataMgr.MainInterface.jComboBoxPaymentStatusItemStateChanged(MainInterface.java:1676),
dataMgr.MainInterface.access$600(MainInterface.java:28),
dataMgr.MainInterface$7.itemStateChanged(MainInterface.java:437),
javax.swing.JComboBox.fireItemStateChanged(JComboBox.java:1223),
javax.swing.JComboBox.selectedItemChanged(JComboBox.java:1280),
javax.swing.JComboBox.contentsChanged(JComboBox.java:1330),
javax.swing.AbstractListModel.fireContentsChanged(AbstractListModel.java:118),
javax.swing.DefaultComboBoxModel.setSelectedItem(DefaultComboBoxModel.java:93),
javax.swing.JComboBox.setSelectedItem(JComboBox.java:576),
javax.swing.JComboBox.setSelectedIndex(JComboBox.java:622),
javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(BasicComboPopup.java:852),
java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:290),
java.awt.Component.processMouseEvent(Component.java:6533),
javax.swing.JComponent.processMouseEvent(JComponent.java:3324),
javax.swing.plaf.basic.BasicComboPopup$1.processMouseEvent(BasicComboPopup.java:501),
java.awt.Component.processEvent(Component.java:6298), java.awt.Container.processEvent(Container.java:2236),
java.awt.Component.dispatchEventImpl(Component.java:4889), java.awt.Container.dispatchEventImpl(Container.java:2294),
java.awt.Component.dispatchEvent(Component.java:4711), java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888),
java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525), java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466),
java.awt.Container.dispatchEventImpl(Container.java:2280), java.awt.Window.dispatchEventImpl(Window.java:2746),
java.awt.Component.dispatchEvent(Component.java:4711), java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758),
java.awt.EventQueue.access$500(EventQueue.java:97), java.awt.EventQueue$3.run(EventQueue.java:709),
java.awt.EventQueue$3.run(EventQueue.java:703), java.security.AccessController.doPrivileged(Native Method),
java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76),
java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86),
java.awt.EventQueue$4.run(EventQueue.java:731), java.awt.EventQueue$4.run(EventQueue.java:729),
java.security.AccessController.doPrivileged(Native Method), java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76), java.awt.EventQueue.dispatchEvent(EventQueue.java:728), java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201), java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116), java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105), java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101), java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93), java.awt.EventDispatchThread.run(EventDispatchThread.java:82)]
JComboBox.setFocusable(false) will do the trick.