making sure JCombo actions only execute on initial selection? - java

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());
}
});
}

Related

Checkbox disabled Combobox in Java [duplicate]

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);
}
}

Swing Jcombobox set first element as default selected

String[] bookArray={"a","b","c"};
JComboBox bookComboBox = new JComboBox(bookArray);
bookComboBox.setSelectedIndex(0);
bookComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox cb= (JComboBox) e.getSource();
bookNameSelected=(String) cb.getSelectedItem();
System.out.println("book name selected:"+bookNameSelected);
}
});
First element of drop down is shown as default but not passed as default selected value if user does not select any value.
Move bookComboBox.setSelectedIndex(0); after the registration of the ActionListener, this allows the ActionListener to be triggered and sets the bookNameSelected
String[] bookArray = {"a", "b", "c"};
JComboBox bookComboBox = new JComboBox(bookArray);
bookComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
bookNameSelected = (String) cb.getSelectedItem();
System.out.println("book name selected:" + bookNameSelected);
}
});
bookComboBox.setSelectedIndex(0);

ComboBox with ActionListener and if-statement

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".

case sensitive jcombobox

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);
}

ComboBox - printing out the selected item

I am a little stuck. I can't figure out a much bigger problem than this, so I am going to the roots to eventually build my way up!
I can't print the selected item in the combo box, currently I have an ActionListener for it:
box.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
myBox(evt);
}
});
...
protected void myBox(ActionEvent evt)
{
if(myBoxName.getSelectedItem().toString() != null)
System.out.println(myBoxName.getSelectedItem().toString());
}
I would expect this to print out to the console every time I change the selected item, but it doesn't. This should be so easy though!
Thanks
I just tried your code and it works fine. Whenever I change selection, the selected text is written to System.out.
The only thing I changed was the check for myBoxName.getSelectedItem().toString() != null, I check for myBoxName.getSelectedItem() != null instead. This should not be related to your problems though.
public class ComboBoxTest {
private JComboBox comboBox = new JComboBox(
new DefaultComboBoxModel(new String[] { "Test1", "Test2", "Test3" }));
public ComboBoxTest() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(200, 100);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
myBox(evt);
}
});
frame.getContentPane().add(comboBox);
frame.setVisible(true);
}
protected void myBox(ActionEvent evt) {
if (comboBox.getSelectedItem() != null) {
System.out.println(comboBox.getSelectedItem().toString());
}
}
}

Categories