case sensitive jcombobox - java

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

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

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

multiple JComboBox in one JPanel

I have a JPanel with three JComboBox. Here is the code I wrote:
public class Main {
private static String pat_order;
private static String PS_selection;
private static String ovlp_selection;
public static void main(String args[]) throws FileNotFoundException, IOException {
Date start_time = new Date();
try {
GridBagConstraints gbc = new GridBagConstraints();
final JComboBox jc = new JComboBox();
jc.addItem("ARR");
jc.addItem("SRR");
final JComboBox jc1 = new JComboBox();
jc1.addItem("RR");
jc1.addItem("IQC");
final JComboBox jc2 = new JComboBox();
jc2.addItem("YES");
jc2.addItem("NO");
JPanel myPanel = new JPanel(new GridBagLayout());
myPanel.add(jc, gbc);
myPanel.add(jc1, gbc);
myPanel.add(jc2, gbc);
jc.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
String order = (String) jc.getSelectedItem();
pat_order = order;
}
});
jc1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
String PS_method = (String) jc1.getSelectedItem();
PS_selection = PS_method;
}
});
jc2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
String ovlp_user = (String) jc2.getSelectedItem();
ovlp_selection = ovlp_user;
}
});
if (pat_order == "ARR") {
Arrays.sort(patterns_array, new ColumnComparator(0));
} else if (pat_order == "SRR") {
Arrays.sort(patterns_array, new ColumnComparator(1));
}
if (PS_selection == "RR") {
System.out.println("RR");
} else if (PS_selection == "IQC") {
System.out.println("IQC");
}
if (ovlp_selection == "YES") {
Overlap a = new Overlap(Xdisc, final_patterns, k, Yresid, Xresid, projectname, pat_order, PS_selection);
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
} finally {
}
}
}
The problem is that the first JComboBox is working fine, but the second and third is doing nothing. It would be great if you can help me in this problem.
You seem to be running your UI as if it was a console program. UI's don't work this way, they respond to events. These events may come in any order and at any time...
Dialogs are a great way of control the flow of the execution. They will block code until the dialog is closed, allowing you to ascertain the results and take appropriate action.
Take a look at How to use dialogs for more details...
While you there, you might also want to take a look through Creating a UI with Swing which will explain more of the concepts you need to understand.
Like the fact that a UI needs some kind of Window in order to be displayed on the screen
Try to add ActionListener instead of ItemListener

How can i make an event to a JComboBox which triggers AFTER selection?

I want to make an event which will be triggered after i make the selection to the JComboBox.
the problem I'm now facing is that when i added an ActionListener, it was triggered when the user clicked on the box but BEFORE he actually chose the new item, thus the action listener was activated all the time on the previous value which was selected in the box. what i want to do is simply changing the title of an JTextArea according to the selection.
I tried doing something like this:
jBox.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
String alt = GetAlgoAreaTitleByChoice();
panel.remove(jArea);
currentBest = setArea("",alt);
currentBest.setBounds(50, 350, 1000, 290);
panel.add(jArea);
}
});
and the method inside:
private String GetArgsAreaTitleByChoice(){
String chi = jBox.getSelectedItem().toString();
if(chi.equals(generalChoice)){
return "Hello";
}
else if(chi.equals(algoChoice)){
return "World";
}
else if(chi.equals(argsChoice)){
return "Hello";
}
return null;
}
I've tried using the SELECTED events now like this:
public void itemStateChanged(ItemEvent e) {
JComboBox cb = (JComboBox)e.getSource();
// Get the affected item
String item = cb.getSelectedItem().toString();
if (e.getStateChange() == ItemEvent.SELECTED) {
panel.remove(jBox);
textArea = setArea("", item);
panel.add(jBox);
}
but it seems to remove the area from the panel without adding it back... why is this happening?
Here is a simple demonstration with a sample code :
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.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(e.getStateChange()==ItemEvent.SELECTED){
e.getItem(); //Do what ever you want :))
}
}
});
JFrame frame = new JFrame();
frame.getContentPane().add(box);
frame.pack();
frame.setVisible(true);
}
public static void main(String [] args) {
Tester tester = new Tester();
}
}
For listening of events from JComboBox is better implements ItemListener, returns two events SELECTED/DESELECTED
EDIT
if you remove/add JComponent(s) on Runtime and in already visible container, then you have to call (as least code lines)
revalidate();
repaint();

JComboBox Selection Change Listener?

I'm trying to get an event to fire whenever a choice is made from a JComboBox.
The problem I'm having is that there is no obvious addSelectionListener() method.
I've tried to use actionPerformed(), but it never fires.
Short of overriding the model for the JComboBox, I'm out of ideas.
How do I get notified of a selection change on a JComboBox?**
Edit: I have to apologize. It turns out I was using a misbehaving subclass of JComboBox, but I'll leave the question up since your answer is good.
It should respond to ActionListeners, like this:
combo.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
doSomething();
}
});
#John Calsbeek rightly points out that addItemListener() will work, too. You may get 2 ItemEvents, though, one for the deselection of the previously selected item, and another for the selection of the new item. Just don't use both event types!
Code example of ItemListener implementation
class ItemChangeListener implements ItemListener{
#Override
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
Object item = event.getItem();
// do something with object
}
}
}
Now we will get only selected item.
Then just add listener to your JComboBox
addItemListener(new ItemChangeListener());
I would try the itemStateChanged() method of the ItemListener interface if jodonnell's solution fails.
Here is creating a ComboBox adding a listener for item selection change:
JComboBox comboBox = new JComboBox();
comboBox.setBounds(84, 45, 150, 20);
contentPane.add(comboBox);
JComboBox comboBox_1 = new JComboBox();
comboBox_1.setBounds(84, 97, 150, 20);
contentPane.add(comboBox_1);
comboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
//Do Something
}
});
You may try these
int selectedIndex = myComboBox.getSelectedIndex();
-or-
Object selectedObject = myComboBox.getSelectedItem();
-or-
String selectedValue = myComboBox.getSelectedValue().toString();
I was recently looking for this very same solution and managed to find a simple one without assigning specific variables for the last selected item and the new selected item. And this question, although very helpful, didn't provide the solution I needed. This solved my problem, I hope it solves yours and others. Thanks.
How do I get the previous or last item?
you can do this with jdk >= 8
getComboBox().addItemListener(this::comboBoxitemStateChanged);
so
public void comboBoxitemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
YourObject selectedItem = (YourObject) e.getItem();
//TODO your actitons
}
}
I use this:
cb = new JComboBox<String>();
cb.setBounds(10, 33, 46, 22);
panelConfig.add(cb);
for(int i = 0; i < 10; ++i)
{
cb.addItem(Integer.toString(i));
}
cb.addItemListener(new ItemListener()
{
#Override
public void itemStateChanged(ItemEvent e)
{
if(e.getID() == temEvent.ITEM_STATE_CHANGED)
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
JComboBox<String> cb = (JComboBox<String>) e.getSource();
String newSelection = (String) cb.getSelectedItem();
System.out.println("newSelection: " + newSelection);
}
}
}
});

Categories