I'm trying to build a form where one can fill in own's own values into a JTextField or rely a preset option which is depending on a selection from a JComboBox.
This is the JCombobox
String[] areas = new String [] {"Own Specifications", "SurveySample", "UK", "London", "Surrey"};
#SuppressWarnings({ "unchecked", "rawtypes" })
final JComboBox<String> selectedArea = new JComboBox(areas);
//selectedArea = new JComboBox<String>();
selectedArea.setModel(new DefaultComboBoxModel<String>(areas));
selectedArea.setBounds(282, 52, 164, 27);
contentPane.add(selectedArea);
And this is the JTextField
tenurePrivateRenters = new JTextField();
tenurePrivateRenters.setHorizontalAlignment(SwingConstants.CENTER);
tenurePrivateRenters.setText("Private Renters");
tenurePrivateRenters.setBounds(58, 213, 134, 28);
contentPane.add(tenurePrivateRenters);
Depending on the JComboBox Selection of the user, in a JTextField, the value is supposed to change, e.g. if Survey Sample is selected the JTextField should chance its value to 10.
I've tried the two following option:
selectedArea.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
Object selectedValue = selectedArea.getSelectedItem();
if(selectedValue.equals("Own Specifications")){
tenurePrivateRenters.setText("10");
System.out.println("Good choice!");
}
}
});
and
selectedArea.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e){
#SuppressWarnings("unchecked")
JComboBox<String> selectedArea = (JComboBox<String>) e.getSource();
String selectedItem = (String) selectedArea.getSelectedItem();
if(selectedItem.equals("Own Specifications")){
tenurePrivateRenters.setText("10");
System.out.println("Good choice!");
}
}
}
);
}
But for both options nothing happens and the value of the JTextField remains on "Private Renters". Any idea's on where I'm going wrong?
In your itemStateChanged method, you have the following:
Object selectedValue = selectedArea.getSelectedItem();
The getSelectedItem method returns an Object. Then, you call that Object's equals method:
if(selectedValue.equals("Own Specifications")){
This will certainly always return false because the Object equals method is comparing an object of type String to an object of type Object.
Instead, if you want to compare selectedValue to a String:
String selectedValue = (String)selectedArea.getSelectedItem();
Then, the if statement should work as expected.
I have tried your code and it worked perfectly. Are you sure you are properly attaching those listeners to combobox BEFORE you try to change its value? Try to attach them right in the constructor to be sure.
Related
Here is my code:
JComboBox unity=new JComboBox();
unity.setBounds(430,280,140,25);
unity.addItem("Pakistan");
unity.addItem("China");
unity.addItem("America");
unity.addItem("Japan");
unity.addItem("Bangladesh");
unity.addItem("Srilanka");
unity.addItem("India");
unity.addItem("Turkey");
unity.addItem("UK");
unity.addItem("Afghanistan");
unity.addItem("Iran");
unity.addItem("Iraq");
unity.setEditable(true);
uy.add(unity);
JLabel city=new JLabel("City:");
city.setBounds(350,320,100,25);
city.setForeground(Color.BLACK);
uy.add(city);
JComboBox cety=new JComboBox();
cety.setBounds(430,320,140,25);
cety.addItem("");
uy.add(cety);
unity.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent olala){
if(unity.getSelectedItem().equals("Pakistan")){
cety.addItem("Lahore");
cety.addItem("Islamabad");
cety.addItem("Karachi");
cety.addItem("Rawalpindi");
cety.addItem("Faisalabad");
cety.addItem("Gujjranwala");
}
}
});
But when i run the program,the block of if statement did not do anything.
What should I do,if I want to Load Values into JComboBox, depending on selection from another JComboBox?
Actually, if you choose "China" first, then "Pakistan" again, and click on the down arrow of the cety combobox, you'll see the items.
You can easily debug and see when the method is called by adding a println like so,
...
unity.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent olala) {
// DEBUG
System.out.println("itemStateChanged(): item = " + olala.getItem());
...
You'll notice that itemStateChanged is called when you select a different item. If you start the program and see the comboboxes for the first time, they haven't changed state yet, the method hasn't been called, and cety is empty. You could make unity change state, by adding
unity.setSelectedIndex(1);
unity.setSelectedIndex(0);
at the end of your code. Alternatively, you could just move all the unity.addItem lines to after the addItemListener so adding the first item to the list will trigger the event.
You'll need to clear the items before adding new ones, or selecting a couple of items in unity will result in a long list in cety. If you need an empty string in the list, you need to move that statement here as well,
...
public void itemStateChanged(ItemEvent olala){
cety.removeAllItems();
cety.addItem("");
if (unity.getSelectedItem().equals("Pakistan")) {
cety.addItem("Lahore");
...
You could then use a switch instead of a ton of if statements, get the item from the event instead of unity, and get rid of the raw types:
JComboBox<String> unity = new JComboBox<>();
unity.setBounds(430, 280, 140, 25);
unity.setEditable(true);
uy.add(unity);
JLabel city = new JLabel("City:");
city.setBounds(350, 320, 100, 25);
city.setForeground(Color.BLACK);
uy.add(city);
JComboBox<String> cety = new JComboBox<>();
cety.setBounds(430, 320, 140, 25);
uy.add(cety);
unity.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent event) {
cety.removeAllItems();
cety.addItem("");
switch (event.getItem().toString()) {
case "Pakistan":
cety.addItem("Lahore");
cety.addItem("Islamabad");
cety.addItem("Karachi");
cety.addItem("Rawalpindi");
cety.addItem("Faisalabad");
cety.addItem("Gujjranwala");
break;
case "China":
cety.addItem("Beijing");
break;
// ...
}
}
});
unity.addItem("Pakistan");
unity.addItem("China");
unity.addItem("America");
unity.addItem("Japan");
unity.addItem("Bangladesh");
unity.addItem("Srilanka");
unity.addItem("India");
unity.addItem("Turkey");
unity.addItem("UK");
unity.addItem("Afghanistan");
unity.addItem("Iran");
unity.addItem("Iraq");
// This would be a workaround if you don't want to move the addItems:
// unity.setSelectedIndex(1);
// unity.setSelectedIndex(0);
I created a JComboBox and JButton to submit information. I need the information to be sent to a different class to sort it out with a switch method. But it looks like the string created inside the ActionListener is not recognized by a different class.
public Main() {
final JComboBox comboB = new JComboBox(b); //add int b in here for array
comboB.setBounds(50, 30, 123, 20);
contentPane.add(comboB);
JButton btnTest = new JButton("Test");
btnTest.setBounds(300, 350, 89, 23);
contentPane.add(btnTest);
btnTest.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String s = (String)comboB.getSelectedItem();
}
});
}
How do I make it so that String s can be recognized by other classes? I have a separate class that will change action depending on what is selected from ComboBox, but I just can't seem to get this information out. Thank you.
Firstly, other objects need some way to register an ActionListener to the combo box. I would suggest providing a addActionListener method to your class, this would act as a proxy method and simple pass the call onto comboB
Secondly, this means comboB is going to need to be a class instance variable
Thirdly, the other classes are going to need to determine if the action originiated from the combo box or not, for example.
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JComboBox) {
JComboBox cb = (JComboBox)e.getSource();
String s = (String)cb.getSelectedItem();
}
}
Now, there's not a lot of context available to the question, but, personally, I would normally either use a model of some kind that your UI class would update and/or a PropertyChangeListener that other classes could register against and monitor for changes to the "properties" of the your main class.
You just need to create a private method and have the combo call that. Then you just navigate to your component/class, and perform the action.
public Main() {
final JComboBox comboB = new JComboBox(b); //add int b in here for array
comboB.setBounds(50, 30, 123, 20);
contentPane.add(comboB);
JButton btnTest = new JButton("Test");
btnTest.setBounds(300, 350, 89, 23);
contentPane.add(btnTest);
btnTest.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String s = (String)comboB.getSelectedItem();
myMethodThatProcessesS(s);
}
});
}
private void myMethodThatProcessesS(String s) {
contentPane.getSomeOtherComponent().doSOmething(s);
}
Since java swing implements the MVC pattern you can pass the JComboBox's model reference to other objects.
Models implement the observer pattern and therefore the other objects can register themself if they need to get notified immediatly when the model changes.
public class Main {
public initializeComponent(OtherClass otherClass) {
...
JComboBox comboBox = ...;
ComboBoxModel comboBoxModel = comboBox.getModel();
otherClass.setComboBoxModel(comboBoxModel);
}
}
public class OtherClass {
private ComboBoxModel comboBoxModel;
public void setComboBoxModel(ComboBoxModel comboBoxModel) {
this.comboBoxModel = comboBoxModel;
ListDataListener listener = ...;
comboBoxModel.addListDataListener(listener);
}
public String getSelectedItem(){
Object selectedItem = comboBoxModel.getSelectedItem();
...
}
}
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 am making a simple currency convertor which takes the initial value in a JTextField then the user clicks the JCheckBox corresponding to their desired currency, the converted value will then be displayed in another JTextField. Basically i would like to know is there any way of assigning a value to a checked JCheckBoxi have looked around and cannot find a clear answer to this, any help would be appreciated.
For example if the current conversion rate from Sterling to euro is 1.12244 this value would be assigned when the JCheckBox is checked, so the the original value would be multiplied by the conversion rate.
Think it'd be easier if you assign an action-listener to your JCheckBox and make the conversion on trigger of this event. To check is a JCheckBox is checked or not you can use the isSelected() method
EDIT
Actually i think you need to use JRadioButton's in a ButtonGroup for this, as if you are using a checkbox then there is a chance that more than one is selected. Here is an example of how to do use ButtonGroup and trigger action on the radio button
This would give you the value of the check box.
JCheckBox cb = ...;
// Determine status
boolean isSel = cb.isSelected();
if (isSel) {
// The checkbox is now selected
} else {
// The checkbox is now deselected
}
You can change the value on the action-listener of the JCheckBox
// Create an action
Action action = new AbstractAction("CheckBox Label") {
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action
JCheckBox cb = (JCheckBox)evt.getSource();
// Determine status
boolean isSel = cb.isSelected();
if (isSel) {
// The checkbox is now selected
} else {
// The checkbox is now deselected
}
}
};
// Create the checkbox
JCheckBox checkBox = new JCheckBox(action);
// this is whole working code i hope this this will help
public class CConvertor extends JFrame {
private JLabel result;
private JCheckBox pk;
private JCheckBox ch;
public CConvertor(){
result = new JLabel();
ch = new JCheckBox();
pk = new JCheckBox();
init();
}
public void init(){
setTitle("JCheckBox Test");
getContentPane().setLayout(new FlowLayout());
add(result);
add(new JLabel(" "));
add(new JLabel(" China "));
add(ch);
add(new JLabel(" Pakistan "));
add(pk);
setSize(400,80);
pk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ch.setSelected(false);
result.setText("Pakistan selected");
}
});
ch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pk.setSelected(false);
result.setText("China is Selected");
}
});
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new CConvertor();
}
}
This could not be the best solution but you can try this.
Take an array of JCheckBox.
Make sure only one checkbox gets selected at a time.
Take an array of currency conversion value.
Now based on the index of the selected checkbox get the currency conversion value from array.
Instead of using JCheckBox you can use JRadioButton as suggested by #Balanivash. More simpler and proper solution will be using JComboBox.[I'm with #Riduidel in this.]
I also think that JCheckBox isn't the best option to do what you want, however...
Why don't you extend the JCheckBox class to a CurrencyConverterCheckBox where you can
pass as arguments the currencies and the current value of the conversion.
e.g.:
public class CurrencyConverterCheckBox extends JCheckBox {
private String from;
private String to;
private double value;
public CurrencyConverterCheckBox(String from, String to, double value) {
super();
this.from = from;
this.to = to;
this.value = value;
}
}
Then you will be able to do the conversion when the user clicks the checkbox. You can also provide labels next to the checkboxes (USD to EUR). And you can also provide a method in your new checkbox to flip the currencies and calculate the multiplication factor in the other direction.
kind regards
What it's easiest to do is something like this:
String[] ccys = {"USD", "EUR", "CHF", "JPY"};
public void initUI(){
...
ButtonGroup grp = new ButtonGroup();
for(String ccy : ccys){
JCheckBox cb = new JCheckBox(ccy);
cb.setActionCommand(ccy);
cb.addActionListener(this);
grp.add(cb);
...(add CheckBox to ui)
}
}
private double getRate(String ccy){
...(retrieve the current conversion rate, f.ex from a map)
}
public void actionPerformed(ActionEvent evt){
Double rate = getRate(evt.getActionCommand());
...(calculation, display)
}
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);
}
}
}
});